blob: 1d16e69a08556cf9340a4723c299988409c96e24 [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.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
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
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
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 *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static 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);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, 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,
215 expr_ty elt, expr_ty val, int type);
216
217static int compiler_async_comprehension_generator(
218 struct compiler *c,
219 asdl_seq *generators, int gen_index,
220 expr_ty elt, expr_ty val, int type);
221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000223static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400225#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* Name mangling: __private becomes _classname__private.
231 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 PyObject *result;
233 size_t nlen, plen, ipriv;
234 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 PyUnicode_READ_CHAR(ident, 0) != '_' ||
237 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident;
240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 nlen = PyUnicode_GET_LENGTH(ident);
242 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 The only time a name with a dot can occur is when
246 we are compiling an import statement that has a
247 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 TODO(jhylton): Decide whether we want to support
250 mangling of the module name, e.g. __M.X.
251 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
253 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
254 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_INCREF(ident);
256 return ident; /* Don't mangle __whatever__ */
257 }
258 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 ipriv = 0;
260 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
261 ipriv++;
262 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_INCREF(ident);
264 return ident; /* Don't mangle if class is just underscores */
265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000267
Antoine Pitrou55bff892013-04-06 21:21:04 +0200268 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
269 PyErr_SetString(PyExc_OverflowError,
270 "private identifier too large to be mangled");
271 return NULL;
272 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
275 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
276 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
277
278 result = PyUnicode_New(1 + nlen + plen, maxchar);
279 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
282 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200283 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
284 Py_DECREF(result);
285 return NULL;
286 }
287 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
288 Py_DECREF(result);
289 return NULL;
290 }
Victor Stinner8f825062012-04-27 13:55:39 +0200291 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000293}
294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295static int
296compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299
INADA Naokic2e16072018-11-26 21:23:22 +0900300 c->c_const_cache = PyDict_New();
301 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900303 }
304
305 c->c_stack = PyList_New(0);
306 if (!c->c_stack) {
307 Py_CLEAR(c->c_const_cache);
308 return 0;
309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312}
313
314PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200315PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
316 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 struct compiler c;
319 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200320 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200322 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!__doc__) {
325 __doc__ = PyUnicode_InternFromString("__doc__");
326 if (!__doc__)
327 return NULL;
328 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000329 if (!__annotations__) {
330 __annotations__ = PyUnicode_InternFromString("__annotations__");
331 if (!__annotations__)
332 return NULL;
333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!compiler_init(&c))
335 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 c.c_filename = filename;
338 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200339 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (c.c_future == NULL)
341 goto finally;
342 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 flags = &local_flags;
344 }
345 merged = c.c_future->ff_features | flags->cf_flags;
346 c.c_future->ff_features = merged;
347 flags->cf_flags = merged;
348 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200349 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100351 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200353 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900354 goto finally;
355 }
356
Victor Stinner14e461d2013-08-26 22:28:21 +0200357 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (c.c_st == NULL) {
359 if (!PyErr_Occurred())
360 PyErr_SetString(PyExc_SystemError, "no symtable");
361 goto finally;
362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Thomas Wouters1175c432006-02-27 22:49:54 +0000366 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 compiler_free(&c);
368 assert(co || PyErr_Occurred());
369 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370}
371
372PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200373PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
374 int optimize, PyArena *arena)
375{
376 PyObject *filename;
377 PyCodeObject *co;
378 filename = PyUnicode_DecodeFSDefault(filename_str);
379 if (filename == NULL)
380 return NULL;
381 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
382 Py_DECREF(filename);
383 return co;
384
385}
386
387PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388PyNode_Compile(struct _node *n, const char *filename)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyCodeObject *co = NULL;
391 mod_ty mod;
392 PyArena *arena = PyArena_New();
393 if (!arena)
394 return NULL;
395 mod = PyAST_FromNode(n, NULL, filename, arena);
396 if (mod)
397 co = PyAST_Compile(mod, filename, NULL, arena);
398 PyArena_Free(arena);
399 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000400}
401
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (c->c_st)
406 PySymtable_Free(c->c_st);
407 if (c->c_future)
408 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200409 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900410 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000412}
413
Guido van Rossum79f25d91997-04-29 20:08:16 +0000414static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_ssize_t i, n;
418 PyObject *v, *k;
419 PyObject *dict = PyDict_New();
420 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 n = PyList_Size(list);
423 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100424 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (!v) {
426 Py_DECREF(dict);
427 return NULL;
428 }
429 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300430 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(v);
432 Py_DECREF(dict);
433 return NULL;
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(v);
436 }
437 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438}
439
440/* Return new dict containing names from src that match scope(s).
441
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000442src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444values are integers, starting at offset and increasing by one for
445each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446*/
447
448static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100449dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700451 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500453 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 assert(offset >= 0);
456 if (dest == NULL)
457 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Meador Inge2ca63152012-07-18 14:20:11 -0500459 /* Sort the keys so that we have a deterministic order on the indexes
460 saved in the returned dictionary. These indexes are used as indexes
461 into the free and cell var storage. Therefore if they aren't
462 deterministic, then the generated bytecode is not deterministic.
463 */
464 sorted_keys = PyDict_Keys(src);
465 if (sorted_keys == NULL)
466 return NULL;
467 if (PyList_Sort(sorted_keys) != 0) {
468 Py_DECREF(sorted_keys);
469 return NULL;
470 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500471 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500472
473 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* XXX this should probably be a macro in symtable.h */
475 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500476 k = PyList_GET_ITEM(sorted_keys, key_i);
477 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 assert(PyLong_Check(v));
479 vi = PyLong_AS_LONG(v);
480 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300483 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_DECREF(dest);
487 return NULL;
488 }
489 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300490 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(item);
493 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
496 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
498 }
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000501}
502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503static void
504compiler_unit_check(struct compiler_unit *u)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 basicblock *block;
507 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700508 assert((uintptr_t)block != 0xcbcbcbcbU);
509 assert((uintptr_t)block != 0xfbfbfbfbU);
510 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (block->b_instr != NULL) {
512 assert(block->b_ialloc > 0);
513 assert(block->b_iused > 0);
514 assert(block->b_ialloc >= block->b_iused);
515 }
516 else {
517 assert (block->b_iused == 0);
518 assert (block->b_ialloc == 0);
519 }
520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521}
522
523static void
524compiler_unit_free(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 compiler_unit_check(u);
529 b = u->u_blocks;
530 while (b != NULL) {
531 if (b->b_instr)
532 PyObject_Free((void *)b->b_instr);
533 next = b->b_list;
534 PyObject_Free((void *)b);
535 b = next;
536 }
537 Py_CLEAR(u->u_ste);
538 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400539 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_CLEAR(u->u_consts);
541 Py_CLEAR(u->u_names);
542 Py_CLEAR(u->u_varnames);
543 Py_CLEAR(u->u_freevars);
544 Py_CLEAR(u->u_cellvars);
545 Py_CLEAR(u->u_private);
546 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547}
548
549static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100550compiler_enter_scope(struct compiler *c, identifier name,
551 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100554 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
557 struct compiler_unit));
558 if (!u) {
559 PyErr_NoMemory();
560 return 0;
561 }
562 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100563 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100565 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 u->u_kwonlyargcount = 0;
567 u->u_ste = PySymtable_Lookup(c->c_st, key);
568 if (!u->u_ste) {
569 compiler_unit_free(u);
570 return 0;
571 }
572 Py_INCREF(name);
573 u->u_name = name;
574 u->u_varnames = list2dict(u->u_ste->ste_varnames);
575 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
576 if (!u->u_varnames || !u->u_cellvars) {
577 compiler_unit_free(u);
578 return 0;
579 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000581 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300583 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 int res;
585 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200586 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 name = _PyUnicode_FromId(&PyId___class__);
588 if (!name) {
589 compiler_unit_free(u);
590 return 0;
591 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300592 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (res < 0) {
594 compiler_unit_free(u);
595 return 0;
596 }
597 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200600 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (!u->u_freevars) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_blocks = NULL;
607 u->u_nfblocks = 0;
608 u->u_firstlineno = lineno;
609 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000610 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_lineno_set = 0;
612 u->u_consts = PyDict_New();
613 if (!u->u_consts) {
614 compiler_unit_free(u);
615 return 0;
616 }
617 u->u_names = PyDict_New();
618 if (!u->u_names) {
619 compiler_unit_free(u);
620 return 0;
621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Push the old compiler_unit on the stack. */
626 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400627 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
629 Py_XDECREF(capsule);
630 compiler_unit_free(u);
631 return 0;
632 }
633 Py_DECREF(capsule);
634 u->u_private = c->u->u_private;
635 Py_XINCREF(u->u_private);
636 }
637 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100640
641 block = compiler_new_block(c);
642 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100644 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400646 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
647 if (!compiler_set_qualname(c))
648 return 0;
649 }
650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652}
653
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000654static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655compiler_exit_scope(struct compiler *c)
656{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100657 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 c->c_nestlevel--;
661 compiler_unit_free(c->u);
662 /* Restore c->u to the parent unit. */
663 n = PyList_GET_SIZE(c->c_stack) - 1;
664 if (n >= 0) {
665 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400666 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(c->u);
668 /* we are deleting from a list so this really shouldn't fail */
669 if (PySequence_DelItem(c->c_stack, n) < 0)
670 Py_FatalError("compiler_exit_scope()");
671 compiler_unit_check(c->u);
672 }
673 else
674 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678static int
679compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 _Py_static_string(dot_locals, ".<locals>");
683 Py_ssize_t stack_size;
684 struct compiler_unit *u = c->u;
685 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100686
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400689 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 if (stack_size > 1) {
691 int scope, force_global = 0;
692 struct compiler_unit *parent;
693 PyObject *mangled, *capsule;
694
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400695 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400696 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 assert(parent);
698
Yury Selivanov75445082015-05-11 22:57:16 -0400699 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
700 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
701 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 assert(u->u_name);
703 mangled = _Py_Mangle(parent->u_private, u->u_name);
704 if (!mangled)
705 return 0;
706 scope = PyST_GetScope(parent->u_ste, mangled);
707 Py_DECREF(mangled);
708 assert(scope != GLOBAL_IMPLICIT);
709 if (scope == GLOBAL_EXPLICIT)
710 force_global = 1;
711 }
712
713 if (!force_global) {
714 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400715 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400716 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
717 dot_locals_str = _PyUnicode_FromId(&dot_locals);
718 if (dot_locals_str == NULL)
719 return 0;
720 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
721 if (base == NULL)
722 return 0;
723 }
724 else {
725 Py_INCREF(parent->u_qualname);
726 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728 }
729 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 if (base != NULL) {
732 dot_str = _PyUnicode_FromId(&dot);
733 if (dot_str == NULL) {
734 Py_DECREF(base);
735 return 0;
736 }
737 name = PyUnicode_Concat(base, dot_str);
738 Py_DECREF(base);
739 if (name == NULL)
740 return 0;
741 PyUnicode_Append(&name, u->u_name);
742 if (name == NULL)
743 return 0;
744 }
745 else {
746 Py_INCREF(u->u_name);
747 name = u->u_name;
748 }
749 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100750
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400751 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100752}
753
Eric V. Smith235a6f02015-09-19 14:51:32 -0400754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755/* Allocate a new block and return a pointer to it.
756 Returns NULL on error.
757*/
758
759static basicblock *
760compiler_new_block(struct compiler *c)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 basicblock *b;
763 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 u = c->u;
766 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
767 if (b == NULL) {
768 PyErr_NoMemory();
769 return NULL;
770 }
771 memset((void *)b, 0, sizeof(basicblock));
772 /* Extend the singly linked list of blocks with new block. */
773 b->b_list = u->u_blocks;
774 u->u_blocks = b;
775 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779compiler_next_block(struct compiler *c)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 basicblock *block = compiler_new_block(c);
782 if (block == NULL)
783 return NULL;
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789static basicblock *
790compiler_use_next_block(struct compiler *c, basicblock *block)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(block != NULL);
793 c->u->u_curblock->b_next = block;
794 c->u->u_curblock = block;
795 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796}
797
798/* Returns the offset of the next instruction in the current block's
799 b_instr array. Resizes the b_instr as necessary.
800 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802
803static int
804compiler_next_instr(struct compiler *c, basicblock *b)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(b != NULL);
807 if (b->b_instr == NULL) {
808 b->b_instr = (struct instr *)PyObject_Malloc(
809 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
810 if (b->b_instr == NULL) {
811 PyErr_NoMemory();
812 return -1;
813 }
814 b->b_ialloc = DEFAULT_BLOCK_SIZE;
815 memset((char *)b->b_instr, 0,
816 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
817 }
818 else if (b->b_iused == b->b_ialloc) {
819 struct instr *tmp;
820 size_t oldsize, newsize;
821 oldsize = b->b_ialloc * sizeof(struct instr);
822 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000823
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700824 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_NoMemory();
826 return -1;
827 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (newsize == 0) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 b->b_ialloc <<= 1;
834 tmp = (struct instr *)PyObject_Realloc(
835 (void *)b->b_instr, newsize);
836 if (tmp == NULL) {
837 PyErr_NoMemory();
838 return -1;
839 }
840 b->b_instr = tmp;
841 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
842 }
843 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844}
845
Christian Heimes2202f872008-02-06 14:31:34 +0000846/* Set the i_lineno member of the instruction at offset off if the
847 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 already been set. If it has been set, the call has no effect.
849
Christian Heimes2202f872008-02-06 14:31:34 +0000850 The line number is reset in the following cases:
851 - when entering a new scope
852 - on each statement
853 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200854 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000855 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858static void
859compiler_set_lineno(struct compiler *c, int off)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 basicblock *b;
862 if (c->u->u_lineno_set)
863 return;
864 c->u->u_lineno_set = 1;
865 b = c->u->u_curblock;
866 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867}
868
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200869/* Return the stack effect of opcode with argument oparg.
870
871 Some opcodes have different stack effect when jump to the target and
872 when not jump. The 'jump' parameter specifies the case:
873
874 * 0 -- when not jump
875 * 1 -- when jump
876 * -1 -- maximal
877 */
878/* XXX Make the stack effect of WITH_CLEANUP_START and
879 WITH_CLEANUP_FINISH deterministic. */
880static int
881stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300884 case NOP:
885 case EXTENDED_ARG:
886 return 0;
887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case POP_TOP:
890 return -1;
891 case ROT_TWO:
892 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200893 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return 0;
895 case DUP_TOP:
896 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000897 case DUP_TOP_TWO:
898 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case UNARY_POSITIVE:
902 case UNARY_NEGATIVE:
903 case UNARY_NOT:
904 case UNARY_INVERT:
905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case SET_ADD:
908 case LIST_APPEND:
909 return -1;
910 case MAP_ADD:
911 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000912
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200913 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_POWER:
915 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400916 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_MODULO:
918 case BINARY_ADD:
919 case BINARY_SUBTRACT:
920 case BINARY_SUBSCR:
921 case BINARY_FLOOR_DIVIDE:
922 case BINARY_TRUE_DIVIDE:
923 return -1;
924 case INPLACE_FLOOR_DIVIDE:
925 case INPLACE_TRUE_DIVIDE:
926 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case INPLACE_ADD:
929 case INPLACE_SUBTRACT:
930 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400931 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case INPLACE_MODULO:
933 return -1;
934 case STORE_SUBSCR:
935 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case DELETE_SUBSCR:
937 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case BINARY_LSHIFT:
940 case BINARY_RSHIFT:
941 case BINARY_AND:
942 case BINARY_XOR:
943 case BINARY_OR:
944 return -1;
945 case INPLACE_POWER:
946 return -1;
947 case GET_ITER:
948 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case PRINT_EXPR:
951 return -1;
952 case LOAD_BUILD_CLASS:
953 return 1;
954 case INPLACE_LSHIFT:
955 case INPLACE_RSHIFT:
956 case INPLACE_AND:
957 case INPLACE_XOR:
958 case INPLACE_OR:
959 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* 1 in the normal flow.
963 * Restore the stack position and push 6 values before jumping to
964 * the handler if an exception be raised. */
965 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case RETURN_VALUE:
967 return -1;
968 case IMPORT_STAR:
969 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700970 case SETUP_ANNOTATIONS:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case YIELD_VALUE:
973 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500974 case YIELD_FROM:
975 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case POP_BLOCK:
977 return 0;
978 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_NAME:
982 return -1;
983 case DELETE_NAME:
984 return 0;
985 case UNPACK_SEQUENCE:
986 return oparg-1;
987 case UNPACK_EX:
988 return (oparg&0xFF) + (oparg>>8);
989 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200990 /* -1 at end of iterator, 1 if continue iterating. */
991 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case STORE_ATTR:
994 return -2;
995 case DELETE_ATTR:
996 return -1;
997 case STORE_GLOBAL:
998 return -1;
999 case DELETE_GLOBAL:
1000 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CONST:
1002 return 1;
1003 case LOAD_NAME:
1004 return 1;
1005 case BUILD_TUPLE:
1006 case BUILD_LIST:
1007 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001008 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_LIST_UNPACK:
1011 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001012 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_SET_UNPACK:
1014 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001015 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001016 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001018 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001019 case BUILD_CONST_KEY_MAP:
1020 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_ATTR:
1022 return 0;
1023 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001024 case IS_OP:
1025 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001027 case JUMP_IF_NOT_EXC_MATCH:
1028 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case IMPORT_NAME:
1030 return -1;
1031 case IMPORT_FROM:
1032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001034 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case JUMP_ABSOLUTE:
1037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001039 case JUMP_IF_TRUE_OR_POP:
1040 case JUMP_IF_FALSE_OR_POP:
1041 return jump ? 0 : -1;
1042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case POP_JUMP_IF_FALSE:
1044 case POP_JUMP_IF_TRUE:
1045 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case LOAD_GLOBAL:
1048 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001050 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001052 /* 0 in the normal flow.
1053 * Restore the stack position and push 6 values before jumping to
1054 * the handler if an exception be raised. */
1055 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001056 case RERAISE:
1057 return -3;
1058
1059 case WITH_EXCEPT_START:
1060 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 case LOAD_FAST:
1063 return 1;
1064 case STORE_FAST:
1065 return -1;
1066 case DELETE_FAST:
1067 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case RAISE_VARARGS:
1070 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001071
1072 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001075 case CALL_METHOD:
1076 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001078 return -oparg-1;
1079 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001080 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001081 case MAKE_FUNCTION:
1082 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1083 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 case BUILD_SLICE:
1085 if (oparg == 3)
1086 return -2;
1087 else
1088 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001090 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case LOAD_CLOSURE:
1092 return 1;
1093 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001094 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return 1;
1096 case STORE_DEREF:
1097 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001098 case DELETE_DEREF:
1099 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100
1101 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001102 case GET_AWAITABLE:
1103 return 0;
1104 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001105 /* 0 in the normal flow.
1106 * Restore the stack position to the position before the result
1107 * of __aenter__ and push 6 values before jumping to the handler
1108 * if an exception be raised. */
1109 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001110 case BEFORE_ASYNC_WITH:
1111 return 1;
1112 case GET_AITER:
1113 return 0;
1114 case GET_ANEXT:
1115 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116 case GET_YIELD_FROM_ITER:
1117 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001118 case END_ASYNC_FOR:
1119 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001120 case FORMAT_VALUE:
1121 /* If there's a fmt_spec on the stack, we go from 2->1,
1122 else 1->1. */
1123 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001124 case LOAD_METHOD:
1125 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001126 case LOAD_ASSERTION_ERROR:
1127 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001129 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Larry Hastings3a907972013-11-23 14:49:22 -08001131 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001134int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001135PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1136{
1137 return stack_effect(opcode, oparg, jump);
1138}
1139
1140int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001141PyCompile_OpcodeStackEffect(int opcode, int oparg)
1142{
1143 return stack_effect(opcode, oparg, -1);
1144}
1145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146/* Add an opcode with no argument.
1147 Returns 0 on failure, 1 on success.
1148*/
1149
1150static int
1151compiler_addop(struct compiler *c, int opcode)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 basicblock *b;
1154 struct instr *i;
1155 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001156 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001157 if (c->c_do_not_emit_bytecode) {
1158 return 1;
1159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 off = compiler_next_instr(c, c->u->u_curblock);
1161 if (off < 0)
1162 return 0;
1163 b = c->u->u_curblock;
1164 i = &b->b_instr[off];
1165 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001166 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (opcode == RETURN_VALUE)
1168 b->b_return = 1;
1169 compiler_set_lineno(c, off);
1170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171}
1172
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1175{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001176 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001179 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001181 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001183 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001184 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001185 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return -1;
1188 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001189 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 Py_DECREF(v);
1191 return -1;
1192 }
1193 Py_DECREF(v);
1194 }
1195 else
1196 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001197 return arg;
1198}
1199
INADA Naokic2e16072018-11-26 21:23:22 +09001200// Merge const *o* recursively and return constant key object.
1201static PyObject*
1202merge_consts_recursive(struct compiler *c, PyObject *o)
1203{
1204 // None and Ellipsis are singleton, and key is the singleton.
1205 // No need to merge object and key.
1206 if (o == Py_None || o == Py_Ellipsis) {
1207 Py_INCREF(o);
1208 return o;
1209 }
1210
1211 PyObject *key = _PyCode_ConstantKey(o);
1212 if (key == NULL) {
1213 return NULL;
1214 }
1215
1216 // t is borrowed reference
1217 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1218 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001219 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001220 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001221 Py_DECREF(key);
1222 return t;
1223 }
1224
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001226 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001227 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001228 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 Py_ssize_t len = PyTuple_GET_SIZE(o);
1230 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001231 PyObject *item = PyTuple_GET_ITEM(o, i);
1232 PyObject *u = merge_consts_recursive(c, item);
1233 if (u == NULL) {
1234 Py_DECREF(key);
1235 return NULL;
1236 }
1237
1238 // See _PyCode_ConstantKey()
1239 PyObject *v; // borrowed
1240 if (PyTuple_CheckExact(u)) {
1241 v = PyTuple_GET_ITEM(u, 1);
1242 }
1243 else {
1244 v = u;
1245 }
1246 if (v != item) {
1247 Py_INCREF(v);
1248 PyTuple_SET_ITEM(o, i, v);
1249 Py_DECREF(item);
1250 }
1251
1252 Py_DECREF(u);
1253 }
1254 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001255 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001256 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001257 // constant keys.
1258 // See _PyCode_ConstantKey() for detail.
1259 assert(PyTuple_CheckExact(key));
1260 assert(PyTuple_GET_SIZE(key) == 2);
1261
1262 Py_ssize_t len = PySet_GET_SIZE(o);
1263 if (len == 0) { // empty frozenset should not be re-created.
1264 return key;
1265 }
1266 PyObject *tuple = PyTuple_New(len);
1267 if (tuple == NULL) {
1268 Py_DECREF(key);
1269 return NULL;
1270 }
1271 Py_ssize_t i = 0, pos = 0;
1272 PyObject *item;
1273 Py_hash_t hash;
1274 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1275 PyObject *k = merge_consts_recursive(c, item);
1276 if (k == NULL) {
1277 Py_DECREF(tuple);
1278 Py_DECREF(key);
1279 return NULL;
1280 }
1281 PyObject *u;
1282 if (PyTuple_CheckExact(k)) {
1283 u = PyTuple_GET_ITEM(k, 1);
1284 Py_INCREF(u);
1285 Py_DECREF(k);
1286 }
1287 else {
1288 u = k;
1289 }
1290 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1291 i++;
1292 }
1293
1294 // Instead of rewriting o, we create new frozenset and embed in the
1295 // key tuple. Caller should get merged frozenset from the key tuple.
1296 PyObject *new = PyFrozenSet_New(tuple);
1297 Py_DECREF(tuple);
1298 if (new == NULL) {
1299 Py_DECREF(key);
1300 return NULL;
1301 }
1302 assert(PyTuple_GET_ITEM(key, 1) == o);
1303 Py_DECREF(o);
1304 PyTuple_SET_ITEM(key, 1, new);
1305 }
INADA Naokic2e16072018-11-26 21:23:22 +09001306
1307 return key;
1308}
1309
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310static Py_ssize_t
1311compiler_add_const(struct compiler *c, PyObject *o)
1312{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001313 if (c->c_do_not_emit_bytecode) {
1314 return 0;
1315 }
1316
INADA Naokic2e16072018-11-26 21:23:22 +09001317 PyObject *key = merge_consts_recursive(c, o);
1318 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001319 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001320 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001321
INADA Naokic2e16072018-11-26 21:23:22 +09001322 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1323 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325}
1326
1327static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001328compiler_addop_load_const(struct compiler *c, PyObject *o)
1329{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001330 if (c->c_do_not_emit_bytecode) {
1331 return 1;
1332 }
1333
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001334 Py_ssize_t arg = compiler_add_const(c, o);
1335 if (arg < 0)
1336 return 0;
1337 return compiler_addop_i(c, LOAD_CONST, arg);
1338}
1339
1340static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001344 if (c->c_do_not_emit_bytecode) {
1345 return 1;
1346 }
1347
Victor Stinnerad9a0662013-11-19 22:23:20 +01001348 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351 return compiler_addop_i(c, opcode, arg);
1352}
1353
1354static int
1355compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001359
1360 if (c->c_do_not_emit_bytecode) {
1361 return 1;
1362 }
1363
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1365 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 arg = compiler_add_o(c, dict, mangled);
1368 Py_DECREF(mangled);
1369 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001370 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 return compiler_addop_i(c, opcode, arg);
1372}
1373
1374/* Add an opcode with an integer argument.
1375 Returns 0 on failure, 1 on success.
1376*/
1377
1378static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001379compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 struct instr *i;
1382 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001383
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001384 if (c->c_do_not_emit_bytecode) {
1385 return 1;
1386 }
1387
Victor Stinner2ad474b2016-03-01 23:34:47 +01001388 /* oparg value is unsigned, but a signed C int is usually used to store
1389 it in the C code (like Python/ceval.c).
1390
1391 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1392
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001393 The argument of a concrete bytecode instruction is limited to 8-bit.
1394 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1395 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001396 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 off = compiler_next_instr(c, c->u->u_curblock);
1399 if (off < 0)
1400 return 0;
1401 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001402 i->i_opcode = opcode;
1403 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 compiler_set_lineno(c, off);
1405 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406}
1407
1408static int
1409compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 struct instr *i;
1412 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001414 if (c->c_do_not_emit_bytecode) {
1415 return 1;
1416 }
1417
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001418 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 assert(b != NULL);
1420 off = compiler_next_instr(c, c->u->u_curblock);
1421 if (off < 0)
1422 return 0;
1423 i = &c->u->u_curblock->b_instr[off];
1424 i->i_opcode = opcode;
1425 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (absolute)
1427 i->i_jabs = 1;
1428 else
1429 i->i_jrel = 1;
1430 compiler_set_lineno(c, off);
1431 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432}
1433
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001434/* NEXT_BLOCK() creates an implicit jump from the current block
1435 to the new block.
1436
1437 The returns inside this macro make it impossible to decref objects
1438 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (compiler_next_block((C)) == NULL) \
1442 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443}
1444
1445#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_addop((C), (OP))) \
1447 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448}
1449
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001450#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (!compiler_addop((C), (OP))) { \
1452 compiler_exit_scope(c); \
1453 return 0; \
1454 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001455}
1456
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001457#define ADDOP_LOAD_CONST(C, O) { \
1458 if (!compiler_addop_load_const((C), (O))) \
1459 return 0; \
1460}
1461
1462/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1463#define ADDOP_LOAD_CONST_NEW(C, O) { \
1464 PyObject *__new_const = (O); \
1465 if (__new_const == NULL) { \
1466 return 0; \
1467 } \
1468 if (!compiler_addop_load_const((C), __new_const)) { \
1469 Py_DECREF(__new_const); \
1470 return 0; \
1471 } \
1472 Py_DECREF(__new_const); \
1473}
1474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1477 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478}
1479
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001480/* Same as ADDOP_O, but steals a reference. */
1481#define ADDOP_N(C, OP, O, TYPE) { \
1482 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1483 Py_DECREF((O)); \
1484 return 0; \
1485 } \
1486 Py_DECREF((O)); \
1487}
1488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1491 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492}
1493
1494#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 if (!compiler_addop_i((C), (OP), (O))) \
1496 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497}
1498
1499#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!compiler_addop_j((C), (OP), (O), 1)) \
1501 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502}
1503
1504#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (!compiler_addop_j((C), (OP), (O), 0)) \
1506 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507}
1508
Mark Shannon9af0e472020-01-14 10:12:45 +00001509
1510#define ADDOP_COMPARE(C, CMP) { \
1511 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1512 return 0; \
1513}
1514
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1516 the ASDL name to synthesize the name of the C type and the visit function.
1517*/
1518
1519#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) \
1521 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522}
1523
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_visit_ ## TYPE((C), (V))) { \
1526 compiler_exit_scope(c); \
1527 return 0; \
1528 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001529}
1530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (!compiler_visit_slice((C), (V), (CTX))) \
1533 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int _i; \
1538 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1539 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1540 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1541 if (!compiler_visit_ ## TYPE((C), elt)) \
1542 return 0; \
1543 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544}
1545
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int _i; \
1548 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1549 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1550 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1551 if (!compiler_visit_ ## TYPE((C), elt)) { \
1552 compiler_exit_scope(c); \
1553 return 0; \
1554 } \
1555 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001556}
1557
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001558/* These macros allows to check only for errors and not emmit bytecode
1559 * while visiting nodes.
1560*/
1561
1562#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1563 c->c_do_not_emit_bytecode++;
1564
1565#define END_DO_NOT_EMIT_BYTECODE \
1566 c->c_do_not_emit_bytecode--; \
1567}
1568
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001569/* Search if variable annotations are present statically in a block. */
1570
1571static int
1572find_ann(asdl_seq *stmts)
1573{
1574 int i, j, res = 0;
1575 stmt_ty st;
1576
1577 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1578 st = (stmt_ty)asdl_seq_GET(stmts, i);
1579 switch (st->kind) {
1580 case AnnAssign_kind:
1581 return 1;
1582 case For_kind:
1583 res = find_ann(st->v.For.body) ||
1584 find_ann(st->v.For.orelse);
1585 break;
1586 case AsyncFor_kind:
1587 res = find_ann(st->v.AsyncFor.body) ||
1588 find_ann(st->v.AsyncFor.orelse);
1589 break;
1590 case While_kind:
1591 res = find_ann(st->v.While.body) ||
1592 find_ann(st->v.While.orelse);
1593 break;
1594 case If_kind:
1595 res = find_ann(st->v.If.body) ||
1596 find_ann(st->v.If.orelse);
1597 break;
1598 case With_kind:
1599 res = find_ann(st->v.With.body);
1600 break;
1601 case AsyncWith_kind:
1602 res = find_ann(st->v.AsyncWith.body);
1603 break;
1604 case Try_kind:
1605 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1606 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1607 st->v.Try.handlers, j);
1608 if (find_ann(handler->v.ExceptHandler.body)) {
1609 return 1;
1610 }
1611 }
1612 res = find_ann(st->v.Try.body) ||
1613 find_ann(st->v.Try.finalbody) ||
1614 find_ann(st->v.Try.orelse);
1615 break;
1616 default:
1617 res = 0;
1618 }
1619 if (res) {
1620 break;
1621 }
1622 }
1623 return res;
1624}
1625
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001626/*
1627 * Frame block handling functions
1628 */
1629
1630static int
1631compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001632 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001633{
1634 struct fblockinfo *f;
1635 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1636 PyErr_SetString(PyExc_SyntaxError,
1637 "too many statically nested blocks");
1638 return 0;
1639 }
1640 f = &c->u->u_fblock[c->u->u_nfblocks++];
1641 f->fb_type = t;
1642 f->fb_block = b;
1643 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001644 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001645 return 1;
1646}
1647
1648static void
1649compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1650{
1651 struct compiler_unit *u = c->u;
1652 assert(u->u_nfblocks > 0);
1653 u->u_nfblocks--;
1654 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1655 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1656}
1657
Mark Shannonfee55262019-11-21 09:11:43 +00001658static int
1659compiler_call_exit_with_nones(struct compiler *c) {
1660 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1661 ADDOP(c, DUP_TOP);
1662 ADDOP(c, DUP_TOP);
1663 ADDOP_I(c, CALL_FUNCTION, 3);
1664 return 1;
1665}
1666
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001667/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001668 * popping the blocks will be restored afterwards, unless another
1669 * return, break or continue is found. In which case, the TOS will
1670 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001671 */
1672static int
1673compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1674 int preserve_tos)
1675{
1676 switch (info->fb_type) {
1677 case WHILE_LOOP:
1678 return 1;
1679
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001680 case FOR_LOOP:
1681 /* Pop the iterator */
1682 if (preserve_tos) {
1683 ADDOP(c, ROT_TWO);
1684 }
1685 ADDOP(c, POP_TOP);
1686 return 1;
1687
1688 case EXCEPT:
1689 ADDOP(c, POP_BLOCK);
1690 return 1;
1691
1692 case FINALLY_TRY:
1693 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001694 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001695 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1696 return 0;
1697 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001698 }
Mark Shannon88dce262019-12-30 09:53:36 +00001699 /* Emit the finally block, restoring the line number when done */
1700 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001701 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001702 c->u->u_lineno = saved_lineno;
1703 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001704 if (preserve_tos) {
1705 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001706 }
1707 return 1;
Mark Shannonfee55262019-11-21 09:11:43 +00001708
1709 case FINALLY_END:
1710 if (preserve_tos) {
1711 ADDOP(c, ROT_FOUR);
1712 }
1713 ADDOP(c, POP_TOP);
1714 ADDOP(c, POP_TOP);
1715 ADDOP(c, POP_TOP);
1716 if (preserve_tos) {
1717 ADDOP(c, ROT_FOUR);
1718 }
1719 ADDOP(c, POP_EXCEPT);
1720 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001721
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001722 case WITH:
1723 case ASYNC_WITH:
1724 ADDOP(c, POP_BLOCK);
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_TWO);
1727 }
Mark Shannonfee55262019-11-21 09:11:43 +00001728 if(!compiler_call_exit_with_nones(c)) {
1729 return 0;
1730 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001731 if (info->fb_type == ASYNC_WITH) {
1732 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001733 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001734 ADDOP(c, YIELD_FROM);
1735 }
Mark Shannonfee55262019-11-21 09:11:43 +00001736 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 return 1;
1738
1739 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001740 if (info->fb_datum) {
1741 ADDOP(c, POP_BLOCK);
1742 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001743 if (preserve_tos) {
1744 ADDOP(c, ROT_FOUR);
1745 }
Mark Shannonfee55262019-11-21 09:11:43 +00001746 ADDOP(c, POP_EXCEPT);
1747 if (info->fb_datum) {
1748 ADDOP_LOAD_CONST(c, Py_None);
1749 compiler_nameop(c, info->fb_datum, Store);
1750 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001751 }
Mark Shannonfee55262019-11-21 09:11:43 +00001752 return 1;
1753
1754 case POP_VALUE:
1755 if (preserve_tos) {
1756 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001757 }
Mark Shannonfee55262019-11-21 09:11:43 +00001758 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001759 return 1;
1760 }
1761 Py_UNREACHABLE();
1762}
1763
Mark Shannonfee55262019-11-21 09:11:43 +00001764/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1765static int
1766compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1767 if (c->u->u_nfblocks == 0) {
1768 return 1;
1769 }
1770 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1771 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1772 *loop = top;
1773 return 1;
1774 }
1775 struct fblockinfo copy = *top;
1776 c->u->u_nfblocks--;
1777 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1778 return 0;
1779 }
1780 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1781 return 0;
1782 }
1783 c->u->u_fblock[c->u->u_nfblocks] = copy;
1784 c->u->u_nfblocks++;
1785 return 1;
1786}
1787
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001788/* Compile a sequence of statements, checking for a docstring
1789 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790
1791static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001792compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001794 int i = 0;
1795 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001796 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001797
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001798 /* Set current line number to the line number of first statement.
1799 This way line number for SETUP_ANNOTATIONS will always
1800 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301801 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001802 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1803 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001804 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001805 c->u->u_lineno = st->lineno;
1806 }
1807 /* Every annotated class and module should have __annotations__. */
1808 if (find_ann(stmts)) {
1809 ADDOP(c, SETUP_ANNOTATIONS);
1810 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001811 if (!asdl_seq_LEN(stmts))
1812 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001813 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001814 if (c->c_optimize < 2) {
1815 docstring = _PyAST_GetDocString(stmts);
1816 if (docstring) {
1817 i = 1;
1818 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1819 assert(st->kind == Expr_kind);
1820 VISIT(c, expr, st->v.Expr.value);
1821 if (!compiler_nameop(c, __doc__, Store))
1822 return 0;
1823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001825 for (; i < asdl_seq_LEN(stmts); i++)
1826 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828}
1829
1830static PyCodeObject *
1831compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyCodeObject *co;
1834 int addNone = 1;
1835 static PyObject *module;
1836 if (!module) {
1837 module = PyUnicode_InternFromString("<module>");
1838 if (!module)
1839 return NULL;
1840 }
1841 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001842 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return NULL;
1844 switch (mod->kind) {
1845 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001846 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 compiler_exit_scope(c);
1848 return 0;
1849 }
1850 break;
1851 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001852 if (find_ann(mod->v.Interactive.body)) {
1853 ADDOP(c, SETUP_ANNOTATIONS);
1854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 c->c_interactive = 1;
1856 VISIT_SEQ_IN_SCOPE(c, stmt,
1857 mod->v.Interactive.body);
1858 break;
1859 case Expression_kind:
1860 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1861 addNone = 0;
1862 break;
1863 case Suite_kind:
1864 PyErr_SetString(PyExc_SystemError,
1865 "suite should not be possible");
1866 return 0;
1867 default:
1868 PyErr_Format(PyExc_SystemError,
1869 "module kind %d should not be possible",
1870 mod->kind);
1871 return 0;
1872 }
1873 co = assemble(c, addNone);
1874 compiler_exit_scope(c);
1875 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001876}
1877
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878/* The test for LOCAL must come before the test for FREE in order to
1879 handle classes where name is both local and free. The local var is
1880 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001881*/
1882
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883static int
1884get_ref_type(struct compiler *c, PyObject *name)
1885{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001886 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001887 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001888 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001889 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001890 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (scope == 0) {
1892 char buf[350];
1893 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001894 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001896 PyUnicode_AsUTF8(name),
1897 PyUnicode_AsUTF8(c->u->u_name),
1898 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1899 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 );
1903 Py_FatalError(buf);
1904 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
1910compiler_lookup_arg(PyObject *dict, PyObject *name)
1911{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001912 PyObject *v;
1913 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001915 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001916 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917}
1918
1919static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001920compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001922 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 if (qualname == NULL)
1924 qualname = co->co_name;
1925
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001926 if (free) {
1927 for (i = 0; i < free; ++i) {
1928 /* Bypass com_addop_varname because it will generate
1929 LOAD_DEREF but LOAD_CLOSURE is needed.
1930 */
1931 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1932 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001934 /* Special case: If a class contains a method with a
1935 free variable that has the same name as a method,
1936 the name will be considered free *and* local in the
1937 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001938 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001939 */
1940 reftype = get_ref_type(c, name);
1941 if (reftype == CELL)
1942 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1943 else /* (reftype == FREE) */
1944 arg = compiler_lookup_arg(c->u->u_freevars, name);
1945 if (arg == -1) {
1946 fprintf(stderr,
1947 "lookup %s in %s %d %d\n"
1948 "freevars of %s: %s\n",
1949 PyUnicode_AsUTF8(PyObject_Repr(name)),
1950 PyUnicode_AsUTF8(c->u->u_name),
1951 reftype, arg,
1952 PyUnicode_AsUTF8(co->co_name),
1953 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1954 Py_FatalError("compiler_make_closure()");
1955 }
1956 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001958 flags |= 0x08;
1959 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001961 ADDOP_LOAD_CONST(c, (PyObject*)co);
1962 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001963 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965}
1966
1967static int
1968compiler_decorators(struct compiler *c, asdl_seq* decos)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (!decos)
1973 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1976 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1977 }
1978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979}
1980
1981static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001982compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001984{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001985 /* Push a dict of keyword-only default values.
1986
1987 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1988 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001989 int i;
1990 PyObject *keys = NULL;
1991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1993 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1994 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1995 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001996 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001997 if (!mangled) {
1998 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002000 if (keys == NULL) {
2001 keys = PyList_New(1);
2002 if (keys == NULL) {
2003 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002004 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 }
2006 PyList_SET_ITEM(keys, 0, mangled);
2007 }
2008 else {
2009 int res = PyList_Append(keys, mangled);
2010 Py_DECREF(mangled);
2011 if (res == -1) {
2012 goto error;
2013 }
2014 }
2015 if (!compiler_visit_expr(c, default_)) {
2016 goto error;
2017 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
2019 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 if (keys != NULL) {
2021 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2022 PyObject *keys_tuple = PyList_AsTuple(keys);
2023 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002024 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002025 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 assert(default_count > 0);
2027 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002028 }
2029 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002030 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002031 }
2032
2033error:
2034 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002036}
2037
2038static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002039compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2040{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002041 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002042 return 1;
2043}
2044
2045static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002046compiler_visit_argannotation(struct compiler *c, identifier id,
2047 expr_ty annotation, PyObject *names)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002050 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002051 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2052 VISIT(c, annexpr, annotation)
2053 }
2054 else {
2055 VISIT(c, expr, annotation);
2056 }
Victor Stinner065efc32014-02-18 22:07:56 +01002057 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002058 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002059 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 if (PyList_Append(names, mangled) < 0) {
2061 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002062 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002063 }
2064 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002067}
2068
2069static int
2070compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2071 PyObject *names)
2072{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 for (i = 0; i < asdl_seq_LEN(args); i++) {
2075 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002076 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 c,
2078 arg->arg,
2079 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002080 names))
2081 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002083 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002084}
2085
2086static int
2087compiler_visit_annotations(struct compiler *c, arguments_ty args,
2088 expr_ty returns)
2089{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002090 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002091 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002092
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002093 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 */
2095 static identifier return_str;
2096 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002097 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 names = PyList_New(0);
2099 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002100 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002101
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002102 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002104 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2105 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002106 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002107 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002108 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002110 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002112 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002113 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002114 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (!return_str) {
2118 return_str = PyUnicode_InternFromString("return");
2119 if (!return_str)
2120 goto error;
2121 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002122 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 goto error;
2124 }
2125
2126 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002128 PyObject *keytuple = PyList_AsTuple(names);
2129 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002130 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002131 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002132 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002134 else {
2135 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002136 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002137 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002138
2139error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002141 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002142}
2143
2144static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002145compiler_visit_defaults(struct compiler *c, arguments_ty args)
2146{
2147 VISIT_SEQ(c, expr, args->defaults);
2148 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150}
2151
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002152static Py_ssize_t
2153compiler_default_arguments(struct compiler *c, arguments_ty args)
2154{
2155 Py_ssize_t funcflags = 0;
2156 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002157 if (!compiler_visit_defaults(c, args))
2158 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002159 funcflags |= 0x01;
2160 }
2161 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002162 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002163 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002164 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 return -1;
2166 }
2167 else if (res > 0) {
2168 funcflags |= 0x02;
2169 }
2170 }
2171 return funcflags;
2172}
2173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174static int
Yury Selivanov75445082015-05-11 22:57:16 -04002175compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002178 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002179 arguments_ty args;
2180 expr_ty returns;
2181 identifier name;
2182 asdl_seq* decos;
2183 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002184 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002185 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002186 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002187 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188
Yury Selivanov75445082015-05-11 22:57:16 -04002189 if (is_async) {
2190 assert(s->kind == AsyncFunctionDef_kind);
2191
2192 args = s->v.AsyncFunctionDef.args;
2193 returns = s->v.AsyncFunctionDef.returns;
2194 decos = s->v.AsyncFunctionDef.decorator_list;
2195 name = s->v.AsyncFunctionDef.name;
2196 body = s->v.AsyncFunctionDef.body;
2197
2198 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2199 } else {
2200 assert(s->kind == FunctionDef_kind);
2201
2202 args = s->v.FunctionDef.args;
2203 returns = s->v.FunctionDef.returns;
2204 decos = s->v.FunctionDef.decorator_list;
2205 name = s->v.FunctionDef.name;
2206 body = s->v.FunctionDef.body;
2207
2208 scope_type = COMPILER_SCOPE_FUNCTION;
2209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (!compiler_decorators(c, decos))
2212 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002213
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002214 firstlineno = s->lineno;
2215 if (asdl_seq_LEN(decos)) {
2216 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2217 }
2218
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002219 funcflags = compiler_default_arguments(c, args);
2220 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002222 }
2223
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002224 annotations = compiler_visit_annotations(c, args, returns);
2225 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002226 return 0;
2227 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002228 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002229 funcflags |= 0x04;
2230 }
2231
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002232 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002233 return 0;
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235
INADA Naokicb41b272017-02-23 00:31:59 +09002236 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002237 if (c->c_optimize < 2) {
2238 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002239 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002240 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 compiler_exit_scope(c);
2242 return 0;
2243 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002246 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002248 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002250 qualname = c->u->u_qualname;
2251 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002253 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002254 Py_XDECREF(qualname);
2255 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002259 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002260 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* decorators */
2264 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2265 ADDOP_I(c, CALL_FUNCTION, 1);
2266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267
Yury Selivanov75445082015-05-11 22:57:16 -04002268 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269}
2270
2271static int
2272compiler_class(struct compiler *c, stmt_ty s)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyCodeObject *co;
2275 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002276 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (!compiler_decorators(c, decos))
2280 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002281
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002282 firstlineno = s->lineno;
2283 if (asdl_seq_LEN(decos)) {
2284 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2285 }
2286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* ultimately generate code for:
2288 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2289 where:
2290 <func> is a function/closure created from the class body;
2291 it has a single argument (__locals__) where the dict
2292 (or MutableSequence) representing the locals is passed
2293 <name> is the class name
2294 <bases> is the positional arguments and *varargs argument
2295 <keywords> is the keyword arguments and **kwds argument
2296 This borrows from compiler_call.
2297 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002300 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002301 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 return 0;
2303 /* this block represents what we do in the new scope */
2304 {
2305 /* use the class name for name mangling */
2306 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002307 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* load (global) __name__ ... */
2309 str = PyUnicode_InternFromString("__name__");
2310 if (!str || !compiler_nameop(c, str, Load)) {
2311 Py_XDECREF(str);
2312 compiler_exit_scope(c);
2313 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_DECREF(str);
2316 /* ... and store it as __module__ */
2317 str = PyUnicode_InternFromString("__module__");
2318 if (!str || !compiler_nameop(c, str, Store)) {
2319 Py_XDECREF(str);
2320 compiler_exit_scope(c);
2321 return 0;
2322 }
2323 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002324 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002325 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002326 str = PyUnicode_InternFromString("__qualname__");
2327 if (!str || !compiler_nameop(c, str, Store)) {
2328 Py_XDECREF(str);
2329 compiler_exit_scope(c);
2330 return 0;
2331 }
2332 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002334 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 compiler_exit_scope(c);
2336 return 0;
2337 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002338 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002339 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002340 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002341 str = PyUnicode_InternFromString("__class__");
2342 if (str == NULL) {
2343 compiler_exit_scope(c);
2344 return 0;
2345 }
2346 i = compiler_lookup_arg(c->u->u_cellvars, str);
2347 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002348 if (i < 0) {
2349 compiler_exit_scope(c);
2350 return 0;
2351 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002352 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002355 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002356 str = PyUnicode_InternFromString("__classcell__");
2357 if (!str || !compiler_nameop(c, str, Store)) {
2358 Py_XDECREF(str);
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002364 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002365 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002366 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002367 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002368 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002369 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* create the code object */
2371 co = assemble(c, 1);
2372 }
2373 /* leave the new scope */
2374 compiler_exit_scope(c);
2375 if (co == NULL)
2376 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* 2. load the 'build_class' function */
2379 ADDOP(c, LOAD_BUILD_CLASS);
2380
2381 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002382 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 Py_DECREF(co);
2384
2385 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002386 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387
2388 /* 5. generate the rest of the code for the call */
2389 if (!compiler_call_helper(c, 2,
2390 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002391 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return 0;
2393
2394 /* 6. apply decorators */
2395 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2396 ADDOP_I(c, CALL_FUNCTION, 1);
2397 }
2398
2399 /* 7. store into <name> */
2400 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2401 return 0;
2402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403}
2404
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002405/* Return 0 if the expression is a constant value except named singletons.
2406 Return 1 otherwise. */
2407static int
2408check_is_arg(expr_ty e)
2409{
2410 if (e->kind != Constant_kind) {
2411 return 1;
2412 }
2413 PyObject *value = e->v.Constant.value;
2414 return (value == Py_None
2415 || value == Py_False
2416 || value == Py_True
2417 || value == Py_Ellipsis);
2418}
2419
2420/* Check operands of identity chacks ("is" and "is not").
2421 Emit a warning if any operand is a constant except named singletons.
2422 Return 0 on error.
2423 */
2424static int
2425check_compare(struct compiler *c, expr_ty e)
2426{
2427 Py_ssize_t i, n;
2428 int left = check_is_arg(e->v.Compare.left);
2429 n = asdl_seq_LEN(e->v.Compare.ops);
2430 for (i = 0; i < n; i++) {
2431 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2432 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2433 if (op == Is || op == IsNot) {
2434 if (!right || !left) {
2435 const char *msg = (op == Is)
2436 ? "\"is\" with a literal. Did you mean \"==\"?"
2437 : "\"is not\" with a literal. Did you mean \"!=\"?";
2438 return compiler_warn(c, msg);
2439 }
2440 }
2441 left = right;
2442 }
2443 return 1;
2444}
2445
Mark Shannon9af0e472020-01-14 10:12:45 +00002446static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002447{
Mark Shannon9af0e472020-01-14 10:12:45 +00002448 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449 switch (op) {
2450 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002451 cmp = Py_EQ;
2452 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002453 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002454 cmp = Py_NE;
2455 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002456 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002457 cmp = Py_LT;
2458 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002459 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002460 cmp = Py_LE;
2461 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002462 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002463 cmp = Py_GT;
2464 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002465 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002466 cmp = Py_GE;
2467 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002468 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002469 ADDOP_I(c, IS_OP, 0);
2470 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002471 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002472 ADDOP_I(c, IS_OP, 1);
2473 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002474 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002475 ADDOP_I(c, CONTAINS_OP, 0);
2476 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002478 ADDOP_I(c, CONTAINS_OP, 1);
2479 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002480 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 ADDOP_I(c, COMPARE_OP, cmp);
2484 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485}
2486
Mark Shannon9af0e472020-01-14 10:12:45 +00002487
2488
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489static int
2490compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2491{
2492 switch (e->kind) {
2493 case UnaryOp_kind:
2494 if (e->v.UnaryOp.op == Not)
2495 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2496 /* fallback to general implementation */
2497 break;
2498 case BoolOp_kind: {
2499 asdl_seq *s = e->v.BoolOp.values;
2500 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2501 assert(n >= 0);
2502 int cond2 = e->v.BoolOp.op == Or;
2503 basicblock *next2 = next;
2504 if (!cond2 != !cond) {
2505 next2 = compiler_new_block(c);
2506 if (next2 == NULL)
2507 return 0;
2508 }
2509 for (i = 0; i < n; ++i) {
2510 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2511 return 0;
2512 }
2513 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2514 return 0;
2515 if (next2 != next)
2516 compiler_use_next_block(c, next2);
2517 return 1;
2518 }
2519 case IfExp_kind: {
2520 basicblock *end, *next2;
2521 end = compiler_new_block(c);
2522 if (end == NULL)
2523 return 0;
2524 next2 = compiler_new_block(c);
2525 if (next2 == NULL)
2526 return 0;
2527 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2528 return 0;
2529 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2530 return 0;
2531 ADDOP_JREL(c, JUMP_FORWARD, end);
2532 compiler_use_next_block(c, next2);
2533 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2534 return 0;
2535 compiler_use_next_block(c, end);
2536 return 1;
2537 }
2538 case Compare_kind: {
2539 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2540 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002541 if (!check_compare(c, e)) {
2542 return 0;
2543 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002544 basicblock *cleanup = compiler_new_block(c);
2545 if (cleanup == NULL)
2546 return 0;
2547 VISIT(c, expr, e->v.Compare.left);
2548 for (i = 0; i < n; i++) {
2549 VISIT(c, expr,
2550 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2551 ADDOP(c, DUP_TOP);
2552 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002553 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002554 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2555 NEXT_BLOCK(c);
2556 }
2557 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002558 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002559 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2560 basicblock *end = compiler_new_block(c);
2561 if (end == NULL)
2562 return 0;
2563 ADDOP_JREL(c, JUMP_FORWARD, end);
2564 compiler_use_next_block(c, cleanup);
2565 ADDOP(c, POP_TOP);
2566 if (!cond) {
2567 ADDOP_JREL(c, JUMP_FORWARD, next);
2568 }
2569 compiler_use_next_block(c, end);
2570 return 1;
2571 }
2572 /* fallback to general implementation */
2573 break;
2574 }
2575 default:
2576 /* fallback to general implementation */
2577 break;
2578 }
2579
2580 /* general implementation */
2581 VISIT(c, expr, e);
2582 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2583 return 1;
2584}
2585
2586static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002587compiler_ifexp(struct compiler *c, expr_ty e)
2588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 basicblock *end, *next;
2590
2591 assert(e->kind == IfExp_kind);
2592 end = compiler_new_block(c);
2593 if (end == NULL)
2594 return 0;
2595 next = compiler_new_block(c);
2596 if (next == NULL)
2597 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002598 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2599 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 VISIT(c, expr, e->v.IfExp.body);
2601 ADDOP_JREL(c, JUMP_FORWARD, end);
2602 compiler_use_next_block(c, next);
2603 VISIT(c, expr, e->v.IfExp.orelse);
2604 compiler_use_next_block(c, end);
2605 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002606}
2607
2608static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609compiler_lambda(struct compiler *c, expr_ty e)
2610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002612 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002614 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 arguments_ty args = e->v.Lambda.args;
2616 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 if (!name) {
2619 name = PyUnicode_InternFromString("<lambda>");
2620 if (!name)
2621 return 0;
2622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002624 funcflags = compiler_default_arguments(c, args);
2625 if (funcflags == -1) {
2626 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002628
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002629 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002630 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 /* Make None the first constant, so the lambda can't have a
2634 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002635 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002639 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2641 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2642 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002643 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 }
2645 else {
2646 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002647 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002649 qualname = c->u->u_qualname;
2650 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002652 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002655 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002656 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 Py_DECREF(co);
2658
2659 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660}
2661
2662static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663compiler_if(struct compiler *c, stmt_ty s)
2664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 basicblock *end, *next;
2666 int constant;
2667 assert(s->kind == If_kind);
2668 end = compiler_new_block(c);
2669 if (end == NULL)
2670 return 0;
2671
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002672 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002673 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 * constant = 1: "if 1", "if 2", ...
2675 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002676 if (constant == 0) {
2677 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002679 END_DO_NOT_EMIT_BYTECODE
2680 if (s->v.If.orelse) {
2681 VISIT_SEQ(c, stmt, s->v.If.orelse);
2682 }
2683 } else if (constant == 1) {
2684 VISIT_SEQ(c, stmt, s->v.If.body);
2685 if (s->v.If.orelse) {
2686 BEGIN_DO_NOT_EMIT_BYTECODE
2687 VISIT_SEQ(c, stmt, s->v.If.orelse);
2688 END_DO_NOT_EMIT_BYTECODE
2689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002691 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 next = compiler_new_block(c);
2693 if (next == NULL)
2694 return 0;
2695 }
Mark Shannonfee55262019-11-21 09:11:43 +00002696 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002698 }
2699 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002700 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002701 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002703 if (asdl_seq_LEN(s->v.If.orelse)) {
2704 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 compiler_use_next_block(c, next);
2706 VISIT_SEQ(c, stmt, s->v.If.orelse);
2707 }
2708 }
2709 compiler_use_next_block(c, end);
2710 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711}
2712
2713static int
2714compiler_for(struct compiler *c, stmt_ty s)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 start = compiler_new_block(c);
2719 cleanup = compiler_new_block(c);
2720 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002721 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002723 }
2724 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 VISIT(c, expr, s->v.For.iter);
2728 ADDOP(c, GET_ITER);
2729 compiler_use_next_block(c, start);
2730 ADDOP_JREL(c, FOR_ITER, cleanup);
2731 VISIT(c, expr, s->v.For.target);
2732 VISIT_SEQ(c, stmt, s->v.For.body);
2733 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2734 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002735
2736 compiler_pop_fblock(c, FOR_LOOP, start);
2737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 VISIT_SEQ(c, stmt, s->v.For.orelse);
2739 compiler_use_next_block(c, end);
2740 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741}
2742
Yury Selivanov75445082015-05-11 22:57:16 -04002743
2744static int
2745compiler_async_for(struct compiler *c, stmt_ty s)
2746{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002747 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002748 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2749 c->u->u_ste->ste_coroutine = 1;
2750 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002751 return compiler_error(c, "'async for' outside async function");
2752 }
2753
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002754 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002755 except = compiler_new_block(c);
2756 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002757
Mark Shannonfee55262019-11-21 09:11:43 +00002758 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002759 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002760 }
Yury Selivanov75445082015-05-11 22:57:16 -04002761 VISIT(c, expr, s->v.AsyncFor.iter);
2762 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002763
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002764 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002765 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002767 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002768 /* SETUP_FINALLY to guard the __anext__ call */
2769 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002770 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002771 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002772 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002774
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002775 /* Success block for __anext__ */
2776 VISIT(c, expr, s->v.AsyncFor.target);
2777 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2778 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2779
2780 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002781
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002782 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002783 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002784 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002785
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002786 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002787 VISIT_SEQ(c, stmt, s->v.For.orelse);
2788
2789 compiler_use_next_block(c, end);
2790
2791 return 1;
2792}
2793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794static int
2795compiler_while(struct compiler *c, stmt_ty s)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002798 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002801 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002802 // Push a dummy block so the VISIT_SEQ knows that we are
2803 // inside a while loop so it can correctly evaluate syntax
2804 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002805 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002806 return 0;
2807 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002808 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002809 // Remove the dummy block now that is not needed.
2810 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002811 END_DO_NOT_EMIT_BYTECODE
2812 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 return 1;
2816 }
2817 loop = compiler_new_block(c);
2818 end = compiler_new_block(c);
2819 if (constant == -1) {
2820 anchor = compiler_new_block(c);
2821 if (anchor == NULL)
2822 return 0;
2823 }
2824 if (loop == NULL || end == NULL)
2825 return 0;
2826 if (s->v.While.orelse) {
2827 orelse = compiler_new_block(c);
2828 if (orelse == NULL)
2829 return 0;
2830 }
2831 else
2832 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002835 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 0;
2837 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002838 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2839 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 }
2841 VISIT_SEQ(c, stmt, s->v.While.body);
2842 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* XXX should the two POP instructions be in a separate block
2845 if there is no else clause ?
2846 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002848 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 compiler_pop_fblock(c, WHILE_LOOP, loop);
2851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 if (orelse != NULL) /* what if orelse is just pass? */
2853 VISIT_SEQ(c, stmt, s->v.While.orelse);
2854 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857}
2858
2859static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002860compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002863 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002864 if (c->u->u_ste->ste_type != FunctionBlock)
2865 return compiler_error(c, "'return' outside function");
2866 if (s->v.Return.value != NULL &&
2867 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2868 {
2869 return compiler_error(
2870 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002872 if (preserve_tos) {
2873 VISIT(c, expr, s->v.Return.value);
2874 }
Mark Shannonfee55262019-11-21 09:11:43 +00002875 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2876 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002878 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 }
2880 else if (!preserve_tos) {
2881 VISIT(c, expr, s->v.Return.value);
2882 }
2883 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886}
2887
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002888static int
2889compiler_break(struct compiler *c)
2890{
Mark Shannonfee55262019-11-21 09:11:43 +00002891 struct fblockinfo *loop = NULL;
2892 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2893 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002894 }
Mark Shannonfee55262019-11-21 09:11:43 +00002895 if (loop == NULL) {
2896 return compiler_error(c, "'break' outside loop");
2897 }
2898 if (!compiler_unwind_fblock(c, loop, 0)) {
2899 return 0;
2900 }
2901 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2902 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002903}
2904
2905static int
2906compiler_continue(struct compiler *c)
2907{
Mark Shannonfee55262019-11-21 09:11:43 +00002908 struct fblockinfo *loop = NULL;
2909 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2910 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002911 }
Mark Shannonfee55262019-11-21 09:11:43 +00002912 if (loop == NULL) {
2913 return compiler_error(c, "'continue' not properly in loop");
2914 }
2915 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2916 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002917}
2918
2919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
2922 SETUP_FINALLY L
2923 <code for body>
2924 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002925 <code for finalbody>
2926 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927 L:
2928 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002929 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 The special instructions use the block stack. Each block
2932 stack entry contains the instruction that created it (here
2933 SETUP_FINALLY), the level of the value stack at the time the
2934 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 Pushes the current value stack level and the label
2938 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002943 when a SETUP_FINALLY entry is found, the raised and the caught
2944 exceptions are pushed onto the value stack (and the exception
2945 condition is cleared), and the interpreter jumps to the label
2946 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947*/
2948
2949static int
2950compiler_try_finally(struct compiler *c, stmt_ty s)
2951{
Mark Shannonfee55262019-11-21 09:11:43 +00002952 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 body = compiler_new_block(c);
2955 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002956 exit = compiler_new_block(c);
2957 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002960 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 ADDOP_JREL(c, SETUP_FINALLY, end);
2962 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002963 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002965 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2966 if (!compiler_try_except(c, s))
2967 return 0;
2968 }
2969 else {
2970 VISIT_SEQ(c, stmt, s->v.Try.body);
2971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002973 compiler_pop_fblock(c, FINALLY_TRY, body);
2974 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2975 ADDOP_JREL(c, JUMP_FORWARD, exit);
2976 /* `finally` block */
2977 compiler_use_next_block(c, end);
2978 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2979 return 0;
2980 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2981 compiler_pop_fblock(c, FINALLY_END, end);
2982 ADDOP(c, RERAISE);
2983 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985}
2986
2987/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002988 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 (The contents of the value stack is shown in [], with the top
2990 at the right; 'tb' is trace-back info, 'val' the exception's
2991 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992
2993 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002994 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 [] <code for S>
2996 [] POP_BLOCK
2997 [] JUMP_FORWARD L0
2998
2999 [tb, val, exc] L1: DUP )
3000 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003001 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 [tb, val, exc] POP
3003 [tb, val] <assign to V1> (or POP if no V1)
3004 [tb] POP
3005 [] <code for S1>
3006 JUMP_FORWARD L0
3007
3008 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 .............................etc.......................
3010
Mark Shannonfee55262019-11-21 09:11:43 +00003011 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012
3013 [] L0: <next statement>
3014
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 Of course, parts are not generated if Vi or Ei is not present.
3016*/
3017static int
3018compiler_try_except(struct compiler *c, stmt_ty s)
3019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003021 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 body = compiler_new_block(c);
3024 except = compiler_new_block(c);
3025 orelse = compiler_new_block(c);
3026 end = compiler_new_block(c);
3027 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3028 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003029 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003031 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003033 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 ADDOP(c, POP_BLOCK);
3035 compiler_pop_fblock(c, EXCEPT, body);
3036 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003037 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 compiler_use_next_block(c, except);
3039 for (i = 0; i < n; i++) {
3040 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003041 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 if (!handler->v.ExceptHandler.type && i < n-1)
3043 return compiler_error(c, "default 'except:' must be last");
3044 c->u->u_lineno_set = 0;
3045 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003046 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 except = compiler_new_block(c);
3048 if (except == NULL)
3049 return 0;
3050 if (handler->v.ExceptHandler.type) {
3051 ADDOP(c, DUP_TOP);
3052 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003053 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 }
3055 ADDOP(c, POP_TOP);
3056 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003058
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 cleanup_end = compiler_new_block(c);
3060 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003061 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003062 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003063 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003064
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3066 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 /*
3069 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003070 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003071 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003072 try:
3073 # body
3074 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003075 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003076 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 /* second try: */
3080 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3081 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003082 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 /* second # body */
3086 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003087 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003088 ADDOP(c, POP_BLOCK);
3089 ADDOP(c, POP_EXCEPT);
3090 /* name = None; del name */
3091 ADDOP_LOAD_CONST(c, Py_None);
3092 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3093 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3094 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095
Mark Shannonfee55262019-11-21 09:11:43 +00003096 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003099 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003100 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103
Mark Shannonfee55262019-11-21 09:11:43 +00003104 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
3106 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003110 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112
Guido van Rossumb940e112007-01-10 16:19:56 +00003113 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003114 ADDOP(c, POP_TOP);
3115 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003116 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003119 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003120 ADDOP(c, POP_EXCEPT);
3121 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 compiler_use_next_block(c, except);
3124 }
Mark Shannonfee55262019-11-21 09:11:43 +00003125 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003127 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 compiler_use_next_block(c, end);
3129 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130}
3131
3132static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003133compiler_try(struct compiler *c, stmt_ty s) {
3134 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3135 return compiler_try_finally(c, s);
3136 else
3137 return compiler_try_except(c, s);
3138}
3139
3140
3141static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142compiler_import_as(struct compiler *c, identifier name, identifier asname)
3143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* The IMPORT_NAME opcode was already generated. This function
3145 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003148 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003150 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3151 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003152 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003153 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003156 while (1) {
3157 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003159 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003160 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003161 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003162 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003164 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003165 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003166 if (dot == -1) {
3167 break;
3168 }
3169 ADDOP(c, ROT_TWO);
3170 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003172 if (!compiler_nameop(c, asname, Store)) {
3173 return 0;
3174 }
3175 ADDOP(c, POP_TOP);
3176 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 }
3178 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179}
3180
3181static int
3182compiler_import(struct compiler *c, stmt_ty s)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 /* The Import node stores a module name like a.b.c as a single
3185 string. This is convenient for all cases except
3186 import a.b.c as d
3187 where we need to parse that string to extract the individual
3188 module names.
3189 XXX Perhaps change the representation to make this case simpler?
3190 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003191 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 for (i = 0; i < n; i++) {
3194 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3195 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003197 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3198 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 if (alias->asname) {
3202 r = compiler_import_as(c, alias->name, alias->asname);
3203 if (!r)
3204 return r;
3205 }
3206 else {
3207 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003208 Py_ssize_t dot = PyUnicode_FindChar(
3209 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003210 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003211 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003212 if (tmp == NULL)
3213 return 0;
3214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003216 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_DECREF(tmp);
3218 }
3219 if (!r)
3220 return r;
3221 }
3222 }
3223 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224}
3225
3226static int
3227compiler_from_import(struct compiler *c, stmt_ty s)
3228{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003229 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003230 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 if (!empty_string) {
3234 empty_string = PyUnicode_FromString("");
3235 if (!empty_string)
3236 return 0;
3237 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003239 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003240
3241 names = PyTuple_New(n);
3242 if (!names)
3243 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 /* build up the names */
3246 for (i = 0; i < n; i++) {
3247 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3248 Py_INCREF(alias->name);
3249 PyTuple_SET_ITEM(names, i, alias->name);
3250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003253 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 Py_DECREF(names);
3255 return compiler_error(c, "from __future__ imports must occur "
3256 "at the beginning of the file");
3257 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003258 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (s->v.ImportFrom.module) {
3261 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3262 }
3263 else {
3264 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3265 }
3266 for (i = 0; i < n; i++) {
3267 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3268 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003270 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 assert(n == 1);
3272 ADDOP(c, IMPORT_STAR);
3273 return 1;
3274 }
3275
3276 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3277 store_name = alias->name;
3278 if (alias->asname)
3279 store_name = alias->asname;
3280
3281 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return 0;
3283 }
3284 }
3285 /* remove imported module */
3286 ADDOP(c, POP_TOP);
3287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288}
3289
3290static int
3291compiler_assert(struct compiler *c, stmt_ty s)
3292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294
Georg Brandl8334fd92010-12-04 10:26:46 +00003295 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003298 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3299 {
3300 if (!compiler_warn(c, "assertion is always true, "
3301 "perhaps remove parentheses?"))
3302 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003303 return 0;
3304 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 end = compiler_new_block(c);
3307 if (end == NULL)
3308 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003309 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3310 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003311 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 if (s->v.Assert.msg) {
3313 VISIT(c, expr, s->v.Assert.msg);
3314 ADDOP_I(c, CALL_FUNCTION, 1);
3315 }
3316 ADDOP_I(c, RAISE_VARARGS, 1);
3317 compiler_use_next_block(c, end);
3318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319}
3320
3321static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003322compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3323{
3324 if (c->c_interactive && c->c_nestlevel <= 1) {
3325 VISIT(c, expr, value);
3326 ADDOP(c, PRINT_EXPR);
3327 return 1;
3328 }
3329
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003330 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003331 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003332 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003333 }
3334
3335 VISIT(c, expr, value);
3336 ADDOP(c, POP_TOP);
3337 return 1;
3338}
3339
3340static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003341compiler_visit_stmt(struct compiler *c, stmt_ty s)
3342{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003343 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 /* Always assign a lineno to the next instruction for a stmt. */
3346 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003347 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 switch (s->kind) {
3351 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003352 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 case ClassDef_kind:
3354 return compiler_class(c, s);
3355 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003356 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 case Delete_kind:
3358 VISIT_SEQ(c, expr, s->v.Delete.targets)
3359 break;
3360 case Assign_kind:
3361 n = asdl_seq_LEN(s->v.Assign.targets);
3362 VISIT(c, expr, s->v.Assign.value);
3363 for (i = 0; i < n; i++) {
3364 if (i < n - 1)
3365 ADDOP(c, DUP_TOP);
3366 VISIT(c, expr,
3367 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3368 }
3369 break;
3370 case AugAssign_kind:
3371 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003372 case AnnAssign_kind:
3373 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case For_kind:
3375 return compiler_for(c, s);
3376 case While_kind:
3377 return compiler_while(c, s);
3378 case If_kind:
3379 return compiler_if(c, s);
3380 case Raise_kind:
3381 n = 0;
3382 if (s->v.Raise.exc) {
3383 VISIT(c, expr, s->v.Raise.exc);
3384 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003385 if (s->v.Raise.cause) {
3386 VISIT(c, expr, s->v.Raise.cause);
3387 n++;
3388 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003390 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003392 case Try_kind:
3393 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 case Assert_kind:
3395 return compiler_assert(c, s);
3396 case Import_kind:
3397 return compiler_import(c, s);
3398 case ImportFrom_kind:
3399 return compiler_from_import(c, s);
3400 case Global_kind:
3401 case Nonlocal_kind:
3402 break;
3403 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003404 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 case Pass_kind:
3406 break;
3407 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003408 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 case Continue_kind:
3410 return compiler_continue(c);
3411 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003412 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003413 case AsyncFunctionDef_kind:
3414 return compiler_function(c, s, 1);
3415 case AsyncWith_kind:
3416 return compiler_async_with(c, s, 0);
3417 case AsyncFor_kind:
3418 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 }
Yury Selivanov75445082015-05-11 22:57:16 -04003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422}
3423
3424static int
3425unaryop(unaryop_ty op)
3426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 switch (op) {
3428 case Invert:
3429 return UNARY_INVERT;
3430 case Not:
3431 return UNARY_NOT;
3432 case UAdd:
3433 return UNARY_POSITIVE;
3434 case USub:
3435 return UNARY_NEGATIVE;
3436 default:
3437 PyErr_Format(PyExc_SystemError,
3438 "unary op %d should not be possible", op);
3439 return 0;
3440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441}
3442
3443static int
3444binop(struct compiler *c, operator_ty op)
3445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 switch (op) {
3447 case Add:
3448 return BINARY_ADD;
3449 case Sub:
3450 return BINARY_SUBTRACT;
3451 case Mult:
3452 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003453 case MatMult:
3454 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 case Div:
3456 return BINARY_TRUE_DIVIDE;
3457 case Mod:
3458 return BINARY_MODULO;
3459 case Pow:
3460 return BINARY_POWER;
3461 case LShift:
3462 return BINARY_LSHIFT;
3463 case RShift:
3464 return BINARY_RSHIFT;
3465 case BitOr:
3466 return BINARY_OR;
3467 case BitXor:
3468 return BINARY_XOR;
3469 case BitAnd:
3470 return BINARY_AND;
3471 case FloorDiv:
3472 return BINARY_FLOOR_DIVIDE;
3473 default:
3474 PyErr_Format(PyExc_SystemError,
3475 "binary op %d should not be possible", op);
3476 return 0;
3477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481inplace_binop(struct compiler *c, operator_ty op)
3482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 switch (op) {
3484 case Add:
3485 return INPLACE_ADD;
3486 case Sub:
3487 return INPLACE_SUBTRACT;
3488 case Mult:
3489 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003490 case MatMult:
3491 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 case Div:
3493 return INPLACE_TRUE_DIVIDE;
3494 case Mod:
3495 return INPLACE_MODULO;
3496 case Pow:
3497 return INPLACE_POWER;
3498 case LShift:
3499 return INPLACE_LSHIFT;
3500 case RShift:
3501 return INPLACE_RSHIFT;
3502 case BitOr:
3503 return INPLACE_OR;
3504 case BitXor:
3505 return INPLACE_XOR;
3506 case BitAnd:
3507 return INPLACE_AND;
3508 case FloorDiv:
3509 return INPLACE_FLOOR_DIVIDE;
3510 default:
3511 PyErr_Format(PyExc_SystemError,
3512 "inplace binary op %d should not be possible", op);
3513 return 0;
3514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515}
3516
3517static int
3518compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3519{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003520 int op, scope;
3521 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 PyObject *dict = c->u->u_names;
3525 PyObject *mangled;
3526 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003528 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3529 !_PyUnicode_EqualToASCIIString(name, "True") &&
3530 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003531
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003532 mangled = _Py_Mangle(c->u->u_private, name);
3533 if (!mangled)
3534 return 0;
3535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 op = 0;
3537 optype = OP_NAME;
3538 scope = PyST_GetScope(c->u->u_ste, mangled);
3539 switch (scope) {
3540 case FREE:
3541 dict = c->u->u_freevars;
3542 optype = OP_DEREF;
3543 break;
3544 case CELL:
3545 dict = c->u->u_cellvars;
3546 optype = OP_DEREF;
3547 break;
3548 case LOCAL:
3549 if (c->u->u_ste->ste_type == FunctionBlock)
3550 optype = OP_FAST;
3551 break;
3552 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003553 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 optype = OP_GLOBAL;
3555 break;
3556 case GLOBAL_EXPLICIT:
3557 optype = OP_GLOBAL;
3558 break;
3559 default:
3560 /* scope can be 0 */
3561 break;
3562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003565 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 switch (optype) {
3568 case OP_DEREF:
3569 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003570 case Load:
3571 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3572 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003573 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003574 op = STORE_DEREF;
3575 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 case AugLoad:
3577 case AugStore:
3578 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003579 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 case Param:
3581 default:
3582 PyErr_SetString(PyExc_SystemError,
3583 "param invalid for deref variable");
3584 return 0;
3585 }
3586 break;
3587 case OP_FAST:
3588 switch (ctx) {
3589 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003590 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003591 op = STORE_FAST;
3592 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 case Del: op = DELETE_FAST; break;
3594 case AugLoad:
3595 case AugStore:
3596 break;
3597 case Param:
3598 default:
3599 PyErr_SetString(PyExc_SystemError,
3600 "param invalid for local variable");
3601 return 0;
3602 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003603 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 return 1;
3605 case OP_GLOBAL:
3606 switch (ctx) {
3607 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003608 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003609 op = STORE_GLOBAL;
3610 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 case Del: op = DELETE_GLOBAL; break;
3612 case AugLoad:
3613 case AugStore:
3614 break;
3615 case Param:
3616 default:
3617 PyErr_SetString(PyExc_SystemError,
3618 "param invalid for global variable");
3619 return 0;
3620 }
3621 break;
3622 case OP_NAME:
3623 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003624 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003625 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003626 op = STORE_NAME;
3627 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 case Del: op = DELETE_NAME; break;
3629 case AugLoad:
3630 case AugStore:
3631 break;
3632 case Param:
3633 default:
3634 PyErr_SetString(PyExc_SystemError,
3635 "param invalid for name variable");
3636 return 0;
3637 }
3638 break;
3639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 assert(op);
3642 arg = compiler_add_o(c, dict, mangled);
3643 Py_DECREF(mangled);
3644 if (arg < 0)
3645 return 0;
3646 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647}
3648
3649static int
3650compiler_boolop(struct compiler *c, expr_ty e)
3651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003653 int jumpi;
3654 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 assert(e->kind == BoolOp_kind);
3658 if (e->v.BoolOp.op == And)
3659 jumpi = JUMP_IF_FALSE_OR_POP;
3660 else
3661 jumpi = JUMP_IF_TRUE_OR_POP;
3662 end = compiler_new_block(c);
3663 if (end == NULL)
3664 return 0;
3665 s = e->v.BoolOp.values;
3666 n = asdl_seq_LEN(s) - 1;
3667 assert(n >= 0);
3668 for (i = 0; i < n; ++i) {
3669 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3670 ADDOP_JABS(c, jumpi, end);
3671 }
3672 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3673 compiler_use_next_block(c, end);
3674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675}
3676
3677static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003678starunpack_helper(struct compiler *c, asdl_seq *elts,
3679 int single_op, int inner_op, int outer_op)
3680{
3681 Py_ssize_t n = asdl_seq_LEN(elts);
3682 Py_ssize_t i, nsubitems = 0, nseen = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003683 if (n > 2 && are_all_items_const(elts, 0, n)) {
3684 PyObject *folded = PyTuple_New(n);
3685 if (folded == NULL) {
3686 return 0;
3687 }
3688 PyObject *val;
3689 for (i = 0; i < n; i++) {
3690 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3691 Py_INCREF(val);
3692 PyTuple_SET_ITEM(folded, i, val);
3693 }
3694 if (outer_op == BUILD_SET_UNPACK) {
3695 Py_SETREF(folded, PyFrozenSet_New(folded));
3696 if (folded == NULL) {
3697 return 0;
3698 }
3699 }
3700 ADDOP_LOAD_CONST_NEW(c, folded);
3701 ADDOP_I(c, outer_op, 1);
3702 return 1;
3703 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003704 for (i = 0; i < n; i++) {
3705 expr_ty elt = asdl_seq_GET(elts, i);
3706 if (elt->kind == Starred_kind) {
3707 if (nseen) {
3708 ADDOP_I(c, inner_op, nseen);
3709 nseen = 0;
3710 nsubitems++;
3711 }
3712 VISIT(c, expr, elt->v.Starred.value);
3713 nsubitems++;
3714 }
3715 else {
3716 VISIT(c, expr, elt);
3717 nseen++;
3718 }
3719 }
3720 if (nsubitems) {
3721 if (nseen) {
3722 ADDOP_I(c, inner_op, nseen);
3723 nsubitems++;
3724 }
3725 ADDOP_I(c, outer_op, nsubitems);
3726 }
3727 else
3728 ADDOP_I(c, single_op, nseen);
3729 return 1;
3730}
3731
3732static int
3733assignment_helper(struct compiler *c, asdl_seq *elts)
3734{
3735 Py_ssize_t n = asdl_seq_LEN(elts);
3736 Py_ssize_t i;
3737 int seen_star = 0;
3738 for (i = 0; i < n; i++) {
3739 expr_ty elt = asdl_seq_GET(elts, i);
3740 if (elt->kind == Starred_kind && !seen_star) {
3741 if ((i >= (1 << 8)) ||
3742 (n-i-1 >= (INT_MAX >> 8)))
3743 return compiler_error(c,
3744 "too many expressions in "
3745 "star-unpacking assignment");
3746 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3747 seen_star = 1;
3748 asdl_seq_SET(elts, i, elt->v.Starred.value);
3749 }
3750 else if (elt->kind == Starred_kind) {
3751 return compiler_error(c,
3752 "two starred expressions in assignment");
3753 }
3754 }
3755 if (!seen_star) {
3756 ADDOP_I(c, UNPACK_SEQUENCE, n);
3757 }
3758 VISIT_SEQ(c, expr, elts);
3759 return 1;
3760}
3761
3762static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763compiler_list(struct compiler *c, expr_ty e)
3764{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003766 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769 else if (e->v.List.ctx == Load) {
3770 return starunpack_helper(c, elts,
3771 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 else
3774 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776}
3777
3778static int
3779compiler_tuple(struct compiler *c, expr_ty e)
3780{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003782 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003783 return assignment_helper(c, elts);
3784 }
3785 else if (e->v.Tuple.ctx == Load) {
3786 return starunpack_helper(c, elts,
3787 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3788 }
3789 else
3790 VISIT_SEQ(c, expr, elts);
3791 return 1;
3792}
3793
3794static int
3795compiler_set(struct compiler *c, expr_ty e)
3796{
3797 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3798 BUILD_SET, BUILD_SET_UNPACK);
3799}
3800
3801static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003802are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3803{
3804 Py_ssize_t i;
3805 for (i = begin; i < end; i++) {
3806 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003807 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003808 return 0;
3809 }
3810 return 1;
3811}
3812
3813static int
3814compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3815{
3816 Py_ssize_t i, n = end - begin;
3817 PyObject *keys, *key;
3818 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3819 for (i = begin; i < end; i++) {
3820 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3821 }
3822 keys = PyTuple_New(n);
3823 if (keys == NULL) {
3824 return 0;
3825 }
3826 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003827 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003828 Py_INCREF(key);
3829 PyTuple_SET_ITEM(keys, i - begin, key);
3830 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003831 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003832 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3833 }
3834 else {
3835 for (i = begin; i < end; i++) {
3836 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3837 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3838 }
3839 ADDOP_I(c, BUILD_MAP, n);
3840 }
3841 return 1;
3842}
3843
3844static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003845compiler_dict(struct compiler *c, expr_ty e)
3846{
Victor Stinner976bb402016-03-23 11:36:19 +01003847 Py_ssize_t i, n, elements;
3848 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003849 int is_unpacking = 0;
3850 n = asdl_seq_LEN(e->v.Dict.values);
3851 containers = 0;
3852 elements = 0;
3853 for (i = 0; i < n; i++) {
3854 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3855 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003856 if (!compiler_subdict(c, e, i - elements, i))
3857 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003858 containers++;
3859 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 if (is_unpacking) {
3862 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3863 containers++;
3864 }
3865 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003866 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 }
3868 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003869 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003870 if (!compiler_subdict(c, e, n - elements, n))
3871 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003872 containers++;
3873 }
3874 /* If there is more than one dict, they need to be merged into a new
3875 * dict. If there is one dict and it's an unpacking, then it needs
3876 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003877 if (containers > 1 || is_unpacking) {
3878 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 }
3880 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881}
3882
3883static int
3884compiler_compare(struct compiler *c, expr_ty e)
3885{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003886 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003888 if (!check_compare(c, e)) {
3889 return 0;
3890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003892 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3893 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3894 if (n == 0) {
3895 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003896 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003897 }
3898 else {
3899 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (cleanup == NULL)
3901 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003902 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 VISIT(c, expr,
3904 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003905 ADDOP(c, DUP_TOP);
3906 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003907 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003908 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3909 NEXT_BLOCK(c);
3910 }
3911 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003912 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 basicblock *end = compiler_new_block(c);
3914 if (end == NULL)
3915 return 0;
3916 ADDOP_JREL(c, JUMP_FORWARD, end);
3917 compiler_use_next_block(c, cleanup);
3918 ADDOP(c, ROT_TWO);
3919 ADDOP(c, POP_TOP);
3920 compiler_use_next_block(c, end);
3921 }
3922 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923}
3924
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003925static PyTypeObject *
3926infer_type(expr_ty e)
3927{
3928 switch (e->kind) {
3929 case Tuple_kind:
3930 return &PyTuple_Type;
3931 case List_kind:
3932 case ListComp_kind:
3933 return &PyList_Type;
3934 case Dict_kind:
3935 case DictComp_kind:
3936 return &PyDict_Type;
3937 case Set_kind:
3938 case SetComp_kind:
3939 return &PySet_Type;
3940 case GeneratorExp_kind:
3941 return &PyGen_Type;
3942 case Lambda_kind:
3943 return &PyFunction_Type;
3944 case JoinedStr_kind:
3945 case FormattedValue_kind:
3946 return &PyUnicode_Type;
3947 case Constant_kind:
3948 return e->v.Constant.value->ob_type;
3949 default:
3950 return NULL;
3951 }
3952}
3953
3954static int
3955check_caller(struct compiler *c, expr_ty e)
3956{
3957 switch (e->kind) {
3958 case Constant_kind:
3959 case Tuple_kind:
3960 case List_kind:
3961 case ListComp_kind:
3962 case Dict_kind:
3963 case DictComp_kind:
3964 case Set_kind:
3965 case SetComp_kind:
3966 case GeneratorExp_kind:
3967 case JoinedStr_kind:
3968 case FormattedValue_kind:
3969 return compiler_warn(c, "'%.200s' object is not callable; "
3970 "perhaps you missed a comma?",
3971 infer_type(e)->tp_name);
3972 default:
3973 return 1;
3974 }
3975}
3976
3977static int
3978check_subscripter(struct compiler *c, expr_ty e)
3979{
3980 PyObject *v;
3981
3982 switch (e->kind) {
3983 case Constant_kind:
3984 v = e->v.Constant.value;
3985 if (!(v == Py_None || v == Py_Ellipsis ||
3986 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3987 PyAnySet_Check(v)))
3988 {
3989 return 1;
3990 }
3991 /* fall through */
3992 case Set_kind:
3993 case SetComp_kind:
3994 case GeneratorExp_kind:
3995 case Lambda_kind:
3996 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3997 "perhaps you missed a comma?",
3998 infer_type(e)->tp_name);
3999 default:
4000 return 1;
4001 }
4002}
4003
4004static int
4005check_index(struct compiler *c, expr_ty e, slice_ty s)
4006{
4007 PyObject *v;
4008
4009 if (s->kind != Index_kind) {
4010 return 1;
4011 }
4012 PyTypeObject *index_type = infer_type(s->v.Index.value);
4013 if (index_type == NULL
4014 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4015 || index_type == &PySlice_Type) {
4016 return 1;
4017 }
4018
4019 switch (e->kind) {
4020 case Constant_kind:
4021 v = e->v.Constant.value;
4022 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4023 return 1;
4024 }
4025 /* fall through */
4026 case Tuple_kind:
4027 case List_kind:
4028 case ListComp_kind:
4029 case JoinedStr_kind:
4030 case FormattedValue_kind:
4031 return compiler_warn(c, "%.200s indices must be integers or slices, "
4032 "not %.200s; "
4033 "perhaps you missed a comma?",
4034 infer_type(e)->tp_name,
4035 index_type->tp_name);
4036 default:
4037 return 1;
4038 }
4039}
4040
Zackery Spytz97f5de02019-03-22 01:30:32 -06004041// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004043maybe_optimize_method_call(struct compiler *c, expr_ty e)
4044{
4045 Py_ssize_t argsl, i;
4046 expr_ty meth = e->v.Call.func;
4047 asdl_seq *args = e->v.Call.args;
4048
4049 /* Check that the call node is an attribute access, and that
4050 the call doesn't have keyword parameters. */
4051 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4052 asdl_seq_LEN(e->v.Call.keywords))
4053 return -1;
4054
4055 /* Check that there are no *varargs types of arguments. */
4056 argsl = asdl_seq_LEN(args);
4057 for (i = 0; i < argsl; i++) {
4058 expr_ty elt = asdl_seq_GET(args, i);
4059 if (elt->kind == Starred_kind) {
4060 return -1;
4061 }
4062 }
4063
4064 /* Alright, we can optimize the code. */
4065 VISIT(c, expr, meth->v.Attribute.value);
4066 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4067 VISIT_SEQ(c, expr, e->v.Call.args);
4068 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4069 return 1;
4070}
4071
4072static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073compiler_call(struct compiler *c, expr_ty e)
4074{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004075 int ret = maybe_optimize_method_call(c, e);
4076 if (ret >= 0) {
4077 return ret;
4078 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004079 if (!check_caller(c, e->v.Call.func)) {
4080 return 0;
4081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 VISIT(c, expr, e->v.Call.func);
4083 return compiler_call_helper(c, 0,
4084 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004085 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004086}
4087
Eric V. Smith235a6f02015-09-19 14:51:32 -04004088static int
4089compiler_joined_str(struct compiler *c, expr_ty e)
4090{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004091 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004092 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4093 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004094 return 1;
4095}
4096
Eric V. Smitha78c7952015-11-03 12:45:05 -05004097/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004098static int
4099compiler_formatted_value(struct compiler *c, expr_ty e)
4100{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004101 /* Our oparg encodes 2 pieces of information: the conversion
4102 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004103
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004104 Convert the conversion char to 3 bits:
4105 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004106 !s : 001 0x1 FVC_STR
4107 !r : 010 0x2 FVC_REPR
4108 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004109
Eric V. Smitha78c7952015-11-03 12:45:05 -05004110 next bit is whether or not we have a format spec:
4111 yes : 100 0x4
4112 no : 000 0x0
4113 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004114
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004115 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004116 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004117
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004118 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004119 VISIT(c, expr, e->v.FormattedValue.value);
4120
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004121 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004122 case 's': oparg = FVC_STR; break;
4123 case 'r': oparg = FVC_REPR; break;
4124 case 'a': oparg = FVC_ASCII; break;
4125 case -1: oparg = FVC_NONE; break;
4126 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004127 PyErr_Format(PyExc_SystemError,
4128 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004129 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004130 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004131 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004132 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004133 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004134 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004135 }
4136
Eric V. Smitha78c7952015-11-03 12:45:05 -05004137 /* And push our opcode and oparg */
4138 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004139
Eric V. Smith235a6f02015-09-19 14:51:32 -04004140 return 1;
4141}
4142
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004143static int
4144compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4145{
4146 Py_ssize_t i, n = end - begin;
4147 keyword_ty kw;
4148 PyObject *keys, *key;
4149 assert(n > 0);
4150 if (n > 1) {
4151 for (i = begin; i < end; i++) {
4152 kw = asdl_seq_GET(keywords, i);
4153 VISIT(c, expr, kw->value);
4154 }
4155 keys = PyTuple_New(n);
4156 if (keys == NULL) {
4157 return 0;
4158 }
4159 for (i = begin; i < end; i++) {
4160 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4161 Py_INCREF(key);
4162 PyTuple_SET_ITEM(keys, i - begin, key);
4163 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004164 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004165 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4166 }
4167 else {
4168 /* a for loop only executes once */
4169 for (i = begin; i < end; i++) {
4170 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004171 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004172 VISIT(c, expr, kw->value);
4173 }
4174 ADDOP_I(c, BUILD_MAP, n);
4175 }
4176 return 1;
4177}
4178
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004179/* shared code between compiler_call and compiler_class */
4180static int
4181compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004182 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004183 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004184 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004185{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004186 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004187 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004188
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004189 /* the number of tuples and dictionaries on the stack */
4190 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4191
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004192 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004193 nkwelts = asdl_seq_LEN(keywords);
4194
4195 for (i = 0; i < nkwelts; i++) {
4196 keyword_ty kw = asdl_seq_GET(keywords, i);
4197 if (kw->arg == NULL) {
4198 mustdictunpack = 1;
4199 break;
4200 }
4201 }
4202
4203 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004204 for (i = 0; i < nelts; i++) {
4205 expr_ty elt = asdl_seq_GET(args, i);
4206 if (elt->kind == Starred_kind) {
4207 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004208 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004209 if (nseen) {
4210 ADDOP_I(c, BUILD_TUPLE, nseen);
4211 nseen = 0;
4212 nsubargs++;
4213 }
4214 VISIT(c, expr, elt->v.Starred.value);
4215 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004216 }
4217 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004218 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004219 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004220 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004222
4223 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004224 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004225 if (nseen) {
4226 /* Pack up any trailing positional arguments. */
4227 ADDOP_I(c, BUILD_TUPLE, nseen);
4228 nsubargs++;
4229 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004230 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004231 /* If we ended up with more than one stararg, we need
4232 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004233 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004234 }
4235 else if (nsubargs == 0) {
4236 ADDOP_I(c, BUILD_TUPLE, 0);
4237 }
4238 nseen = 0; /* the number of keyword arguments on the stack following */
4239 for (i = 0; i < nkwelts; i++) {
4240 keyword_ty kw = asdl_seq_GET(keywords, i);
4241 if (kw->arg == NULL) {
4242 /* A keyword argument unpacking. */
4243 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004244 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4245 return 0;
4246 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004247 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004248 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004249 VISIT(c, expr, kw->value);
4250 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004251 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004252 else {
4253 nseen++;
4254 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004255 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004256 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004257 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004258 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004259 return 0;
4260 nsubkwargs++;
4261 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004262 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004263 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004265 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004266 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4267 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004269 else if (nkwelts) {
4270 PyObject *names;
4271 VISIT_SEQ(c, keyword, keywords);
4272 names = PyTuple_New(nkwelts);
4273 if (names == NULL) {
4274 return 0;
4275 }
4276 for (i = 0; i < nkwelts; i++) {
4277 keyword_ty kw = asdl_seq_GET(keywords, i);
4278 Py_INCREF(kw->arg);
4279 PyTuple_SET_ITEM(names, i, kw->arg);
4280 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004281 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004282 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4283 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004285 else {
4286 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4287 return 1;
4288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289}
4290
Nick Coghlan650f0d02007-04-15 12:05:43 +00004291
4292/* List and set comprehensions and generator expressions work by creating a
4293 nested function to perform the actual iteration. This means that the
4294 iteration variables don't leak into the current scope.
4295 The defined function is called immediately following its definition, with the
4296 result of that call being the result of the expression.
4297 The LC/SC version returns the populated container, while the GE version is
4298 flagged in symtable.c as a generator, so it returns the generator object
4299 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004300
4301 Possible cleanups:
4302 - iterate over the generator sequence instead of using recursion
4303*/
4304
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307compiler_comprehension_generator(struct compiler *c,
4308 asdl_seq *generators, int gen_index,
4309 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004311 comprehension_ty gen;
4312 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4313 if (gen->is_async) {
4314 return compiler_async_comprehension_generator(
4315 c, generators, gen_index, elt, val, type);
4316 } else {
4317 return compiler_sync_comprehension_generator(
4318 c, generators, gen_index, elt, val, type);
4319 }
4320}
4321
4322static int
4323compiler_sync_comprehension_generator(struct compiler *c,
4324 asdl_seq *generators, int gen_index,
4325 expr_ty elt, expr_ty val, int type)
4326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 /* generate code for the iterator, then each of the ifs,
4328 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 comprehension_ty gen;
4331 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004332 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 start = compiler_new_block(c);
4335 skip = compiler_new_block(c);
4336 if_cleanup = compiler_new_block(c);
4337 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4340 anchor == NULL)
4341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 if (gen_index == 0) {
4346 /* Receive outermost iter as an implicit argument */
4347 c->u->u_argcount = 1;
4348 ADDOP_I(c, LOAD_FAST, 0);
4349 }
4350 else {
4351 /* Sub-iter - calculate on the fly */
4352 VISIT(c, expr, gen->iter);
4353 ADDOP(c, GET_ITER);
4354 }
4355 compiler_use_next_block(c, start);
4356 ADDOP_JREL(c, FOR_ITER, anchor);
4357 NEXT_BLOCK(c);
4358 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 /* XXX this needs to be cleaned up...a lot! */
4361 n = asdl_seq_LEN(gen->ifs);
4362 for (i = 0; i < n; i++) {
4363 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004364 if (!compiler_jump_if(c, e, if_cleanup, 0))
4365 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 NEXT_BLOCK(c);
4367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 if (++gen_index < asdl_seq_LEN(generators))
4370 if (!compiler_comprehension_generator(c,
4371 generators, gen_index,
4372 elt, val, type))
4373 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 /* only append after the last for generator */
4376 if (gen_index >= asdl_seq_LEN(generators)) {
4377 /* comprehension specific code */
4378 switch (type) {
4379 case COMP_GENEXP:
4380 VISIT(c, expr, elt);
4381 ADDOP(c, YIELD_VALUE);
4382 ADDOP(c, POP_TOP);
4383 break;
4384 case COMP_LISTCOMP:
4385 VISIT(c, expr, elt);
4386 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4387 break;
4388 case COMP_SETCOMP:
4389 VISIT(c, expr, elt);
4390 ADDOP_I(c, SET_ADD, gen_index + 1);
4391 break;
4392 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004393 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004396 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 ADDOP_I(c, MAP_ADD, gen_index + 1);
4398 break;
4399 default:
4400 return 0;
4401 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 compiler_use_next_block(c, skip);
4404 }
4405 compiler_use_next_block(c, if_cleanup);
4406 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4407 compiler_use_next_block(c, anchor);
4408
4409 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004410}
4411
4412static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004413compiler_async_comprehension_generator(struct compiler *c,
4414 asdl_seq *generators, int gen_index,
4415 expr_ty elt, expr_ty val, int type)
4416{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004417 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004418 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004419 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004420 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004421 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004422 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004423
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004424 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425 return 0;
4426 }
4427
4428 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4429
4430 if (gen_index == 0) {
4431 /* Receive outermost iter as an implicit argument */
4432 c->u->u_argcount = 1;
4433 ADDOP_I(c, LOAD_FAST, 0);
4434 }
4435 else {
4436 /* Sub-iter - calculate on the fly */
4437 VISIT(c, expr, gen->iter);
4438 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004439 }
4440
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004441 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004442
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004443 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004444 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004445 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004446 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004447 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004448 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004449
4450 n = asdl_seq_LEN(gen->ifs);
4451 for (i = 0; i < n; i++) {
4452 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004453 if (!compiler_jump_if(c, e, if_cleanup, 0))
4454 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004455 NEXT_BLOCK(c);
4456 }
4457
4458 if (++gen_index < asdl_seq_LEN(generators))
4459 if (!compiler_comprehension_generator(c,
4460 generators, gen_index,
4461 elt, val, type))
4462 return 0;
4463
4464 /* only append after the last for generator */
4465 if (gen_index >= asdl_seq_LEN(generators)) {
4466 /* comprehension specific code */
4467 switch (type) {
4468 case COMP_GENEXP:
4469 VISIT(c, expr, elt);
4470 ADDOP(c, YIELD_VALUE);
4471 ADDOP(c, POP_TOP);
4472 break;
4473 case COMP_LISTCOMP:
4474 VISIT(c, expr, elt);
4475 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4476 break;
4477 case COMP_SETCOMP:
4478 VISIT(c, expr, elt);
4479 ADDOP_I(c, SET_ADD, gen_index + 1);
4480 break;
4481 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004482 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004483 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004485 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 ADDOP_I(c, MAP_ADD, gen_index + 1);
4487 break;
4488 default:
4489 return 0;
4490 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 }
4492 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004493 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4494
4495 compiler_use_next_block(c, except);
4496 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497
4498 return 1;
4499}
4500
4501static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004502compiler_comprehension(struct compiler *c, expr_ty e, int type,
4503 identifier name, asdl_seq *generators, expr_ty elt,
4504 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004508 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509 int is_async_function = c->u->u_ste->ste_coroutine;
4510 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004511
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004513
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004514 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4515 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004518 }
4519
4520 is_async_generator = c->u->u_ste->ste_coroutine;
4521
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004522 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523 compiler_error(c, "asynchronous comprehension outside of "
4524 "an asynchronous function");
4525 goto error_in_scope;
4526 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (type != COMP_GENEXP) {
4529 int op;
4530 switch (type) {
4531 case COMP_LISTCOMP:
4532 op = BUILD_LIST;
4533 break;
4534 case COMP_SETCOMP:
4535 op = BUILD_SET;
4536 break;
4537 case COMP_DICTCOMP:
4538 op = BUILD_MAP;
4539 break;
4540 default:
4541 PyErr_Format(PyExc_SystemError,
4542 "unknown comprehension type %d", type);
4543 goto error_in_scope;
4544 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 ADDOP_I(c, op, 0);
4547 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 if (!compiler_comprehension_generator(c, generators, 0, elt,
4550 val, type))
4551 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 if (type != COMP_GENEXP) {
4554 ADDOP(c, RETURN_VALUE);
4555 }
4556
4557 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004558 qualname = c->u->u_qualname;
4559 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004561 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 goto error;
4563
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004564 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004566 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 Py_DECREF(co);
4568
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 VISIT(c, expr, outermost->iter);
4570
4571 if (outermost->is_async) {
4572 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004573 } else {
4574 ADDOP(c, GET_ITER);
4575 }
4576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578
4579 if (is_async_generator && type != COMP_GENEXP) {
4580 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004581 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004582 ADDOP(c, YIELD_FROM);
4583 }
4584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004586error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004588error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004589 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 Py_XDECREF(co);
4591 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004592}
4593
4594static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004595compiler_genexp(struct compiler *c, expr_ty e)
4596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 static identifier name;
4598 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004599 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 if (!name)
4601 return 0;
4602 }
4603 assert(e->kind == GeneratorExp_kind);
4604 return compiler_comprehension(c, e, COMP_GENEXP, name,
4605 e->v.GeneratorExp.generators,
4606 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004607}
4608
4609static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004610compiler_listcomp(struct compiler *c, expr_ty e)
4611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 static identifier name;
4613 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004614 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 if (!name)
4616 return 0;
4617 }
4618 assert(e->kind == ListComp_kind);
4619 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4620 e->v.ListComp.generators,
4621 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004622}
4623
4624static int
4625compiler_setcomp(struct compiler *c, expr_ty e)
4626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 static identifier name;
4628 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004629 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 if (!name)
4631 return 0;
4632 }
4633 assert(e->kind == SetComp_kind);
4634 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4635 e->v.SetComp.generators,
4636 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004637}
4638
4639
4640static int
4641compiler_dictcomp(struct compiler *c, expr_ty e)
4642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 static identifier name;
4644 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004645 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 if (!name)
4647 return 0;
4648 }
4649 assert(e->kind == DictComp_kind);
4650 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4651 e->v.DictComp.generators,
4652 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004653}
4654
4655
4656static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004657compiler_visit_keyword(struct compiler *c, keyword_ty k)
4658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 VISIT(c, expr, k->value);
4660 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004661}
4662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004664 whether they are true or false.
4665
4666 Return values: 1 for true, 0 for false, -1 for non-constant.
4667 */
4668
4669static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004670expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004671{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004672 if (e->kind == Constant_kind) {
4673 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004674 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004675 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004676}
4677
Mark Shannonfee55262019-11-21 09:11:43 +00004678static int
4679compiler_with_except_finish(struct compiler *c) {
4680 basicblock *exit;
4681 exit = compiler_new_block(c);
4682 if (exit == NULL)
4683 return 0;
4684 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4685 ADDOP(c, RERAISE);
4686 compiler_use_next_block(c, exit);
4687 ADDOP(c, POP_TOP);
4688 ADDOP(c, POP_TOP);
4689 ADDOP(c, POP_TOP);
4690 ADDOP(c, POP_EXCEPT);
4691 ADDOP(c, POP_TOP);
4692 return 1;
4693}
Yury Selivanov75445082015-05-11 22:57:16 -04004694
4695/*
4696 Implements the async with statement.
4697
4698 The semantics outlined in that PEP are as follows:
4699
4700 async with EXPR as VAR:
4701 BLOCK
4702
4703 It is implemented roughly as:
4704
4705 context = EXPR
4706 exit = context.__aexit__ # not calling it
4707 value = await context.__aenter__()
4708 try:
4709 VAR = value # if VAR present in the syntax
4710 BLOCK
4711 finally:
4712 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004713 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004714 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004715 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004716 if not (await exit(*exc)):
4717 raise
4718 */
4719static int
4720compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4721{
Mark Shannonfee55262019-11-21 09:11:43 +00004722 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004723 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4724
4725 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004726 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4727 c->u->u_ste->ste_coroutine = 1;
4728 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004729 return compiler_error(c, "'async with' outside async function");
4730 }
Yury Selivanov75445082015-05-11 22:57:16 -04004731
4732 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004733 final = compiler_new_block(c);
4734 exit = compiler_new_block(c);
4735 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004736 return 0;
4737
4738 /* Evaluate EXPR */
4739 VISIT(c, expr, item->context_expr);
4740
4741 ADDOP(c, BEFORE_ASYNC_WITH);
4742 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004743 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004744 ADDOP(c, YIELD_FROM);
4745
Mark Shannonfee55262019-11-21 09:11:43 +00004746 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004747
4748 /* SETUP_ASYNC_WITH pushes a finally block. */
4749 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004750 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004751 return 0;
4752 }
4753
4754 if (item->optional_vars) {
4755 VISIT(c, expr, item->optional_vars);
4756 }
4757 else {
4758 /* Discard result from context.__aenter__() */
4759 ADDOP(c, POP_TOP);
4760 }
4761
4762 pos++;
4763 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4764 /* BLOCK code */
4765 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4766 else if (!compiler_async_with(c, s, pos))
4767 return 0;
4768
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004769 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004770 ADDOP(c, POP_BLOCK);
4771 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004772
Mark Shannonfee55262019-11-21 09:11:43 +00004773 /* For successful outcome:
4774 * call __exit__(None, None, None)
4775 */
4776 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004777 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004778 ADDOP(c, GET_AWAITABLE);
4779 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4780 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004781
Mark Shannonfee55262019-11-21 09:11:43 +00004782 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004783
Mark Shannonfee55262019-11-21 09:11:43 +00004784 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4785
4786 /* For exceptional outcome: */
4787 compiler_use_next_block(c, final);
4788
4789 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004790 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004791 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004792 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004793 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004794
Mark Shannonfee55262019-11-21 09:11:43 +00004795compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004796 return 1;
4797}
4798
4799
Guido van Rossumc2e20742006-02-27 22:32:47 +00004800/*
4801 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004802 with EXPR as VAR:
4803 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004804 is implemented as:
4805 <code for EXPR>
4806 SETUP_WITH E
4807 <code to store to VAR> or POP_TOP
4808 <code for BLOCK>
4809 LOAD_CONST (None, None, None)
4810 CALL_FUNCTION_EX 0
4811 JUMP_FORWARD EXIT
4812 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4813 POP_JUMP_IF_TRUE T:
4814 RERAISE
4815 T: POP_TOP * 3 (remove exception from stack)
4816 POP_EXCEPT
4817 POP_TOP
4818 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004819 */
Mark Shannonfee55262019-11-21 09:11:43 +00004820
Guido van Rossumc2e20742006-02-27 22:32:47 +00004821static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004822compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004823{
Mark Shannonfee55262019-11-21 09:11:43 +00004824 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004825 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004826
4827 assert(s->kind == With_kind);
4828
Guido van Rossumc2e20742006-02-27 22:32:47 +00004829 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004830 final = compiler_new_block(c);
4831 exit = compiler_new_block(c);
4832 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004834
Thomas Wouters477c8d52006-05-27 19:21:47 +00004835 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004836 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004837 /* Will push bound __exit__ */
4838 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004839
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004840 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004841 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004842 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004843 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004844 }
4845
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004846 if (item->optional_vars) {
4847 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004848 }
4849 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004851 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004852 }
4853
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004854 pos++;
4855 if (pos == asdl_seq_LEN(s->v.With.items))
4856 /* BLOCK code */
4857 VISIT_SEQ(c, stmt, s->v.With.body)
4858 else if (!compiler_with(c, s, pos))
4859 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004860
Guido van Rossumc2e20742006-02-27 22:32:47 +00004861 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004862 compiler_pop_fblock(c, WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004863
4864 /* End of body; start the cleanup. */
4865
4866 /* For successful outcome:
4867 * call __exit__(None, None, None)
4868 */
4869 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004870 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004871 ADDOP(c, POP_TOP);
4872 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004873
Mark Shannonfee55262019-11-21 09:11:43 +00004874 /* For exceptional outcome: */
4875 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004876
Mark Shannonfee55262019-11-21 09:11:43 +00004877 ADDOP(c, WITH_EXCEPT_START);
4878 compiler_with_except_finish(c);
4879
4880 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004881 return 1;
4882}
4883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004884static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004885compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004888 case NamedExpr_kind:
4889 VISIT(c, expr, e->v.NamedExpr.value);
4890 ADDOP(c, DUP_TOP);
4891 VISIT(c, expr, e->v.NamedExpr.target);
4892 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 case BoolOp_kind:
4894 return compiler_boolop(c, e);
4895 case BinOp_kind:
4896 VISIT(c, expr, e->v.BinOp.left);
4897 VISIT(c, expr, e->v.BinOp.right);
4898 ADDOP(c, binop(c, e->v.BinOp.op));
4899 break;
4900 case UnaryOp_kind:
4901 VISIT(c, expr, e->v.UnaryOp.operand);
4902 ADDOP(c, unaryop(e->v.UnaryOp.op));
4903 break;
4904 case Lambda_kind:
4905 return compiler_lambda(c, e);
4906 case IfExp_kind:
4907 return compiler_ifexp(c, e);
4908 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004909 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004911 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 case GeneratorExp_kind:
4913 return compiler_genexp(c, e);
4914 case ListComp_kind:
4915 return compiler_listcomp(c, e);
4916 case SetComp_kind:
4917 return compiler_setcomp(c, e);
4918 case DictComp_kind:
4919 return compiler_dictcomp(c, e);
4920 case Yield_kind:
4921 if (c->u->u_ste->ste_type != FunctionBlock)
4922 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004923 if (e->v.Yield.value) {
4924 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004925 }
4926 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004927 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004929 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004931 case YieldFrom_kind:
4932 if (c->u->u_ste->ste_type != FunctionBlock)
4933 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004934
4935 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4936 return compiler_error(c, "'yield from' inside async function");
4937
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004938 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004939 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004940 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004941 ADDOP(c, YIELD_FROM);
4942 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004943 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004944 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4945 if (c->u->u_ste->ste_type != FunctionBlock){
4946 return compiler_error(c, "'await' outside function");
4947 }
Yury Selivanov75445082015-05-11 22:57:16 -04004948
Victor Stinner331a6a52019-05-27 16:39:22 +02004949 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004950 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4951 return compiler_error(c, "'await' outside async function");
4952 }
4953 }
Yury Selivanov75445082015-05-11 22:57:16 -04004954
4955 VISIT(c, expr, e->v.Await.value);
4956 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004957 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004958 ADDOP(c, YIELD_FROM);
4959 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 case Compare_kind:
4961 return compiler_compare(c, e);
4962 case Call_kind:
4963 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004964 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004965 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004966 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004967 case JoinedStr_kind:
4968 return compiler_joined_str(c, e);
4969 case FormattedValue_kind:
4970 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 /* The following exprs can be assignment targets. */
4972 case Attribute_kind:
4973 if (e->v.Attribute.ctx != AugStore)
4974 VISIT(c, expr, e->v.Attribute.value);
4975 switch (e->v.Attribute.ctx) {
4976 case AugLoad:
4977 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004978 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 case Load:
4980 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4981 break;
4982 case AugStore:
4983 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004984 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 case Store:
4986 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4987 break;
4988 case Del:
4989 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4990 break;
4991 case Param:
4992 default:
4993 PyErr_SetString(PyExc_SystemError,
4994 "param invalid in attribute expression");
4995 return 0;
4996 }
4997 break;
4998 case Subscript_kind:
4999 switch (e->v.Subscript.ctx) {
5000 case AugLoad:
5001 VISIT(c, expr, e->v.Subscript.value);
5002 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5003 break;
5004 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005005 if (!check_subscripter(c, e->v.Subscript.value)) {
5006 return 0;
5007 }
5008 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5009 return 0;
5010 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 VISIT(c, expr, e->v.Subscript.value);
5012 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5013 break;
5014 case AugStore:
5015 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5016 break;
5017 case Store:
5018 VISIT(c, expr, e->v.Subscript.value);
5019 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5020 break;
5021 case Del:
5022 VISIT(c, expr, e->v.Subscript.value);
5023 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5024 break;
5025 case Param:
5026 default:
5027 PyErr_SetString(PyExc_SystemError,
5028 "param invalid in subscript expression");
5029 return 0;
5030 }
5031 break;
5032 case Starred_kind:
5033 switch (e->v.Starred.ctx) {
5034 case Store:
5035 /* In all legitimate cases, the Starred node was already replaced
5036 * by compiler_list/compiler_tuple. XXX: is that okay? */
5037 return compiler_error(c,
5038 "starred assignment target must be in a list or tuple");
5039 default:
5040 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005041 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 case Name_kind:
5044 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5045 /* child nodes of List and Tuple will have expr_context set */
5046 case List_kind:
5047 return compiler_list(c, e);
5048 case Tuple_kind:
5049 return compiler_tuple(c, e);
5050 }
5051 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005052}
5053
5054static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005055compiler_visit_expr(struct compiler *c, expr_ty e)
5056{
5057 /* If expr e has a different line number than the last expr/stmt,
5058 set a new line number for the next instruction.
5059 */
5060 int old_lineno = c->u->u_lineno;
5061 int old_col_offset = c->u->u_col_offset;
5062 if (e->lineno != c->u->u_lineno) {
5063 c->u->u_lineno = e->lineno;
5064 c->u->u_lineno_set = 0;
5065 }
5066 /* Updating the column offset is always harmless. */
5067 c->u->u_col_offset = e->col_offset;
5068
5069 int res = compiler_visit_expr1(c, e);
5070
5071 if (old_lineno != c->u->u_lineno) {
5072 c->u->u_lineno = old_lineno;
5073 c->u->u_lineno_set = 0;
5074 }
5075 c->u->u_col_offset = old_col_offset;
5076 return res;
5077}
5078
5079static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005080compiler_augassign(struct compiler *c, stmt_ty s)
5081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 expr_ty e = s->v.AugAssign.target;
5083 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 switch (e->kind) {
5088 case Attribute_kind:
5089 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005090 AugLoad, e->lineno, e->col_offset,
5091 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 if (auge == NULL)
5093 return 0;
5094 VISIT(c, expr, auge);
5095 VISIT(c, expr, s->v.AugAssign.value);
5096 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5097 auge->v.Attribute.ctx = AugStore;
5098 VISIT(c, expr, auge);
5099 break;
5100 case Subscript_kind:
5101 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005102 AugLoad, e->lineno, e->col_offset,
5103 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 if (auge == NULL)
5105 return 0;
5106 VISIT(c, expr, auge);
5107 VISIT(c, expr, s->v.AugAssign.value);
5108 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5109 auge->v.Subscript.ctx = AugStore;
5110 VISIT(c, expr, auge);
5111 break;
5112 case Name_kind:
5113 if (!compiler_nameop(c, e->v.Name.id, Load))
5114 return 0;
5115 VISIT(c, expr, s->v.AugAssign.value);
5116 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5117 return compiler_nameop(c, e->v.Name.id, Store);
5118 default:
5119 PyErr_Format(PyExc_SystemError,
5120 "invalid node type (%d) for augmented assignment",
5121 e->kind);
5122 return 0;
5123 }
5124 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005125}
5126
5127static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005128check_ann_expr(struct compiler *c, expr_ty e)
5129{
5130 VISIT(c, expr, e);
5131 ADDOP(c, POP_TOP);
5132 return 1;
5133}
5134
5135static int
5136check_annotation(struct compiler *c, stmt_ty s)
5137{
5138 /* Annotations are only evaluated in a module or class. */
5139 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5140 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5141 return check_ann_expr(c, s->v.AnnAssign.annotation);
5142 }
5143 return 1;
5144}
5145
5146static int
5147check_ann_slice(struct compiler *c, slice_ty sl)
5148{
5149 switch(sl->kind) {
5150 case Index_kind:
5151 return check_ann_expr(c, sl->v.Index.value);
5152 case Slice_kind:
5153 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5154 return 0;
5155 }
5156 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5157 return 0;
5158 }
5159 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5160 return 0;
5161 }
5162 break;
5163 default:
5164 PyErr_SetString(PyExc_SystemError,
5165 "unexpected slice kind");
5166 return 0;
5167 }
5168 return 1;
5169}
5170
5171static int
5172check_ann_subscr(struct compiler *c, slice_ty sl)
5173{
5174 /* We check that everything in a subscript is defined at runtime. */
5175 Py_ssize_t i, n;
5176
5177 switch (sl->kind) {
5178 case Index_kind:
5179 case Slice_kind:
5180 if (!check_ann_slice(c, sl)) {
5181 return 0;
5182 }
5183 break;
5184 case ExtSlice_kind:
5185 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5186 for (i = 0; i < n; i++) {
5187 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5188 switch (subsl->kind) {
5189 case Index_kind:
5190 case Slice_kind:
5191 if (!check_ann_slice(c, subsl)) {
5192 return 0;
5193 }
5194 break;
5195 case ExtSlice_kind:
5196 default:
5197 PyErr_SetString(PyExc_SystemError,
5198 "extended slice invalid in nested slice");
5199 return 0;
5200 }
5201 }
5202 break;
5203 default:
5204 PyErr_Format(PyExc_SystemError,
5205 "invalid subscript kind %d", sl->kind);
5206 return 0;
5207 }
5208 return 1;
5209}
5210
5211static int
5212compiler_annassign(struct compiler *c, stmt_ty s)
5213{
5214 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005215 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005216
5217 assert(s->kind == AnnAssign_kind);
5218
5219 /* We perform the actual assignment first. */
5220 if (s->v.AnnAssign.value) {
5221 VISIT(c, expr, s->v.AnnAssign.value);
5222 VISIT(c, expr, targ);
5223 }
5224 switch (targ->kind) {
5225 case Name_kind:
5226 /* If we have a simple name in a module or class, store annotation. */
5227 if (s->v.AnnAssign.simple &&
5228 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5229 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005230 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5231 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5232 }
5233 else {
5234 VISIT(c, expr, s->v.AnnAssign.annotation);
5235 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005236 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005237 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005238 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005239 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005240 }
5241 break;
5242 case Attribute_kind:
5243 if (!s->v.AnnAssign.value &&
5244 !check_ann_expr(c, targ->v.Attribute.value)) {
5245 return 0;
5246 }
5247 break;
5248 case Subscript_kind:
5249 if (!s->v.AnnAssign.value &&
5250 (!check_ann_expr(c, targ->v.Subscript.value) ||
5251 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5252 return 0;
5253 }
5254 break;
5255 default:
5256 PyErr_Format(PyExc_SystemError,
5257 "invalid node type (%d) for annotated assignment",
5258 targ->kind);
5259 return 0;
5260 }
5261 /* Annotation is evaluated last. */
5262 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5263 return 0;
5264 }
5265 return 1;
5266}
5267
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005268/* Raises a SyntaxError and returns 0.
5269 If something goes wrong, a different exception may be raised.
5270*/
5271
5272static int
5273compiler_error(struct compiler *c, const char *errstr)
5274{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005275 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005277
Victor Stinner14e461d2013-08-26 22:28:21 +02005278 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 if (!loc) {
5280 Py_INCREF(Py_None);
5281 loc = Py_None;
5282 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005283 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005284 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 if (!u)
5286 goto exit;
5287 v = Py_BuildValue("(zO)", errstr, u);
5288 if (!v)
5289 goto exit;
5290 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005291 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 Py_DECREF(loc);
5293 Py_XDECREF(u);
5294 Py_XDECREF(v);
5295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005296}
5297
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005298/* Emits a SyntaxWarning and returns 1 on success.
5299 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5300 and returns 0.
5301*/
5302static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005303compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005304{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005305 va_list vargs;
5306#ifdef HAVE_STDARG_PROTOTYPES
5307 va_start(vargs, format);
5308#else
5309 va_start(vargs);
5310#endif
5311 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5312 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005313 if (msg == NULL) {
5314 return 0;
5315 }
5316 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5317 c->u->u_lineno, NULL, NULL) < 0)
5318 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005319 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005320 /* Replace the SyntaxWarning exception with a SyntaxError
5321 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005322 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005323 assert(PyUnicode_AsUTF8(msg) != NULL);
5324 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005325 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005326 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005327 return 0;
5328 }
5329 Py_DECREF(msg);
5330 return 1;
5331}
5332
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005333static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334compiler_handle_subscr(struct compiler *c, const char *kind,
5335 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 /* XXX this code is duplicated */
5340 switch (ctx) {
5341 case AugLoad: /* fall through to Load */
5342 case Load: op = BINARY_SUBSCR; break;
5343 case AugStore:/* fall through to Store */
5344 case Store: op = STORE_SUBSCR; break;
5345 case Del: op = DELETE_SUBSCR; break;
5346 case Param:
5347 PyErr_Format(PyExc_SystemError,
5348 "invalid %s kind %d in subscript\n",
5349 kind, ctx);
5350 return 0;
5351 }
5352 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005353 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 }
5355 else if (ctx == AugStore) {
5356 ADDOP(c, ROT_THREE);
5357 }
5358 ADDOP(c, op);
5359 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005360}
5361
5362static int
5363compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 int n = 2;
5366 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 /* only handles the cases where BUILD_SLICE is emitted */
5369 if (s->v.Slice.lower) {
5370 VISIT(c, expr, s->v.Slice.lower);
5371 }
5372 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005373 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (s->v.Slice.upper) {
5377 VISIT(c, expr, s->v.Slice.upper);
5378 }
5379 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005380 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 }
5382
5383 if (s->v.Slice.step) {
5384 n++;
5385 VISIT(c, expr, s->v.Slice.step);
5386 }
5387 ADDOP_I(c, BUILD_SLICE, n);
5388 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005389}
5390
5391static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5393 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 switch (s->kind) {
5396 case Slice_kind:
5397 return compiler_slice(c, s, ctx);
5398 case Index_kind:
5399 VISIT(c, expr, s->v.Index.value);
5400 break;
5401 case ExtSlice_kind:
5402 default:
5403 PyErr_SetString(PyExc_SystemError,
5404 "extended slice invalid in nested slice");
5405 return 0;
5406 }
5407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408}
5409
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005410static int
5411compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5412{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005413 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 switch (s->kind) {
5415 case Index_kind:
5416 kindname = "index";
5417 if (ctx != AugStore) {
5418 VISIT(c, expr, s->v.Index.value);
5419 }
5420 break;
5421 case Slice_kind:
5422 kindname = "slice";
5423 if (ctx != AugStore) {
5424 if (!compiler_slice(c, s, ctx))
5425 return 0;
5426 }
5427 break;
5428 case ExtSlice_kind:
5429 kindname = "extended slice";
5430 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005431 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 for (i = 0; i < n; i++) {
5433 slice_ty sub = (slice_ty)asdl_seq_GET(
5434 s->v.ExtSlice.dims, i);
5435 if (!compiler_visit_nested_slice(c, sub, ctx))
5436 return 0;
5437 }
5438 ADDOP_I(c, BUILD_TUPLE, n);
5439 }
5440 break;
5441 default:
5442 PyErr_Format(PyExc_SystemError,
5443 "invalid subscript kind %d", s->kind);
5444 return 0;
5445 }
5446 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447}
5448
Thomas Wouters89f507f2006-12-13 04:49:30 +00005449/* End of the compiler section, beginning of the assembler section */
5450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005452 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453
5454 XXX must handle implicit jumps from one block to next
5455*/
5456
Thomas Wouters89f507f2006-12-13 04:49:30 +00005457struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 PyObject *a_bytecode; /* string containing bytecode */
5459 int a_offset; /* offset into bytecode */
5460 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005461 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 PyObject *a_lnotab; /* string containing lnotab */
5463 int a_lnotab_off; /* offset into lnotab */
5464 int a_lineno; /* last lineno of emitted instruction */
5465 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005466};
5467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005468static void
T. Wouters99b54d62019-09-12 07:05:33 -07005469dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005470{
T. Wouters99b54d62019-09-12 07:05:33 -07005471 int i, j;
5472
5473 /* Get rid of recursion for normal control flow.
5474 Since the number of blocks is limited, unused space in a_postorder
5475 (from a_nblocks to end) can be used as a stack for still not ordered
5476 blocks. */
5477 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005479 assert(a->a_nblocks < j);
5480 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 }
T. Wouters99b54d62019-09-12 07:05:33 -07005482 while (j < end) {
5483 b = a->a_postorder[j++];
5484 for (i = 0; i < b->b_iused; i++) {
5485 struct instr *instr = &b->b_instr[i];
5486 if (instr->i_jrel || instr->i_jabs)
5487 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005488 }
T. Wouters99b54d62019-09-12 07:05:33 -07005489 assert(a->a_nblocks < j);
5490 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005492}
5493
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005494Py_LOCAL_INLINE(void)
5495stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005496{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005497 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005498 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 assert(b->b_startdepth < 0);
5500 b->b_startdepth = depth;
5501 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005503}
5504
5505/* Find the flow path that needs the largest stack. We assume that
5506 * cycles in the flow graph have no net effect on the stack depth.
5507 */
5508static int
5509stackdepth(struct compiler *c)
5510{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005511 basicblock *b, *entryblock = NULL;
5512 basicblock **stack, **sp;
5513 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 b->b_startdepth = INT_MIN;
5516 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005517 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 }
5519 if (!entryblock)
5520 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005521 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5522 if (!stack) {
5523 PyErr_NoMemory();
5524 return -1;
5525 }
5526
5527 sp = stack;
5528 stackdepth_push(&sp, entryblock, 0);
5529 while (sp != stack) {
5530 b = *--sp;
5531 int depth = b->b_startdepth;
5532 assert(depth >= 0);
5533 basicblock *next = b->b_next;
5534 for (int i = 0; i < b->b_iused; i++) {
5535 struct instr *instr = &b->b_instr[i];
5536 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5537 if (effect == PY_INVALID_STACK_EFFECT) {
5538 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5539 Py_FatalError("PyCompile_OpcodeStackEffect()");
5540 }
5541 int new_depth = depth + effect;
5542 if (new_depth > maxdepth) {
5543 maxdepth = new_depth;
5544 }
5545 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5546 if (instr->i_jrel || instr->i_jabs) {
5547 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5548 assert(effect != PY_INVALID_STACK_EFFECT);
5549 int target_depth = depth + effect;
5550 if (target_depth > maxdepth) {
5551 maxdepth = target_depth;
5552 }
5553 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005554 stackdepth_push(&sp, instr->i_target, target_depth);
5555 }
5556 depth = new_depth;
5557 if (instr->i_opcode == JUMP_ABSOLUTE ||
5558 instr->i_opcode == JUMP_FORWARD ||
5559 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005560 instr->i_opcode == RAISE_VARARGS ||
5561 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005562 {
5563 /* remaining code is dead */
5564 next = NULL;
5565 break;
5566 }
5567 }
5568 if (next != NULL) {
5569 stackdepth_push(&sp, next, depth);
5570 }
5571 }
5572 PyObject_Free(stack);
5573 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005574}
5575
5576static int
5577assemble_init(struct assembler *a, int nblocks, int firstlineno)
5578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 memset(a, 0, sizeof(struct assembler));
5580 a->a_lineno = firstlineno;
5581 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5582 if (!a->a_bytecode)
5583 return 0;
5584 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5585 if (!a->a_lnotab)
5586 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005587 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 PyErr_NoMemory();
5589 return 0;
5590 }
T. Wouters99b54d62019-09-12 07:05:33 -07005591 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005593 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 PyErr_NoMemory();
5595 return 0;
5596 }
5597 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005598}
5599
5600static void
5601assemble_free(struct assembler *a)
5602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 Py_XDECREF(a->a_bytecode);
5604 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005605 if (a->a_postorder)
5606 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005607}
5608
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005609static int
5610blocksize(basicblock *b)
5611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 int i;
5613 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005616 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005618}
5619
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005620/* Appends a pair to the end of the line number table, a_lnotab, representing
5621 the instruction's bytecode offset and line number. See
5622 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005623
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005625assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005628 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005630
Serhiy Storchakaab874002016-09-11 13:48:15 +03005631 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 if(d_bytecode == 0 && d_lineno == 0)
5637 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 if (d_bytecode > 255) {
5640 int j, nbytes, ncodes = d_bytecode / 255;
5641 nbytes = a->a_lnotab_off + 2 * ncodes;
5642 len = PyBytes_GET_SIZE(a->a_lnotab);
5643 if (nbytes >= len) {
5644 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5645 len = nbytes;
5646 else if (len <= INT_MAX / 2)
5647 len *= 2;
5648 else {
5649 PyErr_NoMemory();
5650 return 0;
5651 }
5652 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5653 return 0;
5654 }
5655 lnotab = (unsigned char *)
5656 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5657 for (j = 0; j < ncodes; j++) {
5658 *lnotab++ = 255;
5659 *lnotab++ = 0;
5660 }
5661 d_bytecode -= ncodes * 255;
5662 a->a_lnotab_off += ncodes * 2;
5663 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005664 assert(0 <= d_bytecode && d_bytecode <= 255);
5665
5666 if (d_lineno < -128 || 127 < d_lineno) {
5667 int j, nbytes, ncodes, k;
5668 if (d_lineno < 0) {
5669 k = -128;
5670 /* use division on positive numbers */
5671 ncodes = (-d_lineno) / 128;
5672 }
5673 else {
5674 k = 127;
5675 ncodes = d_lineno / 127;
5676 }
5677 d_lineno -= ncodes * k;
5678 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 nbytes = a->a_lnotab_off + 2 * ncodes;
5680 len = PyBytes_GET_SIZE(a->a_lnotab);
5681 if (nbytes >= len) {
5682 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5683 len = nbytes;
5684 else if (len <= INT_MAX / 2)
5685 len *= 2;
5686 else {
5687 PyErr_NoMemory();
5688 return 0;
5689 }
5690 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5691 return 0;
5692 }
5693 lnotab = (unsigned char *)
5694 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5695 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005696 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 d_bytecode = 0;
5698 for (j = 1; j < ncodes; j++) {
5699 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005700 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 a->a_lnotab_off += ncodes * 2;
5703 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005704 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 len = PyBytes_GET_SIZE(a->a_lnotab);
5707 if (a->a_lnotab_off + 2 >= len) {
5708 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5709 return 0;
5710 }
5711 lnotab = (unsigned char *)
5712 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 a->a_lnotab_off += 2;
5715 if (d_bytecode) {
5716 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005717 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 }
5719 else { /* First line of a block; def stmt, etc. */
5720 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005721 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 }
5723 a->a_lineno = i->i_lineno;
5724 a->a_lineno_off = a->a_offset;
5725 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005726}
5727
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005728/* assemble_emit()
5729 Extend the bytecode with a new instruction.
5730 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005731*/
5732
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005733static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005734assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005735{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005736 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005737 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005738 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005739
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 arg = i->i_oparg;
5741 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 if (i->i_lineno && !assemble_lnotab(a, i))
5743 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005744 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 if (len > PY_SSIZE_T_MAX / 2)
5746 return 0;
5747 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5748 return 0;
5749 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005750 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005752 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005754}
5755
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005756static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005757assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005760 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 /* Compute the size of each block and fixup jump args.
5764 Replace block pointer with position in bytecode. */
5765 do {
5766 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005767 for (i = a->a_nblocks - 1; i >= 0; i--) {
5768 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 bsize = blocksize(b);
5770 b->b_offset = totsize;
5771 totsize += bsize;
5772 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005773 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5775 bsize = b->b_offset;
5776 for (i = 0; i < b->b_iused; i++) {
5777 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005778 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 /* Relative jumps are computed relative to
5780 the instruction pointer after fetching
5781 the jump instruction.
5782 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005783 bsize += isize;
5784 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005786 if (instr->i_jrel) {
5787 instr->i_oparg -= bsize;
5788 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005789 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005790 if (instrsize(instr->i_oparg) != isize) {
5791 extended_arg_recompile = 1;
5792 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 }
5795 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 /* XXX: This is an awful hack that could hurt performance, but
5798 on the bright side it should work until we come up
5799 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 The issue is that in the first loop blocksize() is called
5802 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005803 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 So we loop until we stop seeing new EXTENDED_ARGs.
5807 The only EXTENDED_ARGs that could be popping up are
5808 ones in jump instructions. So this should converge
5809 fairly quickly.
5810 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005811 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005812}
5813
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005814static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005815dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005818 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 tuple = PyTuple_New(size);
5821 if (tuple == NULL)
5822 return NULL;
5823 while (PyDict_Next(dict, &pos, &k, &v)) {
5824 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005825 Py_INCREF(k);
5826 assert((i - offset) < size);
5827 assert((i - offset) >= 0);
5828 PyTuple_SET_ITEM(tuple, i - offset, k);
5829 }
5830 return tuple;
5831}
5832
5833static PyObject *
5834consts_dict_keys_inorder(PyObject *dict)
5835{
5836 PyObject *consts, *k, *v;
5837 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5838
5839 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5840 if (consts == NULL)
5841 return NULL;
5842 while (PyDict_Next(dict, &pos, &k, &v)) {
5843 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005844 /* The keys of the dictionary can be tuples wrapping a contant.
5845 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5846 * the object we want is always second. */
5847 if (PyTuple_CheckExact(k)) {
5848 k = PyTuple_GET_ITEM(k, 1);
5849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005851 assert(i < size);
5852 assert(i >= 0);
5853 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005855 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005856}
5857
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005858static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005859compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005862 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005863 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005864 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 if (ste->ste_nested)
5866 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005867 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005869 if (!ste->ste_generator && ste->ste_coroutine)
5870 flags |= CO_COROUTINE;
5871 if (ste->ste_generator && ste->ste_coroutine)
5872 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 if (ste->ste_varargs)
5874 flags |= CO_VARARGS;
5875 if (ste->ste_varkeywords)
5876 flags |= CO_VARKEYWORDS;
5877 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 /* (Only) inherit compilerflags in PyCF_MASK */
5880 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005881
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005882 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5883 ste->ste_coroutine &&
5884 !ste->ste_generator) {
5885 flags |= CO_COROUTINE;
5886 }
5887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005889}
5890
INADA Naokic2e16072018-11-26 21:23:22 +09005891// Merge *tuple* with constant cache.
5892// Unlike merge_consts_recursive(), this function doesn't work recursively.
5893static int
5894merge_const_tuple(struct compiler *c, PyObject **tuple)
5895{
5896 assert(PyTuple_CheckExact(*tuple));
5897
5898 PyObject *key = _PyCode_ConstantKey(*tuple);
5899 if (key == NULL) {
5900 return 0;
5901 }
5902
5903 // t is borrowed reference
5904 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5905 Py_DECREF(key);
5906 if (t == NULL) {
5907 return 0;
5908 }
5909 if (t == key) { // tuple is new constant.
5910 return 1;
5911 }
5912
5913 PyObject *u = PyTuple_GET_ITEM(t, 1);
5914 Py_INCREF(u);
5915 Py_DECREF(*tuple);
5916 *tuple = u;
5917 return 1;
5918}
5919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005920static PyCodeObject *
5921makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 PyObject *tmp;
5924 PyCodeObject *co = NULL;
5925 PyObject *consts = NULL;
5926 PyObject *names = NULL;
5927 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 PyObject *name = NULL;
5929 PyObject *freevars = NULL;
5930 PyObject *cellvars = NULL;
5931 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005932 Py_ssize_t nlocals;
5933 int nlocals_int;
5934 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005935 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005936
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005937 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 names = dict_keys_inorder(c->u->u_names, 0);
5939 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5940 if (!consts || !names || !varnames)
5941 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5944 if (!cellvars)
5945 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005946 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005947 if (!freevars)
5948 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005949
INADA Naokic2e16072018-11-26 21:23:22 +09005950 if (!merge_const_tuple(c, &names) ||
5951 !merge_const_tuple(c, &varnames) ||
5952 !merge_const_tuple(c, &cellvars) ||
5953 !merge_const_tuple(c, &freevars))
5954 {
5955 goto error;
5956 }
5957
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005958 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005959 assert(nlocals < INT_MAX);
5960 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 flags = compute_code_flags(c);
5963 if (flags < 0)
5964 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5967 if (!bytecode)
5968 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005970 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5971 if (!tmp)
5972 goto error;
5973 Py_DECREF(consts);
5974 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005975 if (!merge_const_tuple(c, &consts)) {
5976 goto error;
5977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005979 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005980 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005981 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005982 maxdepth = stackdepth(c);
5983 if (maxdepth < 0) {
5984 goto error;
5985 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005986 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5987 posonlyargcount, kwonlyargcount, nlocals_int,
5988 maxdepth, flags, bytecode, consts, names,
5989 varnames, freevars, cellvars, c->c_filename,
5990 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005991 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 Py_XDECREF(consts);
5993 Py_XDECREF(names);
5994 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 Py_XDECREF(name);
5996 Py_XDECREF(freevars);
5997 Py_XDECREF(cellvars);
5998 Py_XDECREF(bytecode);
5999 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006000}
6001
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006002
6003/* For debugging purposes only */
6004#if 0
6005static void
6006dump_instr(const struct instr *i)
6007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006008 const char *jrel = i->i_jrel ? "jrel " : "";
6009 const char *jabs = i->i_jabs ? "jabs " : "";
6010 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006013 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006016 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6017 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006018}
6019
6020static void
6021dump_basicblock(const basicblock *b)
6022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 const char *seen = b->b_seen ? "seen " : "";
6024 const char *b_return = b->b_return ? "return " : "";
6025 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6026 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6027 if (b->b_instr) {
6028 int i;
6029 for (i = 0; i < b->b_iused; i++) {
6030 fprintf(stderr, " [%02d] ", i);
6031 dump_instr(b->b_instr + i);
6032 }
6033 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006034}
6035#endif
6036
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006037static PyCodeObject *
6038assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 basicblock *b, *entryblock;
6041 struct assembler a;
6042 int i, j, nblocks;
6043 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 /* Make sure every block that falls off the end returns None.
6046 XXX NEXT_BLOCK() isn't quite right, because if the last
6047 block ends with a jump or return b_next shouldn't set.
6048 */
6049 if (!c->u->u_curblock->b_return) {
6050 NEXT_BLOCK(c);
6051 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006052 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 ADDOP(c, RETURN_VALUE);
6054 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006056 nblocks = 0;
6057 entryblock = NULL;
6058 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6059 nblocks++;
6060 entryblock = b;
6061 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 /* Set firstlineno if it wasn't explicitly set. */
6064 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006065 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006066 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6067 else
6068 c->u->u_firstlineno = 1;
6069 }
6070 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6071 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006072 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 /* Can't modify the bytecode after computing jump offsets. */
6075 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006076
T. Wouters99b54d62019-09-12 07:05:33 -07006077 /* Emit code in reverse postorder from dfs. */
6078 for (i = a.a_nblocks - 1; i >= 0; i--) {
6079 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006080 for (j = 0; j < b->b_iused; j++)
6081 if (!assemble_emit(&a, &b->b_instr[j]))
6082 goto error;
6083 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6086 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006087 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006088 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006090 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006091 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006092 assemble_free(&a);
6093 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006094}
Georg Brandl8334fd92010-12-04 10:26:46 +00006095
6096#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006097PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006098PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6099 PyArena *arena)
6100{
6101 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6102}