blob: 42b09fd96dfbb968f68ef614120c4364249b087a [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Ammar Askare92d3932020-01-15 11:48:40 -050026#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Pablo Galindo90235812020-03-15 04:29:22 +000043#define IS_TOP_LEVEL_AWAIT(c) ( \
44 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
45 && (c->u->u_ste->ste_type == ModuleBlock))
46
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 /* b_return is true if a RETURN_VALUE opcode is inserted. */
71 unsigned b_return : 1;
Mark Shannon6e8128f2020-07-30 10:03:00 +010072 unsigned b_reachable : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 /* depth of stack upon entry of block, computed by stackdepth() */
74 int b_startdepth;
75 /* instruction offset for block, computed by assemble_jump_offsets() */
76 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077} basicblock;
78
79/* fblockinfo tracks the current frame block.
80
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081A frame block is used to handle loops, try/except, and try/finally.
82It's called a frame block to distinguish it from a basic block in the
83compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084*/
85
Mark Shannonfee55262019-11-21 09:11:43 +000086enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
87 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000088
89struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 enum fblocktype fb_type;
91 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020092 /* (optional) type-specific exit or cleanup block */
93 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000094 /* (optional) additional information required for unwinding */
95 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000096};
97
Antoine Pitrou86a36b52011-11-25 18:56:07 +010098enum {
99 COMPILER_SCOPE_MODULE,
100 COMPILER_SCOPE_CLASS,
101 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400102 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400103 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100104 COMPILER_SCOPE_COMPREHENSION,
105};
106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107/* The following items change on entry and exit of code blocks.
108 They must be saved and restored when returning to a block.
109*/
110struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400114 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100115 int u_scope_type;
116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 /* The following fields are dicts that map objects to
118 the index of them in co_XXX. The index is used as
119 the argument for opcodes that refer to those collections.
120 */
121 PyObject *u_consts; /* all constants */
122 PyObject *u_names; /* all names */
123 PyObject *u_varnames; /* local variables */
124 PyObject *u_cellvars; /* cell variables */
125 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100130 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100131 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 /* Pointer to the most recently allocated block. By following b_list
133 members, you can reach all early allocated blocks. */
134 basicblock *u_blocks;
135 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_nfblocks;
138 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 int u_firstlineno; /* the first lineno of the block */
141 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000142 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500182static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200196static int compiler_subscript(struct compiler *, expr_ty);
197static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Andy Lester76d58772020-03-10 21:18:12 -0500199static int inplace_binop(operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800200static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200201static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500203static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400204static int compiler_async_with(struct compiler *, stmt_ty, int);
205static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100206static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400208 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500209static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400210static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700212static int compiler_sync_comprehension_generator(
213 struct compiler *c,
214 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200215 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700216 expr_ty elt, expr_ty val, int type);
217
218static int compiler_async_comprehension_generator(
219 struct compiler *c,
220 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200221 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700222 expr_ty elt, expr_ty val, int type);
223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000225static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400227#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Name mangling: __private becomes _classname__private.
233 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 PyObject *result;
235 size_t nlen, plen, ipriv;
236 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 PyUnicode_READ_CHAR(ident, 0) != '_' ||
239 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 Py_INCREF(ident);
241 return ident;
242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 nlen = PyUnicode_GET_LENGTH(ident);
244 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 The only time a name with a dot can occur is when
248 we are compiling an import statement that has a
249 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 TODO(jhylton): Decide whether we want to support
252 mangling of the module name, e.g. __M.X.
253 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
255 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
256 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 Py_INCREF(ident);
258 return ident; /* Don't mangle __whatever__ */
259 }
260 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200261 ipriv = 0;
262 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
263 ipriv++;
264 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 Py_INCREF(ident);
266 return ident; /* Don't mangle if class is just underscores */
267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000269
Antoine Pitrou55bff892013-04-06 21:21:04 +0200270 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
271 PyErr_SetString(PyExc_OverflowError,
272 "private identifier too large to be mangled");
273 return NULL;
274 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
277 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
278 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
279
280 result = PyUnicode_New(1 + nlen + plen, maxchar);
281 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200283 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
284 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200285 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
286 Py_DECREF(result);
287 return NULL;
288 }
289 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
290 Py_DECREF(result);
291 return NULL;
292 }
Victor Stinner8f825062012-04-27 13:55:39 +0200293 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200294 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000295}
296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297static int
298compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000301
INADA Naokic2e16072018-11-26 21:23:22 +0900302 c->c_const_cache = PyDict_New();
303 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900305 }
306
307 c->c_stack = PyList_New(0);
308 if (!c->c_stack) {
309 Py_CLEAR(c->c_const_cache);
310 return 0;
311 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314}
315
316PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200317PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
318 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 struct compiler c;
321 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200322 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (!__doc__) {
326 __doc__ = PyUnicode_InternFromString("__doc__");
327 if (!__doc__)
328 return NULL;
329 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000330 if (!__annotations__) {
331 __annotations__ = PyUnicode_InternFromString("__annotations__");
332 if (!__annotations__)
333 return NULL;
334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (!compiler_init(&c))
336 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 c.c_filename = filename;
339 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200340 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (c.c_future == NULL)
342 goto finally;
343 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 flags = &local_flags;
345 }
346 merged = c.c_future->ff_features | flags->cf_flags;
347 c.c_future->ff_features = merged;
348 flags->cf_flags = merged;
349 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200350 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100352 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353
Pablo Galindod112c602020-03-18 23:02:09 +0000354 _PyASTOptimizeState state;
355 state.optimize = c.c_optimize;
356 state.ff_features = merged;
357
358 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900359 goto finally;
360 }
361
Victor Stinner14e461d2013-08-26 22:28:21 +0200362 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (c.c_st == NULL) {
364 if (!PyErr_Occurred())
365 PyErr_SetString(PyExc_SystemError, "no symtable");
366 goto finally;
367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
Thomas Wouters1175c432006-02-27 22:49:54 +0000371 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 compiler_free(&c);
373 assert(co || PyErr_Occurred());
374 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375}
376
377PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200378PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
379 int optimize, PyArena *arena)
380{
381 PyObject *filename;
382 PyCodeObject *co;
383 filename = PyUnicode_DecodeFSDefault(filename_str);
384 if (filename == NULL)
385 return NULL;
386 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
387 Py_DECREF(filename);
388 return co;
389
390}
391
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (c->c_st)
396 PySymtable_Free(c->c_st);
397 if (c->c_future)
398 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200399 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900400 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402}
403
Guido van Rossum79f25d91997-04-29 20:08:16 +0000404static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ssize_t i, n;
408 PyObject *v, *k;
409 PyObject *dict = PyDict_New();
410 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 n = PyList_Size(list);
413 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100414 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (!v) {
416 Py_DECREF(dict);
417 return NULL;
418 }
419 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300420 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_DECREF(v);
422 Py_DECREF(dict);
423 return NULL;
424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_DECREF(v);
426 }
427 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428}
429
430/* Return new dict containing names from src that match scope(s).
431
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000432src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000434values are integers, starting at offset and increasing by one for
435each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436*/
437
438static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100439dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000440{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700441 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500443 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 assert(offset >= 0);
446 if (dest == NULL)
447 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448
Meador Inge2ca63152012-07-18 14:20:11 -0500449 /* Sort the keys so that we have a deterministic order on the indexes
450 saved in the returned dictionary. These indexes are used as indexes
451 into the free and cell var storage. Therefore if they aren't
452 deterministic, then the generated bytecode is not deterministic.
453 */
454 sorted_keys = PyDict_Keys(src);
455 if (sorted_keys == NULL)
456 return NULL;
457 if (PyList_Sort(sorted_keys) != 0) {
458 Py_DECREF(sorted_keys);
459 return NULL;
460 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500461 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500462
463 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* XXX this should probably be a macro in symtable.h */
465 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500466 k = PyList_GET_ITEM(sorted_keys, key_i);
467 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 assert(PyLong_Check(v));
469 vi = PyLong_AS_LONG(v);
470 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300473 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(dest);
477 return NULL;
478 }
479 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_DECREF(item);
483 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return NULL;
485 }
486 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
488 }
Meador Inge2ca63152012-07-18 14:20:11 -0500489 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000491}
492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493static void
494compiler_unit_check(struct compiler_unit *u)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 basicblock *block;
497 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700498 assert((uintptr_t)block != 0xcbcbcbcbU);
499 assert((uintptr_t)block != 0xfbfbfbfbU);
500 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (block->b_instr != NULL) {
502 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100503 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 assert(block->b_ialloc >= block->b_iused);
505 }
506 else {
507 assert (block->b_iused == 0);
508 assert (block->b_ialloc == 0);
509 }
510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511}
512
513static void
514compiler_unit_free(struct compiler_unit *u)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 compiler_unit_check(u);
519 b = u->u_blocks;
520 while (b != NULL) {
521 if (b->b_instr)
522 PyObject_Free((void *)b->b_instr);
523 next = b->b_list;
524 PyObject_Free((void *)b);
525 b = next;
526 }
527 Py_CLEAR(u->u_ste);
528 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400529 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_CLEAR(u->u_consts);
531 Py_CLEAR(u->u_names);
532 Py_CLEAR(u->u_varnames);
533 Py_CLEAR(u->u_freevars);
534 Py_CLEAR(u->u_cellvars);
535 Py_CLEAR(u->u_private);
536 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537}
538
539static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100540compiler_enter_scope(struct compiler *c, identifier name,
541 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100544 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Andy Lester7668a8b2020-03-24 23:26:44 -0500546 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 struct compiler_unit));
548 if (!u) {
549 PyErr_NoMemory();
550 return 0;
551 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100552 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100554 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 u->u_kwonlyargcount = 0;
556 u->u_ste = PySymtable_Lookup(c->c_st, key);
557 if (!u->u_ste) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 Py_INCREF(name);
562 u->u_name = name;
563 u->u_varnames = list2dict(u->u_ste->ste_varnames);
564 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
565 if (!u->u_varnames || !u->u_cellvars) {
566 compiler_unit_free(u);
567 return 0;
568 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000570 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300572 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 int res;
574 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200575 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500576 name = _PyUnicode_FromId(&PyId___class__);
577 if (!name) {
578 compiler_unit_free(u);
579 return 0;
580 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300581 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 if (res < 0) {
583 compiler_unit_free(u);
584 return 0;
585 }
586 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200589 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (!u->u_freevars) {
591 compiler_unit_free(u);
592 return 0;
593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_blocks = NULL;
596 u->u_nfblocks = 0;
597 u->u_firstlineno = lineno;
598 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000599 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_consts = PyDict_New();
601 if (!u->u_consts) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 u->u_names = PyDict_New();
606 if (!u->u_names) {
607 compiler_unit_free(u);
608 return 0;
609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Push the old compiler_unit on the stack. */
614 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400615 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
617 Py_XDECREF(capsule);
618 compiler_unit_free(u);
619 return 0;
620 }
621 Py_DECREF(capsule);
622 u->u_private = c->u->u_private;
623 Py_XINCREF(u->u_private);
624 }
625 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100628
629 block = compiler_new_block(c);
630 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100632 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400634 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
635 if (!compiler_set_qualname(c))
636 return 0;
637 }
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640}
641
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643compiler_exit_scope(struct compiler *c)
644{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100645 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 c->c_nestlevel--;
649 compiler_unit_free(c->u);
650 /* Restore c->u to the parent unit. */
651 n = PyList_GET_SIZE(c->c_stack) - 1;
652 if (n >= 0) {
653 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400654 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 assert(c->u);
656 /* we are deleting from a list so this really shouldn't fail */
657 if (PySequence_DelItem(c->c_stack, n) < 0)
658 Py_FatalError("compiler_exit_scope()");
659 compiler_unit_check(c->u);
660 }
661 else
662 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400666static int
667compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400670 _Py_static_string(dot_locals, ".<locals>");
671 Py_ssize_t stack_size;
672 struct compiler_unit *u = c->u;
673 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400675 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100676 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400677 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 if (stack_size > 1) {
679 int scope, force_global = 0;
680 struct compiler_unit *parent;
681 PyObject *mangled, *capsule;
682
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400683 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 assert(parent);
686
Yury Selivanov75445082015-05-11 22:57:16 -0400687 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 assert(u->u_name);
691 mangled = _Py_Mangle(parent->u_private, u->u_name);
692 if (!mangled)
693 return 0;
694 scope = PyST_GetScope(parent->u_ste, mangled);
695 Py_DECREF(mangled);
696 assert(scope != GLOBAL_IMPLICIT);
697 if (scope == GLOBAL_EXPLICIT)
698 force_global = 1;
699 }
700
701 if (!force_global) {
702 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400703 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
705 dot_locals_str = _PyUnicode_FromId(&dot_locals);
706 if (dot_locals_str == NULL)
707 return 0;
708 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
709 if (base == NULL)
710 return 0;
711 }
712 else {
713 Py_INCREF(parent->u_qualname);
714 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400715 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100716 }
717 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 if (base != NULL) {
720 dot_str = _PyUnicode_FromId(&dot);
721 if (dot_str == NULL) {
722 Py_DECREF(base);
723 return 0;
724 }
725 name = PyUnicode_Concat(base, dot_str);
726 Py_DECREF(base);
727 if (name == NULL)
728 return 0;
729 PyUnicode_Append(&name, u->u_name);
730 if (name == NULL)
731 return 0;
732 }
733 else {
734 Py_INCREF(u->u_name);
735 name = u->u_name;
736 }
737 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100738
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400739 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740}
741
Eric V. Smith235a6f02015-09-19 14:51:32 -0400742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743/* Allocate a new block and return a pointer to it.
744 Returns NULL on error.
745*/
746
747static basicblock *
748compiler_new_block(struct compiler *c)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 basicblock *b;
751 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500754 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (b == NULL) {
756 PyErr_NoMemory();
757 return NULL;
758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* Extend the singly linked list of blocks with new block. */
760 b->b_list = u->u_blocks;
761 u->u_blocks = b;
762 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
Andy Lester76d58772020-03-10 21:18:12 -0500791compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500795 b->b_instr = (struct instr *)PyObject_Calloc(
796 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
803 else if (b->b_iused == b->b_ialloc) {
804 struct instr *tmp;
805 size_t oldsize, newsize;
806 oldsize = b->b_ialloc * sizeof(struct instr);
807 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000808
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700809 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyErr_NoMemory();
811 return -1;
812 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (newsize == 0) {
815 PyErr_NoMemory();
816 return -1;
817 }
818 b->b_ialloc <<= 1;
819 tmp = (struct instr *)PyObject_Realloc(
820 (void *)b->b_instr, newsize);
821 if (tmp == NULL) {
822 PyErr_NoMemory();
823 return -1;
824 }
825 b->b_instr = tmp;
826 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
827 }
828 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000829}
830
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200831/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000832
Christian Heimes2202f872008-02-06 14:31:34 +0000833 The line number is reset in the following cases:
834 - when entering a new scope
835 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200836 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200837 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200840#define SET_LOC(c, x) \
841 (c)->u->u_lineno = (x)->lineno; \
842 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200844/* Return the stack effect of opcode with argument oparg.
845
846 Some opcodes have different stack effect when jump to the target and
847 when not jump. The 'jump' parameter specifies the case:
848
849 * 0 -- when not jump
850 * 1 -- when jump
851 * -1 -- maximal
852 */
853/* XXX Make the stack effect of WITH_CLEANUP_START and
854 WITH_CLEANUP_FINISH deterministic. */
855static int
856stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300859 case NOP:
860 case EXTENDED_ARG:
861 return 0;
862
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200863 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 case POP_TOP:
865 return -1;
866 case ROT_TWO:
867 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200868 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return 0;
870 case DUP_TOP:
871 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000872 case DUP_TOP_TWO:
873 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000874
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200875 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case UNARY_POSITIVE:
877 case UNARY_NEGATIVE:
878 case UNARY_NOT:
879 case UNARY_INVERT:
880 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case SET_ADD:
883 case LIST_APPEND:
884 return -1;
885 case MAP_ADD:
886 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case BINARY_POWER:
890 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400891 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case BINARY_MODULO:
893 case BINARY_ADD:
894 case BINARY_SUBTRACT:
895 case BINARY_SUBSCR:
896 case BINARY_FLOOR_DIVIDE:
897 case BINARY_TRUE_DIVIDE:
898 return -1;
899 case INPLACE_FLOOR_DIVIDE:
900 case INPLACE_TRUE_DIVIDE:
901 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case INPLACE_ADD:
904 case INPLACE_SUBTRACT:
905 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400906 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case INPLACE_MODULO:
908 return -1;
909 case STORE_SUBSCR:
910 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case DELETE_SUBSCR:
912 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_LSHIFT:
915 case BINARY_RSHIFT:
916 case BINARY_AND:
917 case BINARY_XOR:
918 case BINARY_OR:
919 return -1;
920 case INPLACE_POWER:
921 return -1;
922 case GET_ITER:
923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case PRINT_EXPR:
926 return -1;
927 case LOAD_BUILD_CLASS:
928 return 1;
929 case INPLACE_LSHIFT:
930 case INPLACE_RSHIFT:
931 case INPLACE_AND:
932 case INPLACE_XOR:
933 case INPLACE_OR:
934 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200937 /* 1 in the normal flow.
938 * Restore the stack position and push 6 values before jumping to
939 * the handler if an exception be raised. */
940 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case RETURN_VALUE:
942 return -1;
943 case IMPORT_STAR:
944 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700945 case SETUP_ANNOTATIONS:
946 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case YIELD_VALUE:
948 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500949 case YIELD_FROM:
950 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 case POP_BLOCK:
952 return 0;
953 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200954 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case STORE_NAME:
957 return -1;
958 case DELETE_NAME:
959 return 0;
960 case UNPACK_SEQUENCE:
961 return oparg-1;
962 case UNPACK_EX:
963 return (oparg&0xFF) + (oparg>>8);
964 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200965 /* -1 at end of iterator, 1 if continue iterating. */
966 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case STORE_ATTR:
969 return -2;
970 case DELETE_ATTR:
971 return -1;
972 case STORE_GLOBAL:
973 return -1;
974 case DELETE_GLOBAL:
975 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case LOAD_CONST:
977 return 1;
978 case LOAD_NAME:
979 return 1;
980 case BUILD_TUPLE:
981 case BUILD_LIST:
982 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300983 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return 1-oparg;
985 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700986 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300987 case BUILD_CONST_KEY_MAP:
988 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case LOAD_ATTR:
990 return 0;
991 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +0000992 case IS_OP:
993 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +0000995 case JUMP_IF_NOT_EXC_MATCH:
996 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case IMPORT_NAME:
998 return -1;
999 case IMPORT_FROM:
1000 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001002 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case JUMP_ABSOLUTE:
1005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001007 case JUMP_IF_TRUE_OR_POP:
1008 case JUMP_IF_FALSE_OR_POP:
1009 return jump ? 0 : -1;
1010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case POP_JUMP_IF_FALSE:
1012 case POP_JUMP_IF_TRUE:
1013 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case LOAD_GLOBAL:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001018 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001020 /* 0 in the normal flow.
1021 * Restore the stack position and push 6 values before jumping to
1022 * the handler if an exception be raised. */
1023 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001024 case RERAISE:
1025 return -3;
1026
1027 case WITH_EXCEPT_START:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case LOAD_FAST:
1031 return 1;
1032 case STORE_FAST:
1033 return -1;
1034 case DELETE_FAST:
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case RAISE_VARARGS:
1038 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001039
1040 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001042 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001043 case CALL_METHOD:
1044 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001046 return -oparg-1;
1047 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001048 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001049 case MAKE_FUNCTION:
1050 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1051 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case BUILD_SLICE:
1053 if (oparg == 3)
1054 return -2;
1055 else
1056 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001058 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case LOAD_CLOSURE:
1060 return 1;
1061 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001062 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 return 1;
1064 case STORE_DEREF:
1065 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001066 case DELETE_DEREF:
1067 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001068
1069 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001070 case GET_AWAITABLE:
1071 return 0;
1072 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001073 /* 0 in the normal flow.
1074 * Restore the stack position to the position before the result
1075 * of __aenter__ and push 6 values before jumping to the handler
1076 * if an exception be raised. */
1077 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001078 case BEFORE_ASYNC_WITH:
1079 return 1;
1080 case GET_AITER:
1081 return 0;
1082 case GET_ANEXT:
1083 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001084 case GET_YIELD_FROM_ITER:
1085 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001086 case END_ASYNC_FOR:
1087 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001088 case FORMAT_VALUE:
1089 /* If there's a fmt_spec on the stack, we go from 2->1,
1090 else 1->1. */
1091 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001092 case LOAD_METHOD:
1093 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001094 case LOAD_ASSERTION_ERROR:
1095 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001096 case LIST_TO_TUPLE:
1097 return 0;
1098 case LIST_EXTEND:
1099 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001100 case DICT_MERGE:
1101 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001102 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001104 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 }
Larry Hastings3a907972013-11-23 14:49:22 -08001106 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107}
1108
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001109int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001110PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1111{
1112 return stack_effect(opcode, oparg, jump);
1113}
1114
1115int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001116PyCompile_OpcodeStackEffect(int opcode, int oparg)
1117{
1118 return stack_effect(opcode, oparg, -1);
1119}
1120
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121/* Add an opcode with no argument.
1122 Returns 0 on failure, 1 on success.
1123*/
1124
1125static int
1126compiler_addop(struct compiler *c, int opcode)
1127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 basicblock *b;
1129 struct instr *i;
1130 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001131 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001132 if (c->c_do_not_emit_bytecode) {
1133 return 1;
1134 }
Andy Lester76d58772020-03-10 21:18:12 -05001135 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (off < 0)
1137 return 0;
1138 b = c->u->u_curblock;
1139 i = &b->b_instr[off];
1140 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001141 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (opcode == RETURN_VALUE)
1143 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001144 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146}
1147
Victor Stinnerf8e32212013-11-19 23:56:34 +01001148static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001149compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001151 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001154 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001156 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001158 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001159 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001160 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return -1;
1163 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001164 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 Py_DECREF(v);
1166 return -1;
1167 }
1168 Py_DECREF(v);
1169 }
1170 else
1171 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 return arg;
1173}
1174
INADA Naokic2e16072018-11-26 21:23:22 +09001175// Merge const *o* recursively and return constant key object.
1176static PyObject*
1177merge_consts_recursive(struct compiler *c, PyObject *o)
1178{
1179 // None and Ellipsis are singleton, and key is the singleton.
1180 // No need to merge object and key.
1181 if (o == Py_None || o == Py_Ellipsis) {
1182 Py_INCREF(o);
1183 return o;
1184 }
1185
1186 PyObject *key = _PyCode_ConstantKey(o);
1187 if (key == NULL) {
1188 return NULL;
1189 }
1190
1191 // t is borrowed reference
1192 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1193 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001194 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001195 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001196 Py_DECREF(key);
1197 return t;
1198 }
1199
INADA Naokif7e4d362018-11-29 00:58:46 +09001200 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001201 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001202 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001203 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001204 Py_ssize_t len = PyTuple_GET_SIZE(o);
1205 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001206 PyObject *item = PyTuple_GET_ITEM(o, i);
1207 PyObject *u = merge_consts_recursive(c, item);
1208 if (u == NULL) {
1209 Py_DECREF(key);
1210 return NULL;
1211 }
1212
1213 // See _PyCode_ConstantKey()
1214 PyObject *v; // borrowed
1215 if (PyTuple_CheckExact(u)) {
1216 v = PyTuple_GET_ITEM(u, 1);
1217 }
1218 else {
1219 v = u;
1220 }
1221 if (v != item) {
1222 Py_INCREF(v);
1223 PyTuple_SET_ITEM(o, i, v);
1224 Py_DECREF(item);
1225 }
1226
1227 Py_DECREF(u);
1228 }
1229 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001230 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001231 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001232 // constant keys.
1233 // See _PyCode_ConstantKey() for detail.
1234 assert(PyTuple_CheckExact(key));
1235 assert(PyTuple_GET_SIZE(key) == 2);
1236
1237 Py_ssize_t len = PySet_GET_SIZE(o);
1238 if (len == 0) { // empty frozenset should not be re-created.
1239 return key;
1240 }
1241 PyObject *tuple = PyTuple_New(len);
1242 if (tuple == NULL) {
1243 Py_DECREF(key);
1244 return NULL;
1245 }
1246 Py_ssize_t i = 0, pos = 0;
1247 PyObject *item;
1248 Py_hash_t hash;
1249 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1250 PyObject *k = merge_consts_recursive(c, item);
1251 if (k == NULL) {
1252 Py_DECREF(tuple);
1253 Py_DECREF(key);
1254 return NULL;
1255 }
1256 PyObject *u;
1257 if (PyTuple_CheckExact(k)) {
1258 u = PyTuple_GET_ITEM(k, 1);
1259 Py_INCREF(u);
1260 Py_DECREF(k);
1261 }
1262 else {
1263 u = k;
1264 }
1265 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1266 i++;
1267 }
1268
1269 // Instead of rewriting o, we create new frozenset and embed in the
1270 // key tuple. Caller should get merged frozenset from the key tuple.
1271 PyObject *new = PyFrozenSet_New(tuple);
1272 Py_DECREF(tuple);
1273 if (new == NULL) {
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 assert(PyTuple_GET_ITEM(key, 1) == o);
1278 Py_DECREF(o);
1279 PyTuple_SET_ITEM(key, 1, new);
1280 }
INADA Naokic2e16072018-11-26 21:23:22 +09001281
1282 return key;
1283}
1284
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001285static Py_ssize_t
1286compiler_add_const(struct compiler *c, PyObject *o)
1287{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001288 if (c->c_do_not_emit_bytecode) {
1289 return 0;
1290 }
1291
INADA Naokic2e16072018-11-26 21:23:22 +09001292 PyObject *key = merge_consts_recursive(c, o);
1293 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001294 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001295 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001296
Andy Lester76d58772020-03-10 21:18:12 -05001297 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001298 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300}
1301
1302static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001303compiler_addop_load_const(struct compiler *c, PyObject *o)
1304{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001305 if (c->c_do_not_emit_bytecode) {
1306 return 1;
1307 }
1308
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001309 Py_ssize_t arg = compiler_add_const(c, o);
1310 if (arg < 0)
1311 return 0;
1312 return compiler_addop_i(c, LOAD_CONST, arg);
1313}
1314
1315static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001319 if (c->c_do_not_emit_bytecode) {
1320 return 1;
1321 }
1322
Andy Lester76d58772020-03-10 21:18:12 -05001323 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 return compiler_addop_i(c, opcode, arg);
1327}
1328
1329static int
1330compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001333 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001334
1335 if (c->c_do_not_emit_bytecode) {
1336 return 1;
1337 }
1338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1340 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001341 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001342 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343 Py_DECREF(mangled);
1344 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 return compiler_addop_i(c, opcode, arg);
1347}
1348
1349/* Add an opcode with an integer argument.
1350 Returns 0 on failure, 1 on success.
1351*/
1352
1353static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001354compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 struct instr *i;
1357 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001359 if (c->c_do_not_emit_bytecode) {
1360 return 1;
1361 }
1362
Victor Stinner2ad474b2016-03-01 23:34:47 +01001363 /* oparg value is unsigned, but a signed C int is usually used to store
1364 it in the C code (like Python/ceval.c).
1365
1366 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1367
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001368 The argument of a concrete bytecode instruction is limited to 8-bit.
1369 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1370 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001371 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001372
Andy Lester76d58772020-03-10 21:18:12 -05001373 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (off < 0)
1375 return 0;
1376 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001377 i->i_opcode = opcode;
1378 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001379 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381}
1382
1383static int
1384compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 struct instr *i;
1387 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001389 if (c->c_do_not_emit_bytecode) {
1390 return 1;
1391 }
1392
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001393 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001395 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (off < 0)
1397 return 0;
1398 i = &c->u->u_curblock->b_instr[off];
1399 i->i_opcode = opcode;
1400 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (absolute)
1402 i->i_jabs = 1;
1403 else
1404 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001405 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407}
1408
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001409/* NEXT_BLOCK() creates an implicit jump from the current block
1410 to the new block.
1411
1412 The returns inside this macro make it impossible to decref objects
1413 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (compiler_next_block((C)) == NULL) \
1417 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418}
1419
1420#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (!compiler_addop((C), (OP))) \
1422 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423}
1424
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001425#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (!compiler_addop((C), (OP))) { \
1427 compiler_exit_scope(c); \
1428 return 0; \
1429 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001430}
1431
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001432#define ADDOP_LOAD_CONST(C, O) { \
1433 if (!compiler_addop_load_const((C), (O))) \
1434 return 0; \
1435}
1436
1437/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1438#define ADDOP_LOAD_CONST_NEW(C, O) { \
1439 PyObject *__new_const = (O); \
1440 if (__new_const == NULL) { \
1441 return 0; \
1442 } \
1443 if (!compiler_addop_load_const((C), __new_const)) { \
1444 Py_DECREF(__new_const); \
1445 return 0; \
1446 } \
1447 Py_DECREF(__new_const); \
1448}
1449
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1452 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453}
1454
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001455/* Same as ADDOP_O, but steals a reference. */
1456#define ADDOP_N(C, OP, O, TYPE) { \
1457 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1458 Py_DECREF((O)); \
1459 return 0; \
1460 } \
1461 Py_DECREF((O)); \
1462}
1463
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1466 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467}
1468
1469#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!compiler_addop_i((C), (OP), (O))) \
1471 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472}
1473
1474#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (!compiler_addop_j((C), (OP), (O), 1)) \
1476 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477}
1478
1479#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (!compiler_addop_j((C), (OP), (O), 0)) \
1481 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482}
1483
Mark Shannon9af0e472020-01-14 10:12:45 +00001484
1485#define ADDOP_COMPARE(C, CMP) { \
1486 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1487 return 0; \
1488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1491 the ASDL name to synthesize the name of the C type and the visit function.
1492*/
1493
1494#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 if (!compiler_visit_ ## TYPE((C), (V))) \
1496 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497}
1498
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001499#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!compiler_visit_ ## TYPE((C), (V))) { \
1501 compiler_exit_scope(c); \
1502 return 0; \
1503 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001504}
1505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (!compiler_visit_slice((C), (V), (CTX))) \
1508 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509}
1510
1511#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 int _i; \
1513 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1514 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1515 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1516 if (!compiler_visit_ ## TYPE((C), elt)) \
1517 return 0; \
1518 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001521#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 int _i; \
1523 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1524 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1525 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1526 if (!compiler_visit_ ## TYPE((C), elt)) { \
1527 compiler_exit_scope(c); \
1528 return 0; \
1529 } \
1530 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001531}
1532
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001533/* These macros allows to check only for errors and not emmit bytecode
1534 * while visiting nodes.
1535*/
1536
1537#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1538 c->c_do_not_emit_bytecode++;
1539
1540#define END_DO_NOT_EMIT_BYTECODE \
1541 c->c_do_not_emit_bytecode--; \
1542}
1543
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001544/* Search if variable annotations are present statically in a block. */
1545
1546static int
1547find_ann(asdl_seq *stmts)
1548{
1549 int i, j, res = 0;
1550 stmt_ty st;
1551
1552 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1553 st = (stmt_ty)asdl_seq_GET(stmts, i);
1554 switch (st->kind) {
1555 case AnnAssign_kind:
1556 return 1;
1557 case For_kind:
1558 res = find_ann(st->v.For.body) ||
1559 find_ann(st->v.For.orelse);
1560 break;
1561 case AsyncFor_kind:
1562 res = find_ann(st->v.AsyncFor.body) ||
1563 find_ann(st->v.AsyncFor.orelse);
1564 break;
1565 case While_kind:
1566 res = find_ann(st->v.While.body) ||
1567 find_ann(st->v.While.orelse);
1568 break;
1569 case If_kind:
1570 res = find_ann(st->v.If.body) ||
1571 find_ann(st->v.If.orelse);
1572 break;
1573 case With_kind:
1574 res = find_ann(st->v.With.body);
1575 break;
1576 case AsyncWith_kind:
1577 res = find_ann(st->v.AsyncWith.body);
1578 break;
1579 case Try_kind:
1580 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1581 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1582 st->v.Try.handlers, j);
1583 if (find_ann(handler->v.ExceptHandler.body)) {
1584 return 1;
1585 }
1586 }
1587 res = find_ann(st->v.Try.body) ||
1588 find_ann(st->v.Try.finalbody) ||
1589 find_ann(st->v.Try.orelse);
1590 break;
1591 default:
1592 res = 0;
1593 }
1594 if (res) {
1595 break;
1596 }
1597 }
1598 return res;
1599}
1600
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001601/*
1602 * Frame block handling functions
1603 */
1604
1605static int
1606compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001607 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001608{
1609 struct fblockinfo *f;
1610 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1611 PyErr_SetString(PyExc_SyntaxError,
1612 "too many statically nested blocks");
1613 return 0;
1614 }
1615 f = &c->u->u_fblock[c->u->u_nfblocks++];
1616 f->fb_type = t;
1617 f->fb_block = b;
1618 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001619 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001620 return 1;
1621}
1622
1623static void
1624compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1625{
1626 struct compiler_unit *u = c->u;
1627 assert(u->u_nfblocks > 0);
1628 u->u_nfblocks--;
1629 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1630 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1631}
1632
Mark Shannonfee55262019-11-21 09:11:43 +00001633static int
1634compiler_call_exit_with_nones(struct compiler *c) {
1635 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1636 ADDOP(c, DUP_TOP);
1637 ADDOP(c, DUP_TOP);
1638 ADDOP_I(c, CALL_FUNCTION, 3);
1639 return 1;
1640}
1641
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001642/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001643 * popping the blocks will be restored afterwards, unless another
1644 * return, break or continue is found. In which case, the TOS will
1645 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001646 */
1647static int
1648compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1649 int preserve_tos)
1650{
1651 switch (info->fb_type) {
1652 case WHILE_LOOP:
1653 return 1;
1654
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001655 case FOR_LOOP:
1656 /* Pop the iterator */
1657 if (preserve_tos) {
1658 ADDOP(c, ROT_TWO);
1659 }
1660 ADDOP(c, POP_TOP);
1661 return 1;
1662
1663 case EXCEPT:
1664 ADDOP(c, POP_BLOCK);
1665 return 1;
1666
1667 case FINALLY_TRY:
1668 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001669 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001670 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1671 return 0;
1672 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001673 }
Mark Shannon88dce262019-12-30 09:53:36 +00001674 /* Emit the finally block, restoring the line number when done */
1675 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001676 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001677 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001678 if (preserve_tos) {
1679 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001680 }
1681 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001682
Mark Shannonfee55262019-11-21 09:11:43 +00001683 case FINALLY_END:
1684 if (preserve_tos) {
1685 ADDOP(c, ROT_FOUR);
1686 }
1687 ADDOP(c, POP_TOP);
1688 ADDOP(c, POP_TOP);
1689 ADDOP(c, POP_TOP);
1690 if (preserve_tos) {
1691 ADDOP(c, ROT_FOUR);
1692 }
1693 ADDOP(c, POP_EXCEPT);
1694 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001695
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001696 case WITH:
1697 case ASYNC_WITH:
1698 ADDOP(c, POP_BLOCK);
1699 if (preserve_tos) {
1700 ADDOP(c, ROT_TWO);
1701 }
Mark Shannonfee55262019-11-21 09:11:43 +00001702 if(!compiler_call_exit_with_nones(c)) {
1703 return 0;
1704 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001705 if (info->fb_type == ASYNC_WITH) {
1706 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001707 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001708 ADDOP(c, YIELD_FROM);
1709 }
Mark Shannonfee55262019-11-21 09:11:43 +00001710 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001711 return 1;
1712
1713 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001714 if (info->fb_datum) {
1715 ADDOP(c, POP_BLOCK);
1716 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001717 if (preserve_tos) {
1718 ADDOP(c, ROT_FOUR);
1719 }
Mark Shannonfee55262019-11-21 09:11:43 +00001720 ADDOP(c, POP_EXCEPT);
1721 if (info->fb_datum) {
1722 ADDOP_LOAD_CONST(c, Py_None);
1723 compiler_nameop(c, info->fb_datum, Store);
1724 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001725 }
Mark Shannonfee55262019-11-21 09:11:43 +00001726 return 1;
1727
1728 case POP_VALUE:
1729 if (preserve_tos) {
1730 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001731 }
Mark Shannonfee55262019-11-21 09:11:43 +00001732 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 return 1;
1734 }
1735 Py_UNREACHABLE();
1736}
1737
Mark Shannonfee55262019-11-21 09:11:43 +00001738/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1739static int
1740compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1741 if (c->u->u_nfblocks == 0) {
1742 return 1;
1743 }
1744 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1745 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1746 *loop = top;
1747 return 1;
1748 }
1749 struct fblockinfo copy = *top;
1750 c->u->u_nfblocks--;
1751 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1752 return 0;
1753 }
1754 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1755 return 0;
1756 }
1757 c->u->u_fblock[c->u->u_nfblocks] = copy;
1758 c->u->u_nfblocks++;
1759 return 1;
1760}
1761
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001762/* Compile a sequence of statements, checking for a docstring
1763 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764
1765static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001766compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001767{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001768 int i = 0;
1769 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001770 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001771
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001772 /* Set current line number to the line number of first statement.
1773 This way line number for SETUP_ANNOTATIONS will always
1774 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301775 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001776 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001777 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001778 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001779 }
1780 /* Every annotated class and module should have __annotations__. */
1781 if (find_ann(stmts)) {
1782 ADDOP(c, SETUP_ANNOTATIONS);
1783 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001784 if (!asdl_seq_LEN(stmts))
1785 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001786 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001787 if (c->c_optimize < 2) {
1788 docstring = _PyAST_GetDocString(stmts);
1789 if (docstring) {
1790 i = 1;
1791 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1792 assert(st->kind == Expr_kind);
1793 VISIT(c, expr, st->v.Expr.value);
1794 if (!compiler_nameop(c, __doc__, Store))
1795 return 0;
1796 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001798 for (; i < asdl_seq_LEN(stmts); i++)
1799 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801}
1802
1803static PyCodeObject *
1804compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyCodeObject *co;
1807 int addNone = 1;
1808 static PyObject *module;
1809 if (!module) {
1810 module = PyUnicode_InternFromString("<module>");
1811 if (!module)
1812 return NULL;
1813 }
1814 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001815 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return NULL;
1817 switch (mod->kind) {
1818 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001819 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 compiler_exit_scope(c);
1821 return 0;
1822 }
1823 break;
1824 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001825 if (find_ann(mod->v.Interactive.body)) {
1826 ADDOP(c, SETUP_ANNOTATIONS);
1827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 c->c_interactive = 1;
1829 VISIT_SEQ_IN_SCOPE(c, stmt,
1830 mod->v.Interactive.body);
1831 break;
1832 case Expression_kind:
1833 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1834 addNone = 0;
1835 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 default:
1837 PyErr_Format(PyExc_SystemError,
1838 "module kind %d should not be possible",
1839 mod->kind);
1840 return 0;
1841 }
1842 co = assemble(c, addNone);
1843 compiler_exit_scope(c);
1844 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001845}
1846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847/* The test for LOCAL must come before the test for FREE in order to
1848 handle classes where name is both local and free. The local var is
1849 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001850*/
1851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852static int
1853get_ref_type(struct compiler *c, PyObject *name)
1854{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001855 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001856 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001857 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001858 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001859 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001861 _Py_FatalErrorFormat(__func__,
1862 "unknown scope for %.100s in %.100s(%s)\n"
1863 "symbols: %s\nlocals: %s\nglobals: %s",
1864 PyUnicode_AsUTF8(name),
1865 PyUnicode_AsUTF8(c->u->u_name),
1866 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1867 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1868 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1869 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873}
1874
1875static int
1876compiler_lookup_arg(PyObject *dict, PyObject *name)
1877{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001878 PyObject *v;
1879 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001881 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001882 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883}
1884
1885static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001886compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001888 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001889 if (qualname == NULL)
1890 qualname = co->co_name;
1891
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001892 if (free) {
1893 for (i = 0; i < free; ++i) {
1894 /* Bypass com_addop_varname because it will generate
1895 LOAD_DEREF but LOAD_CLOSURE is needed.
1896 */
1897 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1898 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001900 /* Special case: If a class contains a method with a
1901 free variable that has the same name as a method,
1902 the name will be considered free *and* local in the
1903 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001904 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001905 */
1906 reftype = get_ref_type(c, name);
1907 if (reftype == CELL)
1908 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1909 else /* (reftype == FREE) */
1910 arg = compiler_lookup_arg(c->u->u_freevars, name);
1911 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001912 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 "lookup %s in %s %d %d\n"
1914 "freevars of %s: %s\n",
1915 PyUnicode_AsUTF8(PyObject_Repr(name)),
1916 PyUnicode_AsUTF8(c->u->u_name),
1917 reftype, arg,
1918 PyUnicode_AsUTF8(co->co_name),
1919 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001920 }
1921 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001923 flags |= 0x08;
1924 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001926 ADDOP_LOAD_CONST(c, (PyObject*)co);
1927 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930}
1931
1932static int
1933compiler_decorators(struct compiler *c, asdl_seq* decos)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 if (!decos)
1938 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1941 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1942 }
1943 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944}
1945
1946static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001947compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001949{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001950 /* Push a dict of keyword-only default values.
1951
1952 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1953 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001954 int i;
1955 PyObject *keys = NULL;
1956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1958 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1959 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1960 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001961 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001962 if (!mangled) {
1963 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 if (keys == NULL) {
1966 keys = PyList_New(1);
1967 if (keys == NULL) {
1968 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001969 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001970 }
1971 PyList_SET_ITEM(keys, 0, mangled);
1972 }
1973 else {
1974 int res = PyList_Append(keys, mangled);
1975 Py_DECREF(mangled);
1976 if (res == -1) {
1977 goto error;
1978 }
1979 }
1980 if (!compiler_visit_expr(c, default_)) {
1981 goto error;
1982 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 }
1984 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985 if (keys != NULL) {
1986 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1987 PyObject *keys_tuple = PyList_AsTuple(keys);
1988 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001989 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001991 assert(default_count > 0);
1992 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001993 }
1994 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001995 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001996 }
1997
1998error:
1999 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002000 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002001}
2002
2003static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002004compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2005{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002006 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002007 return 1;
2008}
2009
2010static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002011compiler_visit_argannotation(struct compiler *c, identifier id,
2012 expr_ty annotation, PyObject *names)
2013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002015 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002016 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2017 VISIT(c, annexpr, annotation)
2018 }
2019 else {
2020 VISIT(c, expr, annotation);
2021 }
Victor Stinner065efc32014-02-18 22:07:56 +01002022 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002023 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002024 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002025 if (PyList_Append(names, mangled) < 0) {
2026 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002027 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002028 }
2029 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002031 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002032}
2033
2034static int
2035compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2036 PyObject *names)
2037{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002038 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 for (i = 0; i < asdl_seq_LEN(args); i++) {
2040 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002041 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 c,
2043 arg->arg,
2044 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002045 names))
2046 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002048 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002049}
2050
2051static int
2052compiler_visit_annotations(struct compiler *c, arguments_ty args,
2053 expr_ty returns)
2054{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002055 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002056 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002057
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002058 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 */
2060 static identifier return_str;
2061 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002062 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 names = PyList_New(0);
2064 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002065 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002066
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002069 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2070 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002071 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002072 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002073 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002077 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002078 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002079 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (!return_str) {
2083 return_str = PyUnicode_InternFromString("return");
2084 if (!return_str)
2085 goto error;
2086 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002087 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 goto error;
2089 }
2090
2091 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002093 PyObject *keytuple = PyList_AsTuple(names);
2094 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002095 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002096 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002097 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002099 else {
2100 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002101 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002102 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002103
2104error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002106 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002107}
2108
2109static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110compiler_visit_defaults(struct compiler *c, arguments_ty args)
2111{
2112 VISIT_SEQ(c, expr, args->defaults);
2113 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2114 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115}
2116
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002117static Py_ssize_t
2118compiler_default_arguments(struct compiler *c, arguments_ty args)
2119{
2120 Py_ssize_t funcflags = 0;
2121 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002122 if (!compiler_visit_defaults(c, args))
2123 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002124 funcflags |= 0x01;
2125 }
2126 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002127 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002128 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002129 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002130 return -1;
2131 }
2132 else if (res > 0) {
2133 funcflags |= 0x02;
2134 }
2135 }
2136 return funcflags;
2137}
2138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002140forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2141{
2142
2143 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2144 compiler_error(c, "cannot assign to __debug__");
2145 return 1;
2146 }
2147 return 0;
2148}
2149
2150static int
2151compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2152{
2153 if (arg != NULL) {
2154 if (forbidden_name(c, arg->arg, Store))
2155 return 0;
2156 }
2157 return 1;
2158}
2159
2160static int
2161compiler_check_debug_args_seq(struct compiler *c, asdl_seq *args)
2162{
2163 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002164 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002165 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2166 return 0;
2167 }
2168 }
2169 return 1;
2170}
2171
2172static int
2173compiler_check_debug_args(struct compiler *c, arguments_ty args)
2174{
2175 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2176 return 0;
2177 if (!compiler_check_debug_args_seq(c, args->args))
2178 return 0;
2179 if (!compiler_check_debug_one_arg(c, args->vararg))
2180 return 0;
2181 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2182 return 0;
2183 if (!compiler_check_debug_one_arg(c, args->kwarg))
2184 return 0;
2185 return 1;
2186}
2187
2188static int
Yury Selivanov75445082015-05-11 22:57:16 -04002189compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002192 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002193 arguments_ty args;
2194 expr_ty returns;
2195 identifier name;
2196 asdl_seq* decos;
2197 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002198 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002199 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002200 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002201 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202
Yury Selivanov75445082015-05-11 22:57:16 -04002203 if (is_async) {
2204 assert(s->kind == AsyncFunctionDef_kind);
2205
2206 args = s->v.AsyncFunctionDef.args;
2207 returns = s->v.AsyncFunctionDef.returns;
2208 decos = s->v.AsyncFunctionDef.decorator_list;
2209 name = s->v.AsyncFunctionDef.name;
2210 body = s->v.AsyncFunctionDef.body;
2211
2212 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2213 } else {
2214 assert(s->kind == FunctionDef_kind);
2215
2216 args = s->v.FunctionDef.args;
2217 returns = s->v.FunctionDef.returns;
2218 decos = s->v.FunctionDef.decorator_list;
2219 name = s->v.FunctionDef.name;
2220 body = s->v.FunctionDef.body;
2221
2222 scope_type = COMPILER_SCOPE_FUNCTION;
2223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002225 if (!compiler_check_debug_args(c, args))
2226 return 0;
2227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 if (!compiler_decorators(c, decos))
2229 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002230
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002231 firstlineno = s->lineno;
2232 if (asdl_seq_LEN(decos)) {
2233 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2234 }
2235
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002236 funcflags = compiler_default_arguments(c, args);
2237 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002239 }
2240
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002241 annotations = compiler_visit_annotations(c, args, returns);
2242 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002243 return 0;
2244 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002245 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002246 funcflags |= 0x04;
2247 }
2248
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002249 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002250 return 0;
2251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252
INADA Naokicb41b272017-02-23 00:31:59 +09002253 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002254 if (c->c_optimize < 2) {
2255 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002256 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002257 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 compiler_exit_scope(c);
2259 return 0;
2260 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002263 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002265 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002267 qualname = c->u->u_qualname;
2268 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002270 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002271 Py_XDECREF(qualname);
2272 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002276 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002277 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* decorators */
2281 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2282 ADDOP_I(c, CALL_FUNCTION, 1);
2283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284
Yury Selivanov75445082015-05-11 22:57:16 -04002285 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286}
2287
2288static int
2289compiler_class(struct compiler *c, stmt_ty s)
2290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyCodeObject *co;
2292 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002293 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (!compiler_decorators(c, decos))
2297 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002298
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002299 firstlineno = s->lineno;
2300 if (asdl_seq_LEN(decos)) {
2301 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2302 }
2303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* ultimately generate code for:
2305 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2306 where:
2307 <func> is a function/closure created from the class body;
2308 it has a single argument (__locals__) where the dict
2309 (or MutableSequence) representing the locals is passed
2310 <name> is the class name
2311 <bases> is the positional arguments and *varargs argument
2312 <keywords> is the keyword arguments and **kwds argument
2313 This borrows from compiler_call.
2314 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002317 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002318 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 return 0;
2320 /* this block represents what we do in the new scope */
2321 {
2322 /* use the class name for name mangling */
2323 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002324 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* load (global) __name__ ... */
2326 str = PyUnicode_InternFromString("__name__");
2327 if (!str || !compiler_nameop(c, str, Load)) {
2328 Py_XDECREF(str);
2329 compiler_exit_scope(c);
2330 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 Py_DECREF(str);
2333 /* ... and store it as __module__ */
2334 str = PyUnicode_InternFromString("__module__");
2335 if (!str || !compiler_nameop(c, str, Store)) {
2336 Py_XDECREF(str);
2337 compiler_exit_scope(c);
2338 return 0;
2339 }
2340 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002341 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002342 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002343 str = PyUnicode_InternFromString("__qualname__");
2344 if (!str || !compiler_nameop(c, str, Store)) {
2345 Py_XDECREF(str);
2346 compiler_exit_scope(c);
2347 return 0;
2348 }
2349 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002351 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 compiler_exit_scope(c);
2353 return 0;
2354 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002355 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002356 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002357 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002358 str = PyUnicode_InternFromString("__class__");
2359 if (str == NULL) {
2360 compiler_exit_scope(c);
2361 return 0;
2362 }
2363 i = compiler_lookup_arg(c->u->u_cellvars, str);
2364 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002365 if (i < 0) {
2366 compiler_exit_scope(c);
2367 return 0;
2368 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002369 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002372 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002373 str = PyUnicode_InternFromString("__classcell__");
2374 if (!str || !compiler_nameop(c, str, Store)) {
2375 Py_XDECREF(str);
2376 compiler_exit_scope(c);
2377 return 0;
2378 }
2379 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002381 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002382 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002383 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002384 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002385 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002386 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* create the code object */
2388 co = assemble(c, 1);
2389 }
2390 /* leave the new scope */
2391 compiler_exit_scope(c);
2392 if (co == NULL)
2393 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* 2. load the 'build_class' function */
2396 ADDOP(c, LOAD_BUILD_CLASS);
2397
2398 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002399 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 Py_DECREF(co);
2401
2402 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002403 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404
2405 /* 5. generate the rest of the code for the call */
2406 if (!compiler_call_helper(c, 2,
2407 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002408 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return 0;
2410
2411 /* 6. apply decorators */
2412 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2413 ADDOP_I(c, CALL_FUNCTION, 1);
2414 }
2415
2416 /* 7. store into <name> */
2417 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2418 return 0;
2419 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420}
2421
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002422/* Return 0 if the expression is a constant value except named singletons.
2423 Return 1 otherwise. */
2424static int
2425check_is_arg(expr_ty e)
2426{
2427 if (e->kind != Constant_kind) {
2428 return 1;
2429 }
2430 PyObject *value = e->v.Constant.value;
2431 return (value == Py_None
2432 || value == Py_False
2433 || value == Py_True
2434 || value == Py_Ellipsis);
2435}
2436
2437/* Check operands of identity chacks ("is" and "is not").
2438 Emit a warning if any operand is a constant except named singletons.
2439 Return 0 on error.
2440 */
2441static int
2442check_compare(struct compiler *c, expr_ty e)
2443{
2444 Py_ssize_t i, n;
2445 int left = check_is_arg(e->v.Compare.left);
2446 n = asdl_seq_LEN(e->v.Compare.ops);
2447 for (i = 0; i < n; i++) {
2448 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2449 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2450 if (op == Is || op == IsNot) {
2451 if (!right || !left) {
2452 const char *msg = (op == Is)
2453 ? "\"is\" with a literal. Did you mean \"==\"?"
2454 : "\"is not\" with a literal. Did you mean \"!=\"?";
2455 return compiler_warn(c, msg);
2456 }
2457 }
2458 left = right;
2459 }
2460 return 1;
2461}
2462
Mark Shannon9af0e472020-01-14 10:12:45 +00002463static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002464{
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002466 switch (op) {
2467 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 cmp = Py_EQ;
2469 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002471 cmp = Py_NE;
2472 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 cmp = Py_LT;
2475 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002477 cmp = Py_LE;
2478 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 cmp = Py_GT;
2481 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 cmp = Py_GE;
2484 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002486 ADDOP_I(c, IS_OP, 0);
2487 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002488 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002489 ADDOP_I(c, IS_OP, 1);
2490 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002492 ADDOP_I(c, CONTAINS_OP, 0);
2493 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002494 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002495 ADDOP_I(c, CONTAINS_OP, 1);
2496 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002497 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002498 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002500 ADDOP_I(c, COMPARE_OP, cmp);
2501 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002502}
2503
Mark Shannon9af0e472020-01-14 10:12:45 +00002504
2505
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002506static int
2507compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2508{
2509 switch (e->kind) {
2510 case UnaryOp_kind:
2511 if (e->v.UnaryOp.op == Not)
2512 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2513 /* fallback to general implementation */
2514 break;
2515 case BoolOp_kind: {
2516 asdl_seq *s = e->v.BoolOp.values;
2517 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2518 assert(n >= 0);
2519 int cond2 = e->v.BoolOp.op == Or;
2520 basicblock *next2 = next;
2521 if (!cond2 != !cond) {
2522 next2 = compiler_new_block(c);
2523 if (next2 == NULL)
2524 return 0;
2525 }
2526 for (i = 0; i < n; ++i) {
2527 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2528 return 0;
2529 }
2530 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2531 return 0;
2532 if (next2 != next)
2533 compiler_use_next_block(c, next2);
2534 return 1;
2535 }
2536 case IfExp_kind: {
2537 basicblock *end, *next2;
2538 end = compiler_new_block(c);
2539 if (end == NULL)
2540 return 0;
2541 next2 = compiler_new_block(c);
2542 if (next2 == NULL)
2543 return 0;
2544 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2545 return 0;
2546 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2547 return 0;
2548 ADDOP_JREL(c, JUMP_FORWARD, end);
2549 compiler_use_next_block(c, next2);
2550 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2551 return 0;
2552 compiler_use_next_block(c, end);
2553 return 1;
2554 }
2555 case Compare_kind: {
2556 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2557 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002558 if (!check_compare(c, e)) {
2559 return 0;
2560 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002561 basicblock *cleanup = compiler_new_block(c);
2562 if (cleanup == NULL)
2563 return 0;
2564 VISIT(c, expr, e->v.Compare.left);
2565 for (i = 0; i < n; i++) {
2566 VISIT(c, expr,
2567 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2568 ADDOP(c, DUP_TOP);
2569 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002570 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002571 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2572 NEXT_BLOCK(c);
2573 }
2574 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002575 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002576 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2577 basicblock *end = compiler_new_block(c);
2578 if (end == NULL)
2579 return 0;
2580 ADDOP_JREL(c, JUMP_FORWARD, end);
2581 compiler_use_next_block(c, cleanup);
2582 ADDOP(c, POP_TOP);
2583 if (!cond) {
2584 ADDOP_JREL(c, JUMP_FORWARD, next);
2585 }
2586 compiler_use_next_block(c, end);
2587 return 1;
2588 }
2589 /* fallback to general implementation */
2590 break;
2591 }
2592 default:
2593 /* fallback to general implementation */
2594 break;
2595 }
2596
2597 /* general implementation */
2598 VISIT(c, expr, e);
2599 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2600 return 1;
2601}
2602
2603static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002604compiler_ifexp(struct compiler *c, expr_ty e)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 basicblock *end, *next;
2607
2608 assert(e->kind == IfExp_kind);
2609 end = compiler_new_block(c);
2610 if (end == NULL)
2611 return 0;
2612 next = compiler_new_block(c);
2613 if (next == NULL)
2614 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002615 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2616 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 VISIT(c, expr, e->v.IfExp.body);
2618 ADDOP_JREL(c, JUMP_FORWARD, end);
2619 compiler_use_next_block(c, next);
2620 VISIT(c, expr, e->v.IfExp.orelse);
2621 compiler_use_next_block(c, end);
2622 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002623}
2624
2625static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626compiler_lambda(struct compiler *c, expr_ty e)
2627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002629 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002631 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 arguments_ty args = e->v.Lambda.args;
2633 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002635 if (!compiler_check_debug_args(c, args))
2636 return 0;
2637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 if (!name) {
2639 name = PyUnicode_InternFromString("<lambda>");
2640 if (!name)
2641 return 0;
2642 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002644 funcflags = compiler_default_arguments(c, args);
2645 if (funcflags == -1) {
2646 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002648
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002649 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002650 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 /* Make None the first constant, so the lambda can't have a
2654 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002655 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002659 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2661 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2662 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002663 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 }
2665 else {
2666 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002667 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002669 qualname = c->u->u_qualname;
2670 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002672 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002675 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002676 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 Py_DECREF(co);
2678
2679 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680}
2681
2682static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683compiler_if(struct compiler *c, stmt_ty s)
2684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 basicblock *end, *next;
2686 int constant;
2687 assert(s->kind == If_kind);
2688 end = compiler_new_block(c);
2689 if (end == NULL)
2690 return 0;
2691
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002692 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002693 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 * constant = 1: "if 1", "if 2", ...
2695 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002696 if (constant == 0) {
2697 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002699 END_DO_NOT_EMIT_BYTECODE
2700 if (s->v.If.orelse) {
2701 VISIT_SEQ(c, stmt, s->v.If.orelse);
2702 }
2703 } else if (constant == 1) {
2704 VISIT_SEQ(c, stmt, s->v.If.body);
2705 if (s->v.If.orelse) {
2706 BEGIN_DO_NOT_EMIT_BYTECODE
2707 VISIT_SEQ(c, stmt, s->v.If.orelse);
2708 END_DO_NOT_EMIT_BYTECODE
2709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002711 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 next = compiler_new_block(c);
2713 if (next == NULL)
2714 return 0;
2715 }
Mark Shannonfee55262019-11-21 09:11:43 +00002716 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002718 }
2719 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002720 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002723 if (asdl_seq_LEN(s->v.If.orelse)) {
2724 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 compiler_use_next_block(c, next);
2726 VISIT_SEQ(c, stmt, s->v.If.orelse);
2727 }
2728 }
2729 compiler_use_next_block(c, end);
2730 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731}
2732
2733static int
2734compiler_for(struct compiler *c, stmt_ty s)
2735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 start = compiler_new_block(c);
2739 cleanup = compiler_new_block(c);
2740 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002741 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002743 }
2744 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002746 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 VISIT(c, expr, s->v.For.iter);
2748 ADDOP(c, GET_ITER);
2749 compiler_use_next_block(c, start);
2750 ADDOP_JREL(c, FOR_ITER, cleanup);
2751 VISIT(c, expr, s->v.For.target);
2752 VISIT_SEQ(c, stmt, s->v.For.body);
2753 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2754 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002755
2756 compiler_pop_fblock(c, FOR_LOOP, start);
2757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 VISIT_SEQ(c, stmt, s->v.For.orelse);
2759 compiler_use_next_block(c, end);
2760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761}
2762
Yury Selivanov75445082015-05-11 22:57:16 -04002763
2764static int
2765compiler_async_for(struct compiler *c, stmt_ty s)
2766{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002767 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002768 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002769 c->u->u_ste->ste_coroutine = 1;
2770 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002771 return compiler_error(c, "'async for' outside async function");
2772 }
2773
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002774 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002775 except = compiler_new_block(c);
2776 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002777
Mark Shannonfee55262019-11-21 09:11:43 +00002778 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002779 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002780 }
Yury Selivanov75445082015-05-11 22:57:16 -04002781 VISIT(c, expr, s->v.AsyncFor.iter);
2782 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002783
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002784 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002785 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002786 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002787 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 /* SETUP_FINALLY to guard the __anext__ call */
2789 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002790 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002791 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002792 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002794
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002795 /* Success block for __anext__ */
2796 VISIT(c, expr, s->v.AsyncFor.target);
2797 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2798 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2799
2800 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002801
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002802 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002803 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002804 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002805
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002807 VISIT_SEQ(c, stmt, s->v.For.orelse);
2808
2809 compiler_use_next_block(c, end);
2810
2811 return 1;
2812}
2813
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814static int
2815compiler_while(struct compiler *c, stmt_ty s)
2816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002818 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002821 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002822 // Push a dummy block so the VISIT_SEQ knows that we are
2823 // inside a while loop so it can correctly evaluate syntax
2824 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002825 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002826 return 0;
2827 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002828 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002829 // Remove the dummy block now that is not needed.
2830 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002831 END_DO_NOT_EMIT_BYTECODE
2832 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002834 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return 1;
2836 }
2837 loop = compiler_new_block(c);
2838 end = compiler_new_block(c);
2839 if (constant == -1) {
2840 anchor = compiler_new_block(c);
2841 if (anchor == NULL)
2842 return 0;
2843 }
2844 if (loop == NULL || end == NULL)
2845 return 0;
2846 if (s->v.While.orelse) {
2847 orelse = compiler_new_block(c);
2848 if (orelse == NULL)
2849 return 0;
2850 }
2851 else
2852 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002855 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 return 0;
2857 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002858 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2859 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 }
2861 VISIT_SEQ(c, stmt, s->v.While.body);
2862 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 /* XXX should the two POP instructions be in a separate block
2865 if there is no else clause ?
2866 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002868 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002870 compiler_pop_fblock(c, WHILE_LOOP, loop);
2871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 if (orelse != NULL) /* what if orelse is just pass? */
2873 VISIT_SEQ(c, stmt, s->v.While.orelse);
2874 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877}
2878
2879static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002880compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002882 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002883 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884 if (c->u->u_ste->ste_type != FunctionBlock)
2885 return compiler_error(c, "'return' outside function");
2886 if (s->v.Return.value != NULL &&
2887 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2888 {
2889 return compiler_error(
2890 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 if (preserve_tos) {
2893 VISIT(c, expr, s->v.Return.value);
2894 }
Mark Shannonfee55262019-11-21 09:11:43 +00002895 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2896 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002898 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002899 }
2900 else if (!preserve_tos) {
2901 VISIT(c, expr, s->v.Return.value);
2902 }
2903 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906}
2907
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002908static int
2909compiler_break(struct compiler *c)
2910{
Mark Shannonfee55262019-11-21 09:11:43 +00002911 struct fblockinfo *loop = NULL;
2912 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2913 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 }
Mark Shannonfee55262019-11-21 09:11:43 +00002915 if (loop == NULL) {
2916 return compiler_error(c, "'break' outside loop");
2917 }
2918 if (!compiler_unwind_fblock(c, loop, 0)) {
2919 return 0;
2920 }
2921 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2922 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002923}
2924
2925static int
2926compiler_continue(struct compiler *c)
2927{
Mark Shannonfee55262019-11-21 09:11:43 +00002928 struct fblockinfo *loop = NULL;
2929 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2930 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002931 }
Mark Shannonfee55262019-11-21 09:11:43 +00002932 if (loop == NULL) {
2933 return compiler_error(c, "'continue' not properly in loop");
2934 }
2935 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2936 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002937}
2938
2939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
2942 SETUP_FINALLY L
2943 <code for body>
2944 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002945 <code for finalbody>
2946 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947 L:
2948 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002949 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 The special instructions use the block stack. Each block
2952 stack entry contains the instruction that created it (here
2953 SETUP_FINALLY), the level of the value stack at the time the
2954 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 Pushes the current value stack level and the label
2958 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002960 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002963 when a SETUP_FINALLY entry is found, the raised and the caught
2964 exceptions are pushed onto the value stack (and the exception
2965 condition is cleared), and the interpreter jumps to the label
2966 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967*/
2968
2969static int
2970compiler_try_finally(struct compiler *c, stmt_ty s)
2971{
Mark Shannonfee55262019-11-21 09:11:43 +00002972 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 body = compiler_new_block(c);
2975 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002976 exit = compiler_new_block(c);
2977 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002980 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 ADDOP_JREL(c, SETUP_FINALLY, end);
2982 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002983 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002985 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2986 if (!compiler_try_except(c, s))
2987 return 0;
2988 }
2989 else {
2990 VISIT_SEQ(c, stmt, s->v.Try.body);
2991 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002993 compiler_pop_fblock(c, FINALLY_TRY, body);
2994 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2995 ADDOP_JREL(c, JUMP_FORWARD, exit);
2996 /* `finally` block */
2997 compiler_use_next_block(c, end);
2998 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2999 return 0;
3000 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3001 compiler_pop_fblock(c, FINALLY_END, end);
3002 ADDOP(c, RERAISE);
3003 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
3007/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003008 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 (The contents of the value stack is shown in [], with the top
3010 at the right; 'tb' is trace-back info, 'val' the exception's
3011 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012
3013 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003014 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 [] <code for S>
3016 [] POP_BLOCK
3017 [] JUMP_FORWARD L0
3018
3019 [tb, val, exc] L1: DUP )
3020 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003021 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 [tb, val, exc] POP
3023 [tb, val] <assign to V1> (or POP if no V1)
3024 [tb] POP
3025 [] <code for S1>
3026 JUMP_FORWARD L0
3027
3028 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 .............................etc.......................
3030
Mark Shannonfee55262019-11-21 09:11:43 +00003031 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032
3033 [] L0: <next statement>
3034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 Of course, parts are not generated if Vi or Ei is not present.
3036*/
3037static int
3038compiler_try_except(struct compiler *c, stmt_ty s)
3039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003041 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 body = compiler_new_block(c);
3044 except = compiler_new_block(c);
3045 orelse = compiler_new_block(c);
3046 end = compiler_new_block(c);
3047 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3048 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003049 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003051 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003053 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 ADDOP(c, POP_BLOCK);
3055 compiler_pop_fblock(c, EXCEPT, body);
3056 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003057 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 compiler_use_next_block(c, except);
3059 for (i = 0; i < n; i++) {
3060 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003061 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 if (!handler->v.ExceptHandler.type && i < n-1)
3063 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003064 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 except = compiler_new_block(c);
3066 if (except == NULL)
3067 return 0;
3068 if (handler->v.ExceptHandler.type) {
3069 ADDOP(c, DUP_TOP);
3070 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003071 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 }
3073 ADDOP(c, POP_TOP);
3074 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003076
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 cleanup_end = compiler_new_block(c);
3078 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003079 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003081 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003082
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3084 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 /*
3087 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003088 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003090 try:
3091 # body
3092 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003093 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003094 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 /* second try: */
3098 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3099 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003100 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 /* second # body */
3104 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003105 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003106 ADDOP(c, POP_BLOCK);
3107 ADDOP(c, POP_EXCEPT);
3108 /* name = None; del name */
3109 ADDOP_LOAD_CONST(c, Py_None);
3110 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3111 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3112 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113
Mark Shannonfee55262019-11-21 09:11:43 +00003114 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003117 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003118 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003120 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121
Mark Shannonfee55262019-11-21 09:11:43 +00003122 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
3124 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003128 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003129 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130
Guido van Rossumb940e112007-01-10 16:19:56 +00003131 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003132 ADDOP(c, POP_TOP);
3133 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003134 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003135 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003137 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003138 ADDOP(c, POP_EXCEPT);
3139 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 compiler_use_next_block(c, except);
3142 }
Mark Shannonfee55262019-11-21 09:11:43 +00003143 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003145 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 compiler_use_next_block(c, end);
3147 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148}
3149
3150static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003151compiler_try(struct compiler *c, stmt_ty s) {
3152 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3153 return compiler_try_finally(c, s);
3154 else
3155 return compiler_try_except(c, s);
3156}
3157
3158
3159static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160compiler_import_as(struct compiler *c, identifier name, identifier asname)
3161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* The IMPORT_NAME opcode was already generated. This function
3163 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003166 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003168 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3169 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003170 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003171 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003172 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003174 while (1) {
3175 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003177 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003178 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003179 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003180 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003182 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003183 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003184 if (dot == -1) {
3185 break;
3186 }
3187 ADDOP(c, ROT_TWO);
3188 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003190 if (!compiler_nameop(c, asname, Store)) {
3191 return 0;
3192 }
3193 ADDOP(c, POP_TOP);
3194 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 }
3196 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197}
3198
3199static int
3200compiler_import(struct compiler *c, stmt_ty s)
3201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 /* The Import node stores a module name like a.b.c as a single
3203 string. This is convenient for all cases except
3204 import a.b.c as d
3205 where we need to parse that string to extract the individual
3206 module names.
3207 XXX Perhaps change the representation to make this case simpler?
3208 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003209 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 for (i = 0; i < n; i++) {
3212 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3213 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003215 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3216 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 if (alias->asname) {
3220 r = compiler_import_as(c, alias->name, alias->asname);
3221 if (!r)
3222 return r;
3223 }
3224 else {
3225 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003226 Py_ssize_t dot = PyUnicode_FindChar(
3227 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003228 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003229 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003230 if (tmp == NULL)
3231 return 0;
3232 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003234 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 Py_DECREF(tmp);
3236 }
3237 if (!r)
3238 return r;
3239 }
3240 }
3241 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242}
3243
3244static int
3245compiler_from_import(struct compiler *c, stmt_ty s)
3246{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003247 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003248 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 if (!empty_string) {
3252 empty_string = PyUnicode_FromString("");
3253 if (!empty_string)
3254 return 0;
3255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003257 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003258
3259 names = PyTuple_New(n);
3260 if (!names)
3261 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 /* build up the names */
3264 for (i = 0; i < n; i++) {
3265 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3266 Py_INCREF(alias->name);
3267 PyTuple_SET_ITEM(names, i, alias->name);
3268 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003271 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 Py_DECREF(names);
3273 return compiler_error(c, "from __future__ imports must occur "
3274 "at the beginning of the file");
3275 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003276 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 if (s->v.ImportFrom.module) {
3279 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3280 }
3281 else {
3282 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3283 }
3284 for (i = 0; i < n; i++) {
3285 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3286 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003288 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 assert(n == 1);
3290 ADDOP(c, IMPORT_STAR);
3291 return 1;
3292 }
3293
3294 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3295 store_name = alias->name;
3296 if (alias->asname)
3297 store_name = alias->asname;
3298
3299 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 return 0;
3301 }
3302 }
3303 /* remove imported module */
3304 ADDOP(c, POP_TOP);
3305 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306}
3307
3308static int
3309compiler_assert(struct compiler *c, stmt_ty s)
3310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312
Georg Brandl8334fd92010-12-04 10:26:46 +00003313 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003316 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3317 {
3318 if (!compiler_warn(c, "assertion is always true, "
3319 "perhaps remove parentheses?"))
3320 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003321 return 0;
3322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 end = compiler_new_block(c);
3325 if (end == NULL)
3326 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003327 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3328 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003329 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 if (s->v.Assert.msg) {
3331 VISIT(c, expr, s->v.Assert.msg);
3332 ADDOP_I(c, CALL_FUNCTION, 1);
3333 }
3334 ADDOP_I(c, RAISE_VARARGS, 1);
3335 compiler_use_next_block(c, end);
3336 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337}
3338
3339static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003340compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3341{
3342 if (c->c_interactive && c->c_nestlevel <= 1) {
3343 VISIT(c, expr, value);
3344 ADDOP(c, PRINT_EXPR);
3345 return 1;
3346 }
3347
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003348 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003349 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003350 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003351 }
3352
3353 VISIT(c, expr, value);
3354 ADDOP(c, POP_TOP);
3355 return 1;
3356}
3357
3358static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359compiler_visit_stmt(struct compiler *c, stmt_ty s)
3360{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003361 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003364 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 switch (s->kind) {
3367 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003368 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 case ClassDef_kind:
3370 return compiler_class(c, s);
3371 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003372 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 case Delete_kind:
3374 VISIT_SEQ(c, expr, s->v.Delete.targets)
3375 break;
3376 case Assign_kind:
3377 n = asdl_seq_LEN(s->v.Assign.targets);
3378 VISIT(c, expr, s->v.Assign.value);
3379 for (i = 0; i < n; i++) {
3380 if (i < n - 1)
3381 ADDOP(c, DUP_TOP);
3382 VISIT(c, expr,
3383 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3384 }
3385 break;
3386 case AugAssign_kind:
3387 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003388 case AnnAssign_kind:
3389 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 case For_kind:
3391 return compiler_for(c, s);
3392 case While_kind:
3393 return compiler_while(c, s);
3394 case If_kind:
3395 return compiler_if(c, s);
3396 case Raise_kind:
3397 n = 0;
3398 if (s->v.Raise.exc) {
3399 VISIT(c, expr, s->v.Raise.exc);
3400 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003401 if (s->v.Raise.cause) {
3402 VISIT(c, expr, s->v.Raise.cause);
3403 n++;
3404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003406 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003408 case Try_kind:
3409 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 case Assert_kind:
3411 return compiler_assert(c, s);
3412 case Import_kind:
3413 return compiler_import(c, s);
3414 case ImportFrom_kind:
3415 return compiler_from_import(c, s);
3416 case Global_kind:
3417 case Nonlocal_kind:
3418 break;
3419 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003420 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 case Pass_kind:
3422 break;
3423 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003424 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 case Continue_kind:
3426 return compiler_continue(c);
3427 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003428 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003429 case AsyncFunctionDef_kind:
3430 return compiler_function(c, s, 1);
3431 case AsyncWith_kind:
3432 return compiler_async_with(c, s, 0);
3433 case AsyncFor_kind:
3434 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 }
Yury Selivanov75445082015-05-11 22:57:16 -04003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003438}
3439
3440static int
3441unaryop(unaryop_ty op)
3442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 switch (op) {
3444 case Invert:
3445 return UNARY_INVERT;
3446 case Not:
3447 return UNARY_NOT;
3448 case UAdd:
3449 return UNARY_POSITIVE;
3450 case USub:
3451 return UNARY_NEGATIVE;
3452 default:
3453 PyErr_Format(PyExc_SystemError,
3454 "unary op %d should not be possible", op);
3455 return 0;
3456 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457}
3458
3459static int
Andy Lester76d58772020-03-10 21:18:12 -05003460binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 switch (op) {
3463 case Add:
3464 return BINARY_ADD;
3465 case Sub:
3466 return BINARY_SUBTRACT;
3467 case Mult:
3468 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003469 case MatMult:
3470 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 case Div:
3472 return BINARY_TRUE_DIVIDE;
3473 case Mod:
3474 return BINARY_MODULO;
3475 case Pow:
3476 return BINARY_POWER;
3477 case LShift:
3478 return BINARY_LSHIFT;
3479 case RShift:
3480 return BINARY_RSHIFT;
3481 case BitOr:
3482 return BINARY_OR;
3483 case BitXor:
3484 return BINARY_XOR;
3485 case BitAnd:
3486 return BINARY_AND;
3487 case FloorDiv:
3488 return BINARY_FLOOR_DIVIDE;
3489 default:
3490 PyErr_Format(PyExc_SystemError,
3491 "binary op %d should not be possible", op);
3492 return 0;
3493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494}
3495
3496static int
Andy Lester76d58772020-03-10 21:18:12 -05003497inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 switch (op) {
3500 case Add:
3501 return INPLACE_ADD;
3502 case Sub:
3503 return INPLACE_SUBTRACT;
3504 case Mult:
3505 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003506 case MatMult:
3507 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 case Div:
3509 return INPLACE_TRUE_DIVIDE;
3510 case Mod:
3511 return INPLACE_MODULO;
3512 case Pow:
3513 return INPLACE_POWER;
3514 case LShift:
3515 return INPLACE_LSHIFT;
3516 case RShift:
3517 return INPLACE_RSHIFT;
3518 case BitOr:
3519 return INPLACE_OR;
3520 case BitXor:
3521 return INPLACE_XOR;
3522 case BitAnd:
3523 return INPLACE_AND;
3524 case FloorDiv:
3525 return INPLACE_FLOOR_DIVIDE;
3526 default:
3527 PyErr_Format(PyExc_SystemError,
3528 "inplace binary op %d should not be possible", op);
3529 return 0;
3530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531}
3532
3533static int
3534compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3535{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003536 int op, scope;
3537 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 PyObject *dict = c->u->u_names;
3541 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003543 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3544 !_PyUnicode_EqualToASCIIString(name, "True") &&
3545 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003546
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003547 if (forbidden_name(c, name, ctx))
3548 return 0;
3549
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003550 mangled = _Py_Mangle(c->u->u_private, name);
3551 if (!mangled)
3552 return 0;
3553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 op = 0;
3555 optype = OP_NAME;
3556 scope = PyST_GetScope(c->u->u_ste, mangled);
3557 switch (scope) {
3558 case FREE:
3559 dict = c->u->u_freevars;
3560 optype = OP_DEREF;
3561 break;
3562 case CELL:
3563 dict = c->u->u_cellvars;
3564 optype = OP_DEREF;
3565 break;
3566 case LOCAL:
3567 if (c->u->u_ste->ste_type == FunctionBlock)
3568 optype = OP_FAST;
3569 break;
3570 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003571 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 optype = OP_GLOBAL;
3573 break;
3574 case GLOBAL_EXPLICIT:
3575 optype = OP_GLOBAL;
3576 break;
3577 default:
3578 /* scope can be 0 */
3579 break;
3580 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003583 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 switch (optype) {
3586 case OP_DEREF:
3587 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003588 case Load:
3589 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3590 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003591 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003592 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 }
3594 break;
3595 case OP_FAST:
3596 switch (ctx) {
3597 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003598 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003601 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 return 1;
3603 case OP_GLOBAL:
3604 switch (ctx) {
3605 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003606 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 }
3609 break;
3610 case OP_NAME:
3611 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003612 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003613 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 }
3616 break;
3617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003620 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 Py_DECREF(mangled);
3622 if (arg < 0)
3623 return 0;
3624 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625}
3626
3627static int
3628compiler_boolop(struct compiler *c, expr_ty e)
3629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003631 int jumpi;
3632 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 assert(e->kind == BoolOp_kind);
3636 if (e->v.BoolOp.op == And)
3637 jumpi = JUMP_IF_FALSE_OR_POP;
3638 else
3639 jumpi = JUMP_IF_TRUE_OR_POP;
3640 end = compiler_new_block(c);
3641 if (end == NULL)
3642 return 0;
3643 s = e->v.BoolOp.values;
3644 n = asdl_seq_LEN(s) - 1;
3645 assert(n >= 0);
3646 for (i = 0; i < n; ++i) {
3647 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3648 ADDOP_JABS(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003649 basicblock *next = compiler_new_block(c);
3650 if (next == NULL) {
3651 return 0;
3652 }
3653 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 }
3655 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3656 compiler_use_next_block(c, end);
3657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
3660static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003661starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3662 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003663{
3664 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003665 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003666 if (n > 2 && are_all_items_const(elts, 0, n)) {
3667 PyObject *folded = PyTuple_New(n);
3668 if (folded == NULL) {
3669 return 0;
3670 }
3671 PyObject *val;
3672 for (i = 0; i < n; i++) {
3673 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3674 Py_INCREF(val);
3675 PyTuple_SET_ITEM(folded, i, val);
3676 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003677 if (tuple) {
3678 ADDOP_LOAD_CONST_NEW(c, folded);
3679 } else {
3680 if (add == SET_ADD) {
3681 Py_SETREF(folded, PyFrozenSet_New(folded));
3682 if (folded == NULL) {
3683 return 0;
3684 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003686 ADDOP_I(c, build, pushed);
3687 ADDOP_LOAD_CONST_NEW(c, folded);
3688 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003689 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 return 1;
3691 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003692
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003693 for (i = 0; i < n; i++) {
3694 expr_ty elt = asdl_seq_GET(elts, i);
3695 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003696 seen_star = 1;
3697 }
3698 }
3699 if (seen_star) {
3700 seen_star = 0;
3701 for (i = 0; i < n; i++) {
3702 expr_ty elt = asdl_seq_GET(elts, i);
3703 if (elt->kind == Starred_kind) {
3704 if (seen_star == 0) {
3705 ADDOP_I(c, build, i+pushed);
3706 seen_star = 1;
3707 }
3708 VISIT(c, expr, elt->v.Starred.value);
3709 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003711 else {
3712 VISIT(c, expr, elt);
3713 if (seen_star) {
3714 ADDOP_I(c, add, 1);
3715 }
3716 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003718 assert(seen_star);
3719 if (tuple) {
3720 ADDOP(c, LIST_TO_TUPLE);
3721 }
3722 }
3723 else {
3724 for (i = 0; i < n; i++) {
3725 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003726 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003727 }
3728 if (tuple) {
3729 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3730 } else {
3731 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003732 }
3733 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 return 1;
3735}
3736
3737static int
3738assignment_helper(struct compiler *c, asdl_seq *elts)
3739{
3740 Py_ssize_t n = asdl_seq_LEN(elts);
3741 Py_ssize_t i;
3742 int seen_star = 0;
3743 for (i = 0; i < n; i++) {
3744 expr_ty elt = asdl_seq_GET(elts, i);
3745 if (elt->kind == Starred_kind && !seen_star) {
3746 if ((i >= (1 << 8)) ||
3747 (n-i-1 >= (INT_MAX >> 8)))
3748 return compiler_error(c,
3749 "too many expressions in "
3750 "star-unpacking assignment");
3751 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3752 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 }
3754 else if (elt->kind == Starred_kind) {
3755 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003756 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757 }
3758 }
3759 if (!seen_star) {
3760 ADDOP_I(c, UNPACK_SEQUENCE, n);
3761 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003762 for (i = 0; i < n; i++) {
3763 expr_ty elt = asdl_seq_GET(elts, i);
3764 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3765 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003766 return 1;
3767}
3768
3769static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770compiler_list(struct compiler *c, expr_ty e)
3771{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003772 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003773 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003774 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003776 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003777 return starunpack_helper(c, elts, 0, BUILD_LIST,
3778 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003780 else
3781 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783}
3784
3785static int
3786compiler_tuple(struct compiler *c, expr_ty e)
3787{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003788 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003789 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 return assignment_helper(c, elts);
3791 }
3792 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003793 return starunpack_helper(c, elts, 0, BUILD_LIST,
3794 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 }
3796 else
3797 VISIT_SEQ(c, expr, elts);
3798 return 1;
3799}
3800
3801static int
3802compiler_set(struct compiler *c, expr_ty e)
3803{
Mark Shannon13bc1392020-01-23 09:25:17 +00003804 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3805 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003806}
3807
3808static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003809are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3810{
3811 Py_ssize_t i;
3812 for (i = begin; i < end; i++) {
3813 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003814 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003815 return 0;
3816 }
3817 return 1;
3818}
3819
3820static int
3821compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3822{
3823 Py_ssize_t i, n = end - begin;
3824 PyObject *keys, *key;
3825 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3826 for (i = begin; i < end; i++) {
3827 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3828 }
3829 keys = PyTuple_New(n);
3830 if (keys == NULL) {
3831 return 0;
3832 }
3833 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003834 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003835 Py_INCREF(key);
3836 PyTuple_SET_ITEM(keys, i - begin, key);
3837 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003838 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003839 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3840 }
3841 else {
3842 for (i = begin; i < end; i++) {
3843 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3844 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3845 }
3846 ADDOP_I(c, BUILD_MAP, n);
3847 }
3848 return 1;
3849}
3850
3851static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003852compiler_dict(struct compiler *c, expr_ty e)
3853{
Victor Stinner976bb402016-03-23 11:36:19 +01003854 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003855 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003856 int is_unpacking = 0;
3857 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003858 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003859 elements = 0;
3860 for (i = 0; i < n; i++) {
3861 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003862 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003863 if (elements) {
3864 if (!compiler_subdict(c, e, i - elements, i)) {
3865 return 0;
3866 }
3867 if (have_dict) {
3868 ADDOP_I(c, DICT_UPDATE, 1);
3869 }
3870 have_dict = 1;
3871 elements = 0;
3872 }
3873 if (have_dict == 0) {
3874 ADDOP_I(c, BUILD_MAP, 0);
3875 have_dict = 1;
3876 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879 }
3880 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003881 if (elements == 0xFFFF) {
3882 if (!compiler_subdict(c, e, i - elements, i)) {
3883 return 0;
3884 }
3885 if (have_dict) {
3886 ADDOP_I(c, DICT_UPDATE, 1);
3887 }
3888 have_dict = 1;
3889 elements = 0;
3890 }
3891 else {
3892 elements++;
3893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 }
3895 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003896 if (elements) {
3897 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003898 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003899 }
3900 if (have_dict) {
3901 ADDOP_I(c, DICT_UPDATE, 1);
3902 }
3903 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003904 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003905 if (!have_dict) {
3906 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 }
3908 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909}
3910
3911static int
3912compiler_compare(struct compiler *c, expr_ty e)
3913{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003914 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003916 if (!check_compare(c, e)) {
3917 return 0;
3918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003920 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3921 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3922 if (n == 0) {
3923 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003924 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 }
3926 else {
3927 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (cleanup == NULL)
3929 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003930 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 VISIT(c, expr,
3932 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003933 ADDOP(c, DUP_TOP);
3934 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003935 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003936 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3937 NEXT_BLOCK(c);
3938 }
3939 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003940 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 basicblock *end = compiler_new_block(c);
3942 if (end == NULL)
3943 return 0;
3944 ADDOP_JREL(c, JUMP_FORWARD, end);
3945 compiler_use_next_block(c, cleanup);
3946 ADDOP(c, ROT_TWO);
3947 ADDOP(c, POP_TOP);
3948 compiler_use_next_block(c, end);
3949 }
3950 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951}
3952
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003953static PyTypeObject *
3954infer_type(expr_ty e)
3955{
3956 switch (e->kind) {
3957 case Tuple_kind:
3958 return &PyTuple_Type;
3959 case List_kind:
3960 case ListComp_kind:
3961 return &PyList_Type;
3962 case Dict_kind:
3963 case DictComp_kind:
3964 return &PyDict_Type;
3965 case Set_kind:
3966 case SetComp_kind:
3967 return &PySet_Type;
3968 case GeneratorExp_kind:
3969 return &PyGen_Type;
3970 case Lambda_kind:
3971 return &PyFunction_Type;
3972 case JoinedStr_kind:
3973 case FormattedValue_kind:
3974 return &PyUnicode_Type;
3975 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003976 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003977 default:
3978 return NULL;
3979 }
3980}
3981
3982static int
3983check_caller(struct compiler *c, expr_ty e)
3984{
3985 switch (e->kind) {
3986 case Constant_kind:
3987 case Tuple_kind:
3988 case List_kind:
3989 case ListComp_kind:
3990 case Dict_kind:
3991 case DictComp_kind:
3992 case Set_kind:
3993 case SetComp_kind:
3994 case GeneratorExp_kind:
3995 case JoinedStr_kind:
3996 case FormattedValue_kind:
3997 return compiler_warn(c, "'%.200s' object is not callable; "
3998 "perhaps you missed a comma?",
3999 infer_type(e)->tp_name);
4000 default:
4001 return 1;
4002 }
4003}
4004
4005static int
4006check_subscripter(struct compiler *c, expr_ty e)
4007{
4008 PyObject *v;
4009
4010 switch (e->kind) {
4011 case Constant_kind:
4012 v = e->v.Constant.value;
4013 if (!(v == Py_None || v == Py_Ellipsis ||
4014 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4015 PyAnySet_Check(v)))
4016 {
4017 return 1;
4018 }
4019 /* fall through */
4020 case Set_kind:
4021 case SetComp_kind:
4022 case GeneratorExp_kind:
4023 case Lambda_kind:
4024 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4025 "perhaps you missed a comma?",
4026 infer_type(e)->tp_name);
4027 default:
4028 return 1;
4029 }
4030}
4031
4032static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004033check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004034{
4035 PyObject *v;
4036
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004037 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004038 if (index_type == NULL
4039 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4040 || index_type == &PySlice_Type) {
4041 return 1;
4042 }
4043
4044 switch (e->kind) {
4045 case Constant_kind:
4046 v = e->v.Constant.value;
4047 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4048 return 1;
4049 }
4050 /* fall through */
4051 case Tuple_kind:
4052 case List_kind:
4053 case ListComp_kind:
4054 case JoinedStr_kind:
4055 case FormattedValue_kind:
4056 return compiler_warn(c, "%.200s indices must be integers or slices, "
4057 "not %.200s; "
4058 "perhaps you missed a comma?",
4059 infer_type(e)->tp_name,
4060 index_type->tp_name);
4061 default:
4062 return 1;
4063 }
4064}
4065
Zackery Spytz97f5de02019-03-22 01:30:32 -06004066// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004068maybe_optimize_method_call(struct compiler *c, expr_ty e)
4069{
4070 Py_ssize_t argsl, i;
4071 expr_ty meth = e->v.Call.func;
4072 asdl_seq *args = e->v.Call.args;
4073
4074 /* Check that the call node is an attribute access, and that
4075 the call doesn't have keyword parameters. */
4076 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4077 asdl_seq_LEN(e->v.Call.keywords))
4078 return -1;
4079
4080 /* Check that there are no *varargs types of arguments. */
4081 argsl = asdl_seq_LEN(args);
4082 for (i = 0; i < argsl; i++) {
4083 expr_ty elt = asdl_seq_GET(args, i);
4084 if (elt->kind == Starred_kind) {
4085 return -1;
4086 }
4087 }
4088
4089 /* Alright, we can optimize the code. */
4090 VISIT(c, expr, meth->v.Attribute.value);
4091 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4092 VISIT_SEQ(c, expr, e->v.Call.args);
4093 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4094 return 1;
4095}
4096
4097static int
Zackery Spytz08050e92020-04-06 00:47:47 -06004098validate_keywords(struct compiler *c, asdl_seq *keywords)
4099{
4100 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4101 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004102 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4103 if (key->arg == NULL) {
4104 continue;
4105 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004106 if (forbidden_name(c, key->arg, Store)) {
4107 return -1;
4108 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004109 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004110 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4111 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4112 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4113 if (msg == NULL) {
4114 return -1;
4115 }
4116 c->u->u_col_offset = other->col_offset;
4117 compiler_error(c, PyUnicode_AsUTF8(msg));
4118 Py_DECREF(msg);
4119 return -1;
4120 }
4121 }
4122 }
4123 return 0;
4124}
4125
4126static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127compiler_call(struct compiler *c, expr_ty e)
4128{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004129 int ret = maybe_optimize_method_call(c, e);
4130 if (ret >= 0) {
4131 return ret;
4132 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004133 if (!check_caller(c, e->v.Call.func)) {
4134 return 0;
4135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 VISIT(c, expr, e->v.Call.func);
4137 return compiler_call_helper(c, 0,
4138 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004139 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004140}
4141
Eric V. Smith235a6f02015-09-19 14:51:32 -04004142static int
4143compiler_joined_str(struct compiler *c, expr_ty e)
4144{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004145 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004146 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4147 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004148 return 1;
4149}
4150
Eric V. Smitha78c7952015-11-03 12:45:05 -05004151/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004152static int
4153compiler_formatted_value(struct compiler *c, expr_ty e)
4154{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004155 /* Our oparg encodes 2 pieces of information: the conversion
4156 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004158 Convert the conversion char to 3 bits:
4159 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 !s : 001 0x1 FVC_STR
4161 !r : 010 0x2 FVC_REPR
4162 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004163
Eric V. Smitha78c7952015-11-03 12:45:05 -05004164 next bit is whether or not we have a format spec:
4165 yes : 100 0x4
4166 no : 000 0x0
4167 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004169 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004170 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004171
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004172 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173 VISIT(c, expr, e->v.FormattedValue.value);
4174
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004175 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004176 case 's': oparg = FVC_STR; break;
4177 case 'r': oparg = FVC_REPR; break;
4178 case 'a': oparg = FVC_ASCII; break;
4179 case -1: oparg = FVC_NONE; break;
4180 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004181 PyErr_Format(PyExc_SystemError,
4182 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004183 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004184 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004185 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004186 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004187 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004188 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004189 }
4190
Eric V. Smitha78c7952015-11-03 12:45:05 -05004191 /* And push our opcode and oparg */
4192 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004193
Eric V. Smith235a6f02015-09-19 14:51:32 -04004194 return 1;
4195}
4196
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004197static int
4198compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4199{
4200 Py_ssize_t i, n = end - begin;
4201 keyword_ty kw;
4202 PyObject *keys, *key;
4203 assert(n > 0);
4204 if (n > 1) {
4205 for (i = begin; i < end; i++) {
4206 kw = asdl_seq_GET(keywords, i);
4207 VISIT(c, expr, kw->value);
4208 }
4209 keys = PyTuple_New(n);
4210 if (keys == NULL) {
4211 return 0;
4212 }
4213 for (i = begin; i < end; i++) {
4214 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4215 Py_INCREF(key);
4216 PyTuple_SET_ITEM(keys, i - begin, key);
4217 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004218 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004219 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4220 }
4221 else {
4222 /* a for loop only executes once */
4223 for (i = begin; i < end; i++) {
4224 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004225 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004226 VISIT(c, expr, kw->value);
4227 }
4228 ADDOP_I(c, BUILD_MAP, n);
4229 }
4230 return 1;
4231}
4232
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004233/* shared code between compiler_call and compiler_class */
4234static int
4235compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004236 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004237 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004238 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004239{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004240 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004241
Pablo Galindo254ec782020-04-03 20:37:13 +01004242 if (validate_keywords(c, keywords) == -1) {
4243 return 0;
4244 }
4245
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004247 nkwelts = asdl_seq_LEN(keywords);
4248
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004249 for (i = 0; i < nelts; i++) {
4250 expr_ty elt = asdl_seq_GET(args, i);
4251 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004252 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004253 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004254 }
4255 for (i = 0; i < nkwelts; i++) {
4256 keyword_ty kw = asdl_seq_GET(keywords, i);
4257 if (kw->arg == NULL) {
4258 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004261
Mark Shannon13bc1392020-01-23 09:25:17 +00004262 /* No * or ** args, so can use faster calling sequence */
4263 for (i = 0; i < nelts; i++) {
4264 expr_ty elt = asdl_seq_GET(args, i);
4265 assert(elt->kind != Starred_kind);
4266 VISIT(c, expr, elt);
4267 }
4268 if (nkwelts) {
4269 PyObject *names;
4270 VISIT_SEQ(c, keyword, keywords);
4271 names = PyTuple_New(nkwelts);
4272 if (names == NULL) {
4273 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004274 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004275 for (i = 0; i < nkwelts; i++) {
4276 keyword_ty kw = asdl_seq_GET(keywords, i);
4277 Py_INCREF(kw->arg);
4278 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004279 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004280 ADDOP_LOAD_CONST_NEW(c, names);
4281 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4282 return 1;
4283 }
4284 else {
4285 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4286 return 1;
4287 }
4288
4289ex_call:
4290
4291 /* Do positional arguments. */
4292 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4293 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4294 }
4295 else if (starunpack_helper(c, args, n, BUILD_LIST,
4296 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4297 return 0;
4298 }
4299 /* Then keyword arguments */
4300 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004301 /* Has a new dict been pushed */
4302 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004303
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004304 nseen = 0; /* the number of keyword arguments on the stack following */
4305 for (i = 0; i < nkwelts; i++) {
4306 keyword_ty kw = asdl_seq_GET(keywords, i);
4307 if (kw->arg == NULL) {
4308 /* A keyword argument unpacking. */
4309 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004310 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004311 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004312 }
Mark Shannondb64f122020-06-01 10:42:42 +01004313 if (have_dict) {
4314 ADDOP_I(c, DICT_MERGE, 1);
4315 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004316 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004317 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004318 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004319 if (!have_dict) {
4320 ADDOP_I(c, BUILD_MAP, 0);
4321 have_dict = 1;
4322 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004323 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004324 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004325 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004326 else {
4327 nseen++;
4328 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004329 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004330 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004331 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004332 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004333 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004334 }
4335 if (have_dict) {
4336 ADDOP_I(c, DICT_MERGE, 1);
4337 }
4338 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004339 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004340 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004342 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344}
4345
Nick Coghlan650f0d02007-04-15 12:05:43 +00004346
4347/* List and set comprehensions and generator expressions work by creating a
4348 nested function to perform the actual iteration. This means that the
4349 iteration variables don't leak into the current scope.
4350 The defined function is called immediately following its definition, with the
4351 result of that call being the result of the expression.
4352 The LC/SC version returns the populated container, while the GE version is
4353 flagged in symtable.c as a generator, so it returns the generator object
4354 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004355
4356 Possible cleanups:
4357 - iterate over the generator sequence instead of using recursion
4358*/
4359
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362compiler_comprehension_generator(struct compiler *c,
4363 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004364 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004367 comprehension_ty gen;
4368 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4369 if (gen->is_async) {
4370 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004371 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 } else {
4373 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004374 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004375 }
4376}
4377
4378static int
4379compiler_sync_comprehension_generator(struct compiler *c,
4380 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004381 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004382 expr_ty elt, expr_ty val, int type)
4383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 /* generate code for the iterator, then each of the ifs,
4385 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 comprehension_ty gen;
4388 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004389 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 start = compiler_new_block(c);
4392 skip = compiler_new_block(c);
4393 if_cleanup = compiler_new_block(c);
4394 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4397 anchor == NULL)
4398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 if (gen_index == 0) {
4403 /* Receive outermost iter as an implicit argument */
4404 c->u->u_argcount = 1;
4405 ADDOP_I(c, LOAD_FAST, 0);
4406 }
4407 else {
4408 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004409 /* Fast path for the temporary variable assignment idiom:
4410 for y in [f(x)]
4411 */
4412 asdl_seq *elts;
4413 switch (gen->iter->kind) {
4414 case List_kind:
4415 elts = gen->iter->v.List.elts;
4416 break;
4417 case Tuple_kind:
4418 elts = gen->iter->v.Tuple.elts;
4419 break;
4420 default:
4421 elts = NULL;
4422 }
4423 if (asdl_seq_LEN(elts) == 1) {
4424 expr_ty elt = asdl_seq_GET(elts, 0);
4425 if (elt->kind != Starred_kind) {
4426 VISIT(c, expr, elt);
4427 start = NULL;
4428 }
4429 }
4430 if (start) {
4431 VISIT(c, expr, gen->iter);
4432 ADDOP(c, GET_ITER);
4433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004435 if (start) {
4436 depth++;
4437 compiler_use_next_block(c, start);
4438 ADDOP_JREL(c, FOR_ITER, anchor);
4439 NEXT_BLOCK(c);
4440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 /* XXX this needs to be cleaned up...a lot! */
4444 n = asdl_seq_LEN(gen->ifs);
4445 for (i = 0; i < n; i++) {
4446 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004447 if (!compiler_jump_if(c, e, if_cleanup, 0))
4448 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 NEXT_BLOCK(c);
4450 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 if (++gen_index < asdl_seq_LEN(generators))
4453 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004454 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 elt, val, type))
4456 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 /* only append after the last for generator */
4459 if (gen_index >= asdl_seq_LEN(generators)) {
4460 /* comprehension specific code */
4461 switch (type) {
4462 case COMP_GENEXP:
4463 VISIT(c, expr, elt);
4464 ADDOP(c, YIELD_VALUE);
4465 ADDOP(c, POP_TOP);
4466 break;
4467 case COMP_LISTCOMP:
4468 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004469 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 break;
4471 case COMP_SETCOMP:
4472 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004473 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 break;
4475 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004476 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004479 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004480 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 break;
4482 default:
4483 return 0;
4484 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 compiler_use_next_block(c, skip);
4487 }
4488 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004489 if (start) {
4490 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4491 compiler_use_next_block(c, anchor);
4492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493
4494 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004495}
4496
4497static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004498compiler_async_comprehension_generator(struct compiler *c,
4499 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004500 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004501 expr_ty elt, expr_ty val, int type)
4502{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004504 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004506 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004510 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004511 return 0;
4512 }
4513
4514 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4515
4516 if (gen_index == 0) {
4517 /* Receive outermost iter as an implicit argument */
4518 c->u->u_argcount = 1;
4519 ADDOP_I(c, LOAD_FAST, 0);
4520 }
4521 else {
4522 /* Sub-iter - calculate on the fly */
4523 VISIT(c, expr, gen->iter);
4524 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 }
4526
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004527 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004529 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004531 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004534 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535
4536 n = asdl_seq_LEN(gen->ifs);
4537 for (i = 0; i < n; i++) {
4538 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004539 if (!compiler_jump_if(c, e, if_cleanup, 0))
4540 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004541 NEXT_BLOCK(c);
4542 }
4543
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004544 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004545 if (++gen_index < asdl_seq_LEN(generators))
4546 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004547 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548 elt, val, type))
4549 return 0;
4550
4551 /* only append after the last for generator */
4552 if (gen_index >= asdl_seq_LEN(generators)) {
4553 /* comprehension specific code */
4554 switch (type) {
4555 case COMP_GENEXP:
4556 VISIT(c, expr, elt);
4557 ADDOP(c, YIELD_VALUE);
4558 ADDOP(c, POP_TOP);
4559 break;
4560 case COMP_LISTCOMP:
4561 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004562 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004563 break;
4564 case COMP_SETCOMP:
4565 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004566 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004567 break;
4568 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004569 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004570 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004571 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004572 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004573 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 break;
4575 default:
4576 return 0;
4577 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578 }
4579 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004580 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4581
4582 compiler_use_next_block(c, except);
4583 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004584
4585 return 1;
4586}
4587
4588static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004589compiler_comprehension(struct compiler *c, expr_ty e, int type,
4590 identifier name, asdl_seq *generators, expr_ty elt,
4591 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004594 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004595 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004596 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004597 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004598
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004599
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004600 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004601
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004602 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004603 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4604 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004605 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004607 }
4608
4609 is_async_generator = c->u->u_ste->ste_coroutine;
4610
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004611 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004612 compiler_error(c, "asynchronous comprehension outside of "
4613 "an asynchronous function");
4614 goto error_in_scope;
4615 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 if (type != COMP_GENEXP) {
4618 int op;
4619 switch (type) {
4620 case COMP_LISTCOMP:
4621 op = BUILD_LIST;
4622 break;
4623 case COMP_SETCOMP:
4624 op = BUILD_SET;
4625 break;
4626 case COMP_DICTCOMP:
4627 op = BUILD_MAP;
4628 break;
4629 default:
4630 PyErr_Format(PyExc_SystemError,
4631 "unknown comprehension type %d", type);
4632 goto error_in_scope;
4633 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 ADDOP_I(c, op, 0);
4636 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004637
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004638 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 val, type))
4640 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 if (type != COMP_GENEXP) {
4643 ADDOP(c, RETURN_VALUE);
4644 }
4645
4646 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004647 qualname = c->u->u_qualname;
4648 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004650 if (top_level_await && is_async_generator){
4651 c->u->u_ste->ste_coroutine = 1;
4652 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004653 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 goto error;
4655
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004656 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004658 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 Py_DECREF(co);
4660
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004661 VISIT(c, expr, outermost->iter);
4662
4663 if (outermost->is_async) {
4664 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004665 } else {
4666 ADDOP(c, GET_ITER);
4667 }
4668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004670
4671 if (is_async_generator && type != COMP_GENEXP) {
4672 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004673 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004674 ADDOP(c, YIELD_FROM);
4675 }
4676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004678error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004680error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004681 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 Py_XDECREF(co);
4683 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004684}
4685
4686static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004687compiler_genexp(struct compiler *c, expr_ty e)
4688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 static identifier name;
4690 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004691 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 if (!name)
4693 return 0;
4694 }
4695 assert(e->kind == GeneratorExp_kind);
4696 return compiler_comprehension(c, e, COMP_GENEXP, name,
4697 e->v.GeneratorExp.generators,
4698 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004699}
4700
4701static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004702compiler_listcomp(struct compiler *c, expr_ty e)
4703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 static identifier name;
4705 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004706 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 if (!name)
4708 return 0;
4709 }
4710 assert(e->kind == ListComp_kind);
4711 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4712 e->v.ListComp.generators,
4713 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004714}
4715
4716static int
4717compiler_setcomp(struct compiler *c, expr_ty e)
4718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 static identifier name;
4720 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004721 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 if (!name)
4723 return 0;
4724 }
4725 assert(e->kind == SetComp_kind);
4726 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4727 e->v.SetComp.generators,
4728 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004729}
4730
4731
4732static int
4733compiler_dictcomp(struct compiler *c, expr_ty e)
4734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 static identifier name;
4736 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004737 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 if (!name)
4739 return 0;
4740 }
4741 assert(e->kind == DictComp_kind);
4742 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4743 e->v.DictComp.generators,
4744 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004745}
4746
4747
4748static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004749compiler_visit_keyword(struct compiler *c, keyword_ty k)
4750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 VISIT(c, expr, k->value);
4752 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004753}
4754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004756 whether they are true or false.
4757
4758 Return values: 1 for true, 0 for false, -1 for non-constant.
4759 */
4760
4761static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004762expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004763{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004764 if (e->kind == Constant_kind) {
4765 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004766 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004767 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004768}
4769
Mark Shannonfee55262019-11-21 09:11:43 +00004770static int
4771compiler_with_except_finish(struct compiler *c) {
4772 basicblock *exit;
4773 exit = compiler_new_block(c);
4774 if (exit == NULL)
4775 return 0;
4776 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4777 ADDOP(c, RERAISE);
4778 compiler_use_next_block(c, exit);
4779 ADDOP(c, POP_TOP);
4780 ADDOP(c, POP_TOP);
4781 ADDOP(c, POP_TOP);
4782 ADDOP(c, POP_EXCEPT);
4783 ADDOP(c, POP_TOP);
4784 return 1;
4785}
Yury Selivanov75445082015-05-11 22:57:16 -04004786
4787/*
4788 Implements the async with statement.
4789
4790 The semantics outlined in that PEP are as follows:
4791
4792 async with EXPR as VAR:
4793 BLOCK
4794
4795 It is implemented roughly as:
4796
4797 context = EXPR
4798 exit = context.__aexit__ # not calling it
4799 value = await context.__aenter__()
4800 try:
4801 VAR = value # if VAR present in the syntax
4802 BLOCK
4803 finally:
4804 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004805 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004806 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004807 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004808 if not (await exit(*exc)):
4809 raise
4810 */
4811static int
4812compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4813{
Mark Shannonfee55262019-11-21 09:11:43 +00004814 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004815 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4816
4817 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004818 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004819 c->u->u_ste->ste_coroutine = 1;
4820 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004821 return compiler_error(c, "'async with' outside async function");
4822 }
Yury Selivanov75445082015-05-11 22:57:16 -04004823
4824 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004825 final = compiler_new_block(c);
4826 exit = compiler_new_block(c);
4827 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004828 return 0;
4829
4830 /* Evaluate EXPR */
4831 VISIT(c, expr, item->context_expr);
4832
4833 ADDOP(c, BEFORE_ASYNC_WITH);
4834 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004835 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004836 ADDOP(c, YIELD_FROM);
4837
Mark Shannonfee55262019-11-21 09:11:43 +00004838 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004839
4840 /* SETUP_ASYNC_WITH pushes a finally block. */
4841 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004842 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004843 return 0;
4844 }
4845
4846 if (item->optional_vars) {
4847 VISIT(c, expr, item->optional_vars);
4848 }
4849 else {
4850 /* Discard result from context.__aenter__() */
4851 ADDOP(c, POP_TOP);
4852 }
4853
4854 pos++;
4855 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4856 /* BLOCK code */
4857 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4858 else if (!compiler_async_with(c, s, pos))
4859 return 0;
4860
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004861 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004862 ADDOP(c, POP_BLOCK);
4863 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004864
Mark Shannonfee55262019-11-21 09:11:43 +00004865 /* For successful outcome:
4866 * call __exit__(None, None, None)
4867 */
4868 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004869 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004870 ADDOP(c, GET_AWAITABLE);
4871 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4872 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004873
Mark Shannonfee55262019-11-21 09:11:43 +00004874 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004875
Mark Shannonfee55262019-11-21 09:11:43 +00004876 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4877
4878 /* For exceptional outcome: */
4879 compiler_use_next_block(c, final);
4880
4881 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004882 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004883 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004884 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004885 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004886
Mark Shannonfee55262019-11-21 09:11:43 +00004887compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004888 return 1;
4889}
4890
4891
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892/*
4893 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004894 with EXPR as VAR:
4895 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004896 is implemented as:
4897 <code for EXPR>
4898 SETUP_WITH E
4899 <code to store to VAR> or POP_TOP
4900 <code for BLOCK>
4901 LOAD_CONST (None, None, None)
4902 CALL_FUNCTION_EX 0
4903 JUMP_FORWARD EXIT
4904 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4905 POP_JUMP_IF_TRUE T:
4906 RERAISE
4907 T: POP_TOP * 3 (remove exception from stack)
4908 POP_EXCEPT
4909 POP_TOP
4910 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911 */
Mark Shannonfee55262019-11-21 09:11:43 +00004912
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004914compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004915{
Mark Shannonfee55262019-11-21 09:11:43 +00004916 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004917 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918
4919 assert(s->kind == With_kind);
4920
Guido van Rossumc2e20742006-02-27 22:32:47 +00004921 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004922 final = compiler_new_block(c);
4923 exit = compiler_new_block(c);
4924 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004925 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004926
Thomas Wouters477c8d52006-05-27 19:21:47 +00004927 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004928 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004929 /* Will push bound __exit__ */
4930 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004931
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004932 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004933 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004934 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004935 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004936 }
4937
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004938 if (item->optional_vars) {
4939 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004940 }
4941 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004943 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004944 }
4945
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004946 pos++;
4947 if (pos == asdl_seq_LEN(s->v.With.items))
4948 /* BLOCK code */
4949 VISIT_SEQ(c, stmt, s->v.With.body)
4950 else if (!compiler_with(c, s, pos))
4951 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004952
Guido van Rossumc2e20742006-02-27 22:32:47 +00004953 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004954 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004955
Mark Shannonfee55262019-11-21 09:11:43 +00004956 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004957
Mark Shannonfee55262019-11-21 09:11:43 +00004958 /* For successful outcome:
4959 * call __exit__(None, None, None)
4960 */
4961 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004962 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004963 ADDOP(c, POP_TOP);
4964 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004965
Mark Shannonfee55262019-11-21 09:11:43 +00004966 /* For exceptional outcome: */
4967 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004968
Mark Shannonfee55262019-11-21 09:11:43 +00004969 ADDOP(c, WITH_EXCEPT_START);
4970 compiler_with_except_finish(c);
4971
4972 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004973 return 1;
4974}
4975
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004976static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004977compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004980 case NamedExpr_kind:
4981 VISIT(c, expr, e->v.NamedExpr.value);
4982 ADDOP(c, DUP_TOP);
4983 VISIT(c, expr, e->v.NamedExpr.target);
4984 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 case BoolOp_kind:
4986 return compiler_boolop(c, e);
4987 case BinOp_kind:
4988 VISIT(c, expr, e->v.BinOp.left);
4989 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004990 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 break;
4992 case UnaryOp_kind:
4993 VISIT(c, expr, e->v.UnaryOp.operand);
4994 ADDOP(c, unaryop(e->v.UnaryOp.op));
4995 break;
4996 case Lambda_kind:
4997 return compiler_lambda(c, e);
4998 case IfExp_kind:
4999 return compiler_ifexp(c, e);
5000 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005001 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005002 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005003 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 case GeneratorExp_kind:
5005 return compiler_genexp(c, e);
5006 case ListComp_kind:
5007 return compiler_listcomp(c, e);
5008 case SetComp_kind:
5009 return compiler_setcomp(c, e);
5010 case DictComp_kind:
5011 return compiler_dictcomp(c, e);
5012 case Yield_kind:
5013 if (c->u->u_ste->ste_type != FunctionBlock)
5014 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005015 if (e->v.Yield.value) {
5016 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 }
5018 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005019 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005021 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005023 case YieldFrom_kind:
5024 if (c->u->u_ste->ste_type != FunctionBlock)
5025 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005026
5027 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5028 return compiler_error(c, "'yield from' inside async function");
5029
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005030 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005031 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005032 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005033 ADDOP(c, YIELD_FROM);
5034 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005035 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005036 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005037 if (c->u->u_ste->ste_type != FunctionBlock){
5038 return compiler_error(c, "'await' outside function");
5039 }
Yury Selivanov75445082015-05-11 22:57:16 -04005040
Victor Stinner331a6a52019-05-27 16:39:22 +02005041 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005042 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5043 return compiler_error(c, "'await' outside async function");
5044 }
5045 }
Yury Selivanov75445082015-05-11 22:57:16 -04005046
5047 VISIT(c, expr, e->v.Await.value);
5048 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005050 ADDOP(c, YIELD_FROM);
5051 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 case Compare_kind:
5053 return compiler_compare(c, e);
5054 case Call_kind:
5055 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005056 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005057 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005058 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005059 case JoinedStr_kind:
5060 return compiler_joined_str(c, e);
5061 case FormattedValue_kind:
5062 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 /* The following exprs can be assignment targets. */
5064 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005065 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 case Load:
5068 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5069 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005071 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5072 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5074 break;
5075 case Del:
5076 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5077 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 }
5079 break;
5080 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005081 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 case Starred_kind:
5083 switch (e->v.Starred.ctx) {
5084 case Store:
5085 /* In all legitimate cases, the Starred node was already replaced
5086 * by compiler_list/compiler_tuple. XXX: is that okay? */
5087 return compiler_error(c,
5088 "starred assignment target must be in a list or tuple");
5089 default:
5090 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005091 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005093 break;
5094 case Slice_kind:
5095 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 case Name_kind:
5097 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5098 /* child nodes of List and Tuple will have expr_context set */
5099 case List_kind:
5100 return compiler_list(c, e);
5101 case Tuple_kind:
5102 return compiler_tuple(c, e);
5103 }
5104 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005105}
5106
5107static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005108compiler_visit_expr(struct compiler *c, expr_ty e)
5109{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005110 int old_lineno = c->u->u_lineno;
5111 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005112 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005113 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005114 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005115 c->u->u_col_offset = old_col_offset;
5116 return res;
5117}
5118
5119static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005120compiler_augassign(struct compiler *c, stmt_ty s)
5121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005123 expr_ty e = s->v.AugAssign.target;
5124
5125 int old_lineno = c->u->u_lineno;
5126 int old_col_offset = c->u->u_col_offset;
5127 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 switch (e->kind) {
5130 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005131 VISIT(c, expr, e->v.Attribute.value);
5132 ADDOP(c, DUP_TOP);
5133 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 break;
5135 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005136 VISIT(c, expr, e->v.Subscript.value);
5137 VISIT(c, expr, e->v.Subscript.slice);
5138 ADDOP(c, DUP_TOP_TWO);
5139 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 break;
5141 case Name_kind:
5142 if (!compiler_nameop(c, e->v.Name.id, Load))
5143 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005144 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 default:
5146 PyErr_Format(PyExc_SystemError,
5147 "invalid node type (%d) for augmented assignment",
5148 e->kind);
5149 return 0;
5150 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005151
5152 c->u->u_lineno = old_lineno;
5153 c->u->u_col_offset = old_col_offset;
5154
5155 VISIT(c, expr, s->v.AugAssign.value);
5156 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5157
5158 SET_LOC(c, e);
5159
5160 switch (e->kind) {
5161 case Attribute_kind:
5162 ADDOP(c, ROT_TWO);
5163 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5164 break;
5165 case Subscript_kind:
5166 ADDOP(c, ROT_THREE);
5167 ADDOP(c, STORE_SUBSCR);
5168 break;
5169 case Name_kind:
5170 return compiler_nameop(c, e->v.Name.id, Store);
5171 default:
5172 Py_UNREACHABLE();
5173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005175}
5176
5177static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005178check_ann_expr(struct compiler *c, expr_ty e)
5179{
5180 VISIT(c, expr, e);
5181 ADDOP(c, POP_TOP);
5182 return 1;
5183}
5184
5185static int
5186check_annotation(struct compiler *c, stmt_ty s)
5187{
5188 /* Annotations are only evaluated in a module or class. */
5189 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5190 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5191 return check_ann_expr(c, s->v.AnnAssign.annotation);
5192 }
5193 return 1;
5194}
5195
5196static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005197check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005198{
5199 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005200 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005201 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005202 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005203 return 0;
5204 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005205 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5206 return 0;
5207 }
5208 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5209 return 0;
5210 }
5211 return 1;
5212 case Tuple_kind: {
5213 /* extended slice */
5214 asdl_seq *elts = e->v.Tuple.elts;
5215 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005216 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005217 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005218 return 0;
5219 }
5220 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005221 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005223 default:
5224 return check_ann_expr(c, e);
5225 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005226}
5227
5228static int
5229compiler_annassign(struct compiler *c, stmt_ty s)
5230{
5231 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005232 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005233
5234 assert(s->kind == AnnAssign_kind);
5235
5236 /* We perform the actual assignment first. */
5237 if (s->v.AnnAssign.value) {
5238 VISIT(c, expr, s->v.AnnAssign.value);
5239 VISIT(c, expr, targ);
5240 }
5241 switch (targ->kind) {
5242 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005243 if (forbidden_name(c, targ->v.Name.id, Store))
5244 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005245 /* If we have a simple name in a module or class, store annotation. */
5246 if (s->v.AnnAssign.simple &&
5247 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5248 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005249 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5250 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5251 }
5252 else {
5253 VISIT(c, expr, s->v.AnnAssign.annotation);
5254 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005255 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005256 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005257 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005258 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005259 }
5260 break;
5261 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005262 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5263 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005264 if (!s->v.AnnAssign.value &&
5265 !check_ann_expr(c, targ->v.Attribute.value)) {
5266 return 0;
5267 }
5268 break;
5269 case Subscript_kind:
5270 if (!s->v.AnnAssign.value &&
5271 (!check_ann_expr(c, targ->v.Subscript.value) ||
5272 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5273 return 0;
5274 }
5275 break;
5276 default:
5277 PyErr_Format(PyExc_SystemError,
5278 "invalid node type (%d) for annotated assignment",
5279 targ->kind);
5280 return 0;
5281 }
5282 /* Annotation is evaluated last. */
5283 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5284 return 0;
5285 }
5286 return 1;
5287}
5288
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005289/* Raises a SyntaxError and returns 0.
5290 If something goes wrong, a different exception may be raised.
5291*/
5292
5293static int
5294compiler_error(struct compiler *c, const char *errstr)
5295{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005296 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005298
Victor Stinner14e461d2013-08-26 22:28:21 +02005299 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (!loc) {
5301 Py_INCREF(Py_None);
5302 loc = Py_None;
5303 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005304 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005305 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 if (!u)
5307 goto exit;
5308 v = Py_BuildValue("(zO)", errstr, u);
5309 if (!v)
5310 goto exit;
5311 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 Py_DECREF(loc);
5314 Py_XDECREF(u);
5315 Py_XDECREF(v);
5316 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317}
5318
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005319/* Emits a SyntaxWarning and returns 1 on success.
5320 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5321 and returns 0.
5322*/
5323static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005324compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005325{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005326 va_list vargs;
5327#ifdef HAVE_STDARG_PROTOTYPES
5328 va_start(vargs, format);
5329#else
5330 va_start(vargs);
5331#endif
5332 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5333 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005334 if (msg == NULL) {
5335 return 0;
5336 }
5337 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5338 c->u->u_lineno, NULL, NULL) < 0)
5339 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005340 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005341 /* Replace the SyntaxWarning exception with a SyntaxError
5342 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005343 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005344 assert(PyUnicode_AsUTF8(msg) != NULL);
5345 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005346 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005347 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005348 return 0;
5349 }
5350 Py_DECREF(msg);
5351 return 1;
5352}
5353
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005354static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005355compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005356{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005357 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005359
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005360 if (ctx == Load) {
5361 if (!check_subscripter(c, e->v.Subscript.value)) {
5362 return 0;
5363 }
5364 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5365 return 0;
5366 }
5367 }
5368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 case Store: op = STORE_SUBSCR; break;
5372 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005374 assert(op);
5375 VISIT(c, expr, e->v.Subscript.value);
5376 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 ADDOP(c, op);
5378 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379}
5380
5381static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005382compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 int n = 2;
5385 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 /* only handles the cases where BUILD_SLICE is emitted */
5388 if (s->v.Slice.lower) {
5389 VISIT(c, expr, s->v.Slice.lower);
5390 }
5391 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005392 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 if (s->v.Slice.upper) {
5396 VISIT(c, expr, s->v.Slice.upper);
5397 }
5398 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005399 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 }
5401
5402 if (s->v.Slice.step) {
5403 n++;
5404 VISIT(c, expr, s->v.Slice.step);
5405 }
5406 ADDOP_I(c, BUILD_SLICE, n);
5407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408}
5409
Thomas Wouters89f507f2006-12-13 04:49:30 +00005410/* End of the compiler section, beginning of the assembler section */
5411
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005412/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005413 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005414
5415 XXX must handle implicit jumps from one block to next
5416*/
5417
Thomas Wouters89f507f2006-12-13 04:49:30 +00005418struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 PyObject *a_bytecode; /* string containing bytecode */
5420 int a_offset; /* offset into bytecode */
5421 int a_nblocks; /* number of reachable blocks */
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005422 basicblock **a_reverse_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 PyObject *a_lnotab; /* string containing lnotab */
5424 int a_lnotab_off; /* offset into lnotab */
5425 int a_lineno; /* last lineno of emitted instruction */
5426 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005427};
5428
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005429static void
T. Wouters99b54d62019-09-12 07:05:33 -07005430dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431{
T. Wouters99b54d62019-09-12 07:05:33 -07005432
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005433 /* There is no real depth-first-search to do here because all the
5434 * blocks are emitted in topological order already, so we just need to
5435 * follow the b_next pointers and place them in a->a_reverse_postorder in
5436 * reverse order and make sure that the first one starts at 0. */
5437
5438 for (a->a_nblocks = 0; b != NULL; b = b->b_next) {
5439 a->a_reverse_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005441}
5442
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005443Py_LOCAL_INLINE(void)
5444stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005445{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005446 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005447 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 assert(b->b_startdepth < 0);
5449 b->b_startdepth = depth;
5450 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005451 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005452}
5453
5454/* Find the flow path that needs the largest stack. We assume that
5455 * cycles in the flow graph have no net effect on the stack depth.
5456 */
5457static int
5458stackdepth(struct compiler *c)
5459{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005460 basicblock *b, *entryblock = NULL;
5461 basicblock **stack, **sp;
5462 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 b->b_startdepth = INT_MIN;
5465 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005466 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 }
5468 if (!entryblock)
5469 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005470 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5471 if (!stack) {
5472 PyErr_NoMemory();
5473 return -1;
5474 }
5475
5476 sp = stack;
5477 stackdepth_push(&sp, entryblock, 0);
5478 while (sp != stack) {
5479 b = *--sp;
5480 int depth = b->b_startdepth;
5481 assert(depth >= 0);
5482 basicblock *next = b->b_next;
5483 for (int i = 0; i < b->b_iused; i++) {
5484 struct instr *instr = &b->b_instr[i];
5485 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5486 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005487 _Py_FatalErrorFormat(__func__,
5488 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005489 }
5490 int new_depth = depth + effect;
5491 if (new_depth > maxdepth) {
5492 maxdepth = new_depth;
5493 }
5494 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5495 if (instr->i_jrel || instr->i_jabs) {
5496 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5497 assert(effect != PY_INVALID_STACK_EFFECT);
5498 int target_depth = depth + effect;
5499 if (target_depth > maxdepth) {
5500 maxdepth = target_depth;
5501 }
5502 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005503 stackdepth_push(&sp, instr->i_target, target_depth);
5504 }
5505 depth = new_depth;
5506 if (instr->i_opcode == JUMP_ABSOLUTE ||
5507 instr->i_opcode == JUMP_FORWARD ||
5508 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005509 instr->i_opcode == RAISE_VARARGS ||
5510 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005511 {
5512 /* remaining code is dead */
5513 next = NULL;
5514 break;
5515 }
5516 }
5517 if (next != NULL) {
5518 stackdepth_push(&sp, next, depth);
5519 }
5520 }
5521 PyObject_Free(stack);
5522 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005523}
5524
5525static int
5526assemble_init(struct assembler *a, int nblocks, int firstlineno)
5527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 memset(a, 0, sizeof(struct assembler));
5529 a->a_lineno = firstlineno;
5530 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5531 if (!a->a_bytecode)
5532 return 0;
5533 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5534 if (!a->a_lnotab)
5535 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005536 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 PyErr_NoMemory();
5538 return 0;
5539 }
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005540 a->a_reverse_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 sizeof(basicblock *) * nblocks);
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005542 if (!a->a_reverse_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 PyErr_NoMemory();
5544 return 0;
5545 }
5546 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005547}
5548
5549static void
5550assemble_free(struct assembler *a)
5551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 Py_XDECREF(a->a_bytecode);
5553 Py_XDECREF(a->a_lnotab);
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005554 if (a->a_reverse_postorder)
5555 PyObject_Free(a->a_reverse_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005556}
5557
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005558static int
5559blocksize(basicblock *b)
5560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 int i;
5562 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005565 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005567}
5568
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005569/* Appends a pair to the end of the line number table, a_lnotab, representing
5570 the instruction's bytecode offset and line number. See
5571 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005572
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005573static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005574assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005577 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005581 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005583 }
5584
5585 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5586 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 if (d_bytecode > 255) {
5589 int j, nbytes, ncodes = d_bytecode / 255;
5590 nbytes = a->a_lnotab_off + 2 * ncodes;
5591 len = PyBytes_GET_SIZE(a->a_lnotab);
5592 if (nbytes >= len) {
5593 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5594 len = nbytes;
5595 else if (len <= INT_MAX / 2)
5596 len *= 2;
5597 else {
5598 PyErr_NoMemory();
5599 return 0;
5600 }
5601 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5602 return 0;
5603 }
5604 lnotab = (unsigned char *)
5605 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5606 for (j = 0; j < ncodes; j++) {
5607 *lnotab++ = 255;
5608 *lnotab++ = 0;
5609 }
5610 d_bytecode -= ncodes * 255;
5611 a->a_lnotab_off += ncodes * 2;
5612 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005613 assert(0 <= d_bytecode && d_bytecode <= 255);
5614
5615 if (d_lineno < -128 || 127 < d_lineno) {
5616 int j, nbytes, ncodes, k;
5617 if (d_lineno < 0) {
5618 k = -128;
5619 /* use division on positive numbers */
5620 ncodes = (-d_lineno) / 128;
5621 }
5622 else {
5623 k = 127;
5624 ncodes = d_lineno / 127;
5625 }
5626 d_lineno -= ncodes * k;
5627 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 nbytes = a->a_lnotab_off + 2 * ncodes;
5629 len = PyBytes_GET_SIZE(a->a_lnotab);
5630 if (nbytes >= len) {
5631 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5632 len = nbytes;
5633 else if (len <= INT_MAX / 2)
5634 len *= 2;
5635 else {
5636 PyErr_NoMemory();
5637 return 0;
5638 }
5639 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5640 return 0;
5641 }
5642 lnotab = (unsigned char *)
5643 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5644 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005645 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 d_bytecode = 0;
5647 for (j = 1; j < ncodes; j++) {
5648 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005649 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 a->a_lnotab_off += ncodes * 2;
5652 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005653 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 len = PyBytes_GET_SIZE(a->a_lnotab);
5656 if (a->a_lnotab_off + 2 >= len) {
5657 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5658 return 0;
5659 }
5660 lnotab = (unsigned char *)
5661 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 a->a_lnotab_off += 2;
5664 if (d_bytecode) {
5665 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005666 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 }
5668 else { /* First line of a block; def stmt, etc. */
5669 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005670 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 }
5672 a->a_lineno = i->i_lineno;
5673 a->a_lineno_off = a->a_offset;
5674 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005675}
5676
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005677/* assemble_emit()
5678 Extend the bytecode with a new instruction.
5679 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005680*/
5681
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005682static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005683assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005684{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005685 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005687 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005688
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005689 arg = i->i_oparg;
5690 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 if (i->i_lineno && !assemble_lnotab(a, i))
5692 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005693 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 if (len > PY_SSIZE_T_MAX / 2)
5695 return 0;
5696 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5697 return 0;
5698 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005699 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005701 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005703}
5704
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005705static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005706assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005709 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 /* Compute the size of each block and fixup jump args.
5713 Replace block pointer with position in bytecode. */
5714 do {
5715 totsize = 0;
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005716 for (i = 0; i < a->a_nblocks; i++) {
5717 b = a->a_reverse_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 bsize = blocksize(b);
5719 b->b_offset = totsize;
5720 totsize += bsize;
5721 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005722 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5724 bsize = b->b_offset;
5725 for (i = 0; i < b->b_iused; i++) {
5726 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005727 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 /* Relative jumps are computed relative to
5729 the instruction pointer after fetching
5730 the jump instruction.
5731 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005732 bsize += isize;
5733 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005735 if (instr->i_jrel) {
5736 instr->i_oparg -= bsize;
5737 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005738 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005739 if (instrsize(instr->i_oparg) != isize) {
5740 extended_arg_recompile = 1;
5741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 }
5744 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 /* XXX: This is an awful hack that could hurt performance, but
5747 on the bright side it should work until we come up
5748 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 The issue is that in the first loop blocksize() is called
5751 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005752 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 So we loop until we stop seeing new EXTENDED_ARGs.
5756 The only EXTENDED_ARGs that could be popping up are
5757 ones in jump instructions. So this should converge
5758 fairly quickly.
5759 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005760 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005761}
5762
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005763static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005764dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005767 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 tuple = PyTuple_New(size);
5770 if (tuple == NULL)
5771 return NULL;
5772 while (PyDict_Next(dict, &pos, &k, &v)) {
5773 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005774 Py_INCREF(k);
5775 assert((i - offset) < size);
5776 assert((i - offset) >= 0);
5777 PyTuple_SET_ITEM(tuple, i - offset, k);
5778 }
5779 return tuple;
5780}
5781
5782static PyObject *
5783consts_dict_keys_inorder(PyObject *dict)
5784{
5785 PyObject *consts, *k, *v;
5786 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5787
5788 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5789 if (consts == NULL)
5790 return NULL;
5791 while (PyDict_Next(dict, &pos, &k, &v)) {
5792 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005793 /* The keys of the dictionary can be tuples wrapping a contant.
5794 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5795 * the object we want is always second. */
5796 if (PyTuple_CheckExact(k)) {
5797 k = PyTuple_GET_ITEM(k, 1);
5798 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005800 assert(i < size);
5801 assert(i >= 0);
5802 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005804 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005805}
5806
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005807static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005808compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005811 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005813 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 if (ste->ste_nested)
5815 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005816 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005818 if (!ste->ste_generator && ste->ste_coroutine)
5819 flags |= CO_COROUTINE;
5820 if (ste->ste_generator && ste->ste_coroutine)
5821 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 if (ste->ste_varargs)
5823 flags |= CO_VARARGS;
5824 if (ste->ste_varkeywords)
5825 flags |= CO_VARKEYWORDS;
5826 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 /* (Only) inherit compilerflags in PyCF_MASK */
5829 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005830
Pablo Galindo90235812020-03-15 04:29:22 +00005831 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005832 ste->ste_coroutine &&
5833 !ste->ste_generator) {
5834 flags |= CO_COROUTINE;
5835 }
5836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005838}
5839
INADA Naokic2e16072018-11-26 21:23:22 +09005840// Merge *tuple* with constant cache.
5841// Unlike merge_consts_recursive(), this function doesn't work recursively.
5842static int
5843merge_const_tuple(struct compiler *c, PyObject **tuple)
5844{
5845 assert(PyTuple_CheckExact(*tuple));
5846
5847 PyObject *key = _PyCode_ConstantKey(*tuple);
5848 if (key == NULL) {
5849 return 0;
5850 }
5851
5852 // t is borrowed reference
5853 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5854 Py_DECREF(key);
5855 if (t == NULL) {
5856 return 0;
5857 }
5858 if (t == key) { // tuple is new constant.
5859 return 1;
5860 }
5861
5862 PyObject *u = PyTuple_GET_ITEM(t, 1);
5863 Py_INCREF(u);
5864 Py_DECREF(*tuple);
5865 *tuple = u;
5866 return 1;
5867}
5868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005869static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005870makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 PyObject *names = NULL;
5874 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 PyObject *name = NULL;
5876 PyObject *freevars = NULL;
5877 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005878 Py_ssize_t nlocals;
5879 int nlocals_int;
5880 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005881 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005883 names = dict_keys_inorder(c->u->u_names, 0);
5884 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005885 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5889 if (!cellvars)
5890 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005891 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 if (!freevars)
5893 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005894
INADA Naokic2e16072018-11-26 21:23:22 +09005895 if (!merge_const_tuple(c, &names) ||
5896 !merge_const_tuple(c, &varnames) ||
5897 !merge_const_tuple(c, &cellvars) ||
5898 !merge_const_tuple(c, &freevars))
5899 {
5900 goto error;
5901 }
5902
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005903 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005904 assert(nlocals < INT_MAX);
5905 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 flags = compute_code_flags(c);
5908 if (flags < 0)
5909 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005910
Mark Shannon6e8128f2020-07-30 10:03:00 +01005911 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5912 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005913 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005914 }
INADA Naokic2e16072018-11-26 21:23:22 +09005915 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005916 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005917 goto error;
5918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005920 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005921 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005922 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005923 maxdepth = stackdepth(c);
5924 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005925 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005926 goto error;
5927 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005928 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005929 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005930 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005931 varnames, freevars, cellvars, c->c_filename,
5932 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005933 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005934 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 Py_XDECREF(names);
5936 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005937 Py_XDECREF(name);
5938 Py_XDECREF(freevars);
5939 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005941}
5942
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005943
5944/* For debugging purposes only */
5945#if 0
5946static void
5947dump_instr(const struct instr *i)
5948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 const char *jrel = i->i_jrel ? "jrel " : "";
5950 const char *jabs = i->i_jabs ? "jabs " : "";
5951 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005954 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5958 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005959}
5960
5961static void
5962dump_basicblock(const basicblock *b)
5963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005964 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005965 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5966 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (b->b_instr) {
5968 int i;
5969 for (i = 0; i < b->b_iused; i++) {
5970 fprintf(stderr, " [%02d] ", i);
5971 dump_instr(b->b_instr + i);
5972 }
5973 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005974}
5975#endif
5976
Mark Shannon6e8128f2020-07-30 10:03:00 +01005977static int
5978optimize_cfg(struct assembler *a, PyObject *consts);
5979
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005980static PyCodeObject *
5981assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005983 basicblock *b, *entryblock;
5984 struct assembler a;
5985 int i, j, nblocks;
5986 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005987 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989 /* Make sure every block that falls off the end returns None.
5990 XXX NEXT_BLOCK() isn't quite right, because if the last
5991 block ends with a jump or return b_next shouldn't set.
5992 */
5993 if (!c->u->u_curblock->b_return) {
5994 NEXT_BLOCK(c);
5995 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005996 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 ADDOP(c, RETURN_VALUE);
5998 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 nblocks = 0;
6001 entryblock = NULL;
6002 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6003 nblocks++;
6004 entryblock = b;
6005 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 /* Set firstlineno if it wasn't explicitly set. */
6008 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006009 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6011 else
6012 c->u->u_firstlineno = 1;
6013 }
6014 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6015 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006016 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006017
Mark Shannon6e8128f2020-07-30 10:03:00 +01006018 consts = consts_dict_keys_inorder(c->u->u_consts);
6019 if (consts == NULL) {
6020 goto error;
6021 }
6022 if (optimize_cfg(&a, consts)) {
6023 goto error;
6024 }
6025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006026 /* Can't modify the bytecode after computing jump offsets. */
6027 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006028
T. Wouters99b54d62019-09-12 07:05:33 -07006029 /* Emit code in reverse postorder from dfs. */
Pablo Galindo60eb9f12020-06-28 01:55:47 +01006030 for (i = 0; i < a.a_nblocks; i++) {
6031 b = a.a_reverse_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006032 for (j = 0; j < b->b_iused; j++)
6033 if (!assemble_emit(&a, &b->b_instr[j]))
6034 goto error;
6035 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6038 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006039 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006041
Mark Shannon6e8128f2020-07-30 10:03:00 +01006042 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006043 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006044 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 assemble_free(&a);
6046 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006047}
Georg Brandl8334fd92010-12-04 10:26:46 +00006048
6049#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006050PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006051PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6052 PyArena *arena)
6053{
6054 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6055}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006056
6057
6058/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6059 with LOAD_CONST (c1, c2, ... cn).
6060 The consts table must still be in list form so that the
6061 new constant (c1, c2, ... cn) can be appended.
6062 Called with codestr pointing to the first LOAD_CONST.
6063*/
6064static int
6065fold_tuple_on_constants(struct instr *inst,
6066 int n, PyObject *consts)
6067{
6068 /* Pre-conditions */
6069 assert(PyList_CheckExact(consts));
6070 assert(inst[n].i_opcode == BUILD_TUPLE);
6071 assert(inst[n].i_oparg == n);
6072
6073 for (int i = 0; i < n; i++) {
6074 if (inst[i].i_opcode != LOAD_CONST) {
6075 return 0;
6076 }
6077 }
6078
6079 /* Buildup new tuple of constants */
6080 PyObject *newconst = PyTuple_New(n);
6081 if (newconst == NULL) {
6082 return -1;
6083 }
6084 for (int i = 0; i < n; i++) {
6085 int arg = inst[i].i_oparg;
6086 PyObject *constant = PyList_GET_ITEM(consts, arg);
6087 Py_INCREF(constant);
6088 PyTuple_SET_ITEM(newconst, i, constant);
6089 }
6090 Py_ssize_t index = PyList_GET_SIZE(consts);
6091#if SIZEOF_SIZE_T > SIZEOF_INT
6092 if ((size_t)index >= UINT_MAX - 1) {
6093 Py_DECREF(newconst);
6094 PyErr_SetString(PyExc_OverflowError, "too many constants");
6095 return -1;
6096 }
6097#endif
6098 if (PyList_Append(consts, newconst)) {
6099 Py_DECREF(newconst);
6100 return -1;
6101 }
6102 Py_DECREF(newconst);
6103 for (int i = 0; i < n; i++) {
6104 inst[i].i_opcode = NOP;
6105 }
6106 inst[n].i_opcode = LOAD_CONST;
6107 inst[n].i_oparg = index;
6108 return 0;
6109}
6110
6111
6112/* Optimization */
6113static int
6114optimize_basic_block(basicblock *bb, PyObject *consts)
6115{
6116 assert(PyList_CheckExact(consts));
6117 struct instr nop;
6118 nop.i_opcode = NOP;
6119 struct instr *target;
6120 int lineno;
6121 for (int i = 0; i < bb->b_iused; i++) {
6122 struct instr *inst = &bb->b_instr[i];
6123 int oparg = inst->i_oparg;
6124 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
6125 if (inst->i_jabs || inst->i_jrel) {
6126 /* Skip over empty basic blocks. */
6127 while (inst->i_target->b_iused == 0) {
6128 inst->i_target = inst->i_target->b_next;
6129 }
6130 target = &inst->i_target->b_instr[0];
6131 }
6132 else {
6133 target = &nop;
6134 }
6135 switch (inst->i_opcode) {
6136 /* Skip over LOAD_CONST trueconst
6137 POP_JUMP_IF_FALSE xx. This improves
6138 "while 1" performance. */
6139 case LOAD_CONST:
6140 if (nextop != POP_JUMP_IF_FALSE) {
6141 break;
6142 }
6143 PyObject* cnt = PyList_GET_ITEM(consts, oparg);
6144 int is_true = PyObject_IsTrue(cnt);
6145 if (is_true == -1) {
6146 goto error;
6147 }
6148 if (is_true == 1) {
6149 inst->i_opcode = NOP;
6150 bb->b_instr[i+1].i_opcode = NOP;
6151 bb->b_instr[i+1].i_jabs = 0;
6152 }
6153 break;
6154
6155 /* Try to fold tuples of constants.
6156 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6157 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6158 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6159 case BUILD_TUPLE:
6160 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6161 switch(oparg) {
6162 case 1:
6163 inst->i_opcode = NOP;
6164 bb->b_instr[i+1].i_opcode = NOP;
6165 break;
6166 case 2:
6167 inst->i_opcode = ROT_TWO;
6168 bb->b_instr[i+1].i_opcode = NOP;
6169 break;
6170 case 3:
6171 inst->i_opcode = ROT_THREE;
6172 bb->b_instr[i+1].i_opcode = ROT_TWO;
6173 }
6174 break;
6175 }
6176 if (i >= oparg) {
6177 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6178 goto error;
6179 }
6180 }
6181 break;
6182
6183 /* Simplify conditional jump to conditional jump where the
6184 result of the first test implies the success of a similar
6185 test or the failure of the opposite test.
6186 Arises in code like:
6187 "a and b or c"
6188 "(a and b) and c"
6189 "(a or b) or c"
6190 "(a or b) and c"
6191 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6192 --> x:JUMP_IF_FALSE_OR_POP z
6193 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6194 --> x:POP_JUMP_IF_FALSE y+1
6195 where y+1 is the instruction following the second test.
6196 */
6197 case JUMP_IF_FALSE_OR_POP:
6198 switch(target->i_opcode) {
6199 case POP_JUMP_IF_FALSE:
6200 *inst = *target;
6201 break;
6202 case JUMP_ABSOLUTE:
6203 case JUMP_FORWARD:
6204 case JUMP_IF_FALSE_OR_POP:
6205 inst->i_target = target->i_target;
6206 break;
6207 case JUMP_IF_TRUE_OR_POP:
6208 assert (inst->i_target->b_iused == 1);
6209 inst->i_opcode = POP_JUMP_IF_FALSE;
6210 inst->i_target = inst->i_target->b_next;
6211 break;
6212 }
6213 break;
6214
6215 case JUMP_IF_TRUE_OR_POP:
6216 switch(target->i_opcode) {
6217 case POP_JUMP_IF_TRUE:
6218 *inst = *target;
6219 break;
6220 case JUMP_ABSOLUTE:
6221 case JUMP_FORWARD:
6222 case JUMP_IF_TRUE_OR_POP:
6223 inst->i_target = target->i_target;
6224 break;
6225 case JUMP_IF_FALSE_OR_POP:
6226 assert (inst->i_target->b_iused == 1);
6227 inst->i_opcode = POP_JUMP_IF_TRUE;
6228 inst->i_target = inst->i_target->b_next;
6229 break;
6230 }
6231 break;
6232
6233 case POP_JUMP_IF_FALSE:
6234 switch(target->i_opcode) {
6235 case JUMP_ABSOLUTE:
6236 case JUMP_FORWARD:
6237 inst->i_target = target->i_target;
6238 break;
6239 }
6240 break;
6241
6242 case POP_JUMP_IF_TRUE:
6243 switch(target->i_opcode) {
6244 case JUMP_ABSOLUTE:
6245 case JUMP_FORWARD:
6246 inst->i_target = target->i_target;
6247 break;
6248 }
6249 break;
6250
6251 case JUMP_ABSOLUTE:
6252 case JUMP_FORWARD:
6253 switch(target->i_opcode) {
6254 case JUMP_FORWARD:
6255 inst->i_target = target->i_target;
6256 break;
6257 case JUMP_ABSOLUTE:
6258 case RETURN_VALUE:
6259 case RERAISE:
6260 case RAISE_VARARGS:
6261 lineno = inst->i_lineno;
6262 *inst = *target;
6263 inst->i_lineno = lineno;
6264 break;
6265 }
6266 break;
6267 }
6268 }
6269 return 0;
6270error:
6271 return -1;
6272}
6273
6274
6275static void
6276clean_basic_block(basicblock *bb) {
6277 /* Remove NOPs and any code following a return or re-raise. */
6278 int dest = 0;
6279 for (int src = 0; src < bb->b_iused; src++) {
6280 switch(bb->b_instr[src].i_opcode) {
6281 case NOP:
6282 /* skip */
6283 break;
6284 case RETURN_VALUE:
6285 case RERAISE:
6286 bb->b_next = NULL;
6287 bb->b_instr[dest] = bb->b_instr[src];
6288 dest++;
6289 goto end;
6290 default:
6291 if (dest != src) {
6292 bb->b_instr[dest] = bb->b_instr[src];
6293 }
6294 dest++;
6295 break;
6296 }
6297 }
6298end:
6299 assert(dest <= bb->b_iused);
6300 bb->b_iused = dest;
6301}
6302
6303static int
6304mark_reachable(struct assembler *a) {
6305 basicblock **stack, **sp;
6306 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6307 if (stack == NULL) {
6308 return -1;
6309 }
6310 basicblock *entry = a->a_reverse_postorder[0];
6311 entry->b_reachable = 1;
6312 *sp++ = entry;
6313 while (sp > stack) {
6314 basicblock *b = *(--sp);
6315 if (b->b_next && b->b_next->b_reachable == 0) {
6316 b->b_next->b_reachable = 1;
6317 *sp++ = b->b_next;
6318 }
6319 for (int i = 0; i < b->b_iused; i++) {
6320 basicblock *target;
6321 if (b->b_instr[i].i_jrel || b->b_instr[i].i_jabs) {
6322 target = b->b_instr[i].i_target;
6323 if (target->b_reachable == 0) {
6324 target->b_reachable = 1;
6325 *sp++ = target;
6326 }
6327 }
6328 }
6329 }
6330 PyObject_Free(stack);
6331 return 0;
6332}
6333
6334
6335/* Perform basic peephole optimizations on a control flow graph.
6336 The consts object should still be in list form to allow new constants
6337 to be appended.
6338
6339 All transformations keep the code size the same or smaller.
6340 For those that reduce size, the gaps are initially filled with
6341 NOPs. Later those NOPs are removed.
6342*/
6343
6344static int
6345optimize_cfg(struct assembler *a, PyObject *consts)
6346{
6347 for (int i = 0; i < a->a_nblocks; i++) {
6348 if (optimize_basic_block(a->a_reverse_postorder[i], consts)) {
6349 return -1;
6350 }
6351 clean_basic_block(a->a_reverse_postorder[i]);
6352 assert(a->a_reverse_postorder[i]->b_reachable == 0);
6353 }
6354 if (mark_reachable(a)) {
6355 return -1;
6356 }
6357 /* Delete unreachable instructions */
6358 for (int i = 0; i < a->a_nblocks; i++) {
6359 if (a->a_reverse_postorder[i]->b_reachable == 0) {
6360 a->a_reverse_postorder[i]->b_iused = 0;
6361 }
6362 }
6363 return 0;
6364}
6365
6366/* Retained for API compatibility.
6367 * Optimization is now done in optimize_cfg */
6368
6369PyObject *
6370PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6371 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6372{
6373 Py_INCREF(code);
6374 return code;
6375}
6376