blob: ce6f18a1f571dd0a1f15bc56f1cfa9de15ad58db [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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Victor Stinnerc96be812019-05-14 17:34:56 +020027#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
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:
1024 return -1;
1025 case IMPORT_NAME:
1026 return -1;
1027 case IMPORT_FROM:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001030 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case JUMP_ABSOLUTE:
1033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001035 case JUMP_IF_TRUE_OR_POP:
1036 case JUMP_IF_FALSE_OR_POP:
1037 return jump ? 0 : -1;
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case POP_JUMP_IF_FALSE:
1040 case POP_JUMP_IF_TRUE:
1041 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_GLOBAL:
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001046 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* 0 in the normal flow.
1049 * Restore the stack position and push 6 values before jumping to
1050 * the handler if an exception be raised. */
1051 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001052 case RERAISE:
1053 return -3;
1054
1055 case WITH_EXCEPT_START:
1056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_FAST:
1059 return 1;
1060 case STORE_FAST:
1061 return -1;
1062 case DELETE_FAST:
1063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case RAISE_VARARGS:
1066 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001070 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001071 case CALL_METHOD:
1072 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg-1;
1075 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001076 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001077 case MAKE_FUNCTION:
1078 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1079 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case BUILD_SLICE:
1081 if (oparg == 3)
1082 return -2;
1083 else
1084 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case LOAD_CLOSURE:
1088 return 1;
1089 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001090 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return 1;
1092 case STORE_DEREF:
1093 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001094 case DELETE_DEREF:
1095 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096
1097 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case GET_AWAITABLE:
1099 return 0;
1100 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001101 /* 0 in the normal flow.
1102 * Restore the stack position to the position before the result
1103 * of __aenter__ and push 6 values before jumping to the handler
1104 * if an exception be raised. */
1105 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001106 case BEFORE_ASYNC_WITH:
1107 return 1;
1108 case GET_AITER:
1109 return 0;
1110 case GET_ANEXT:
1111 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001112 case GET_YIELD_FROM_ITER:
1113 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001114 case END_ASYNC_FOR:
1115 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001116 case FORMAT_VALUE:
1117 /* If there's a fmt_spec on the stack, we go from 2->1,
1118 else 1->1. */
1119 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001120 case LOAD_METHOD:
1121 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001122 case LOAD_ASSERTION_ERROR:
1123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001125 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
Larry Hastings3a907972013-11-23 14:49:22 -08001127 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128}
1129
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001130int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001131PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1132{
1133 return stack_effect(opcode, oparg, jump);
1134}
1135
1136int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001137PyCompile_OpcodeStackEffect(int opcode, int oparg)
1138{
1139 return stack_effect(opcode, oparg, -1);
1140}
1141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142/* Add an opcode with no argument.
1143 Returns 0 on failure, 1 on success.
1144*/
1145
1146static int
1147compiler_addop(struct compiler *c, int opcode)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 basicblock *b;
1150 struct instr *i;
1151 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001152 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001153 if (c->c_do_not_emit_bytecode) {
1154 return 1;
1155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 off = compiler_next_instr(c, c->u->u_curblock);
1157 if (off < 0)
1158 return 0;
1159 b = c->u->u_curblock;
1160 i = &b->b_instr[off];
1161 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001162 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (opcode == RETURN_VALUE)
1164 b->b_return = 1;
1165 compiler_set_lineno(c, off);
1166 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167}
1168
Victor Stinnerf8e32212013-11-19 23:56:34 +01001169static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1171{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001175 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001177 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001179 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001180 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return -1;
1184 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001185 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(v);
1187 return -1;
1188 }
1189 Py_DECREF(v);
1190 }
1191 else
1192 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001193 return arg;
1194}
1195
INADA Naokic2e16072018-11-26 21:23:22 +09001196// Merge const *o* recursively and return constant key object.
1197static PyObject*
1198merge_consts_recursive(struct compiler *c, PyObject *o)
1199{
1200 // None and Ellipsis are singleton, and key is the singleton.
1201 // No need to merge object and key.
1202 if (o == Py_None || o == Py_Ellipsis) {
1203 Py_INCREF(o);
1204 return o;
1205 }
1206
1207 PyObject *key = _PyCode_ConstantKey(o);
1208 if (key == NULL) {
1209 return NULL;
1210 }
1211
1212 // t is borrowed reference
1213 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1214 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001215 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001216 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001217 Py_DECREF(key);
1218 return t;
1219 }
1220
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001222 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001223 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001224 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 Py_ssize_t len = PyTuple_GET_SIZE(o);
1226 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001227 PyObject *item = PyTuple_GET_ITEM(o, i);
1228 PyObject *u = merge_consts_recursive(c, item);
1229 if (u == NULL) {
1230 Py_DECREF(key);
1231 return NULL;
1232 }
1233
1234 // See _PyCode_ConstantKey()
1235 PyObject *v; // borrowed
1236 if (PyTuple_CheckExact(u)) {
1237 v = PyTuple_GET_ITEM(u, 1);
1238 }
1239 else {
1240 v = u;
1241 }
1242 if (v != item) {
1243 Py_INCREF(v);
1244 PyTuple_SET_ITEM(o, i, v);
1245 Py_DECREF(item);
1246 }
1247
1248 Py_DECREF(u);
1249 }
1250 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001251 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001252 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001253 // constant keys.
1254 // See _PyCode_ConstantKey() for detail.
1255 assert(PyTuple_CheckExact(key));
1256 assert(PyTuple_GET_SIZE(key) == 2);
1257
1258 Py_ssize_t len = PySet_GET_SIZE(o);
1259 if (len == 0) { // empty frozenset should not be re-created.
1260 return key;
1261 }
1262 PyObject *tuple = PyTuple_New(len);
1263 if (tuple == NULL) {
1264 Py_DECREF(key);
1265 return NULL;
1266 }
1267 Py_ssize_t i = 0, pos = 0;
1268 PyObject *item;
1269 Py_hash_t hash;
1270 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1271 PyObject *k = merge_consts_recursive(c, item);
1272 if (k == NULL) {
1273 Py_DECREF(tuple);
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 PyObject *u;
1278 if (PyTuple_CheckExact(k)) {
1279 u = PyTuple_GET_ITEM(k, 1);
1280 Py_INCREF(u);
1281 Py_DECREF(k);
1282 }
1283 else {
1284 u = k;
1285 }
1286 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1287 i++;
1288 }
1289
1290 // Instead of rewriting o, we create new frozenset and embed in the
1291 // key tuple. Caller should get merged frozenset from the key tuple.
1292 PyObject *new = PyFrozenSet_New(tuple);
1293 Py_DECREF(tuple);
1294 if (new == NULL) {
1295 Py_DECREF(key);
1296 return NULL;
1297 }
1298 assert(PyTuple_GET_ITEM(key, 1) == o);
1299 Py_DECREF(o);
1300 PyTuple_SET_ITEM(key, 1, new);
1301 }
INADA Naokic2e16072018-11-26 21:23:22 +09001302
1303 return key;
1304}
1305
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001306static Py_ssize_t
1307compiler_add_const(struct compiler *c, PyObject *o)
1308{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001309 if (c->c_do_not_emit_bytecode) {
1310 return 0;
1311 }
1312
INADA Naokic2e16072018-11-26 21:23:22 +09001313 PyObject *key = merge_consts_recursive(c, o);
1314 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001315 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001316 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001317
INADA Naokic2e16072018-11-26 21:23:22 +09001318 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1319 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321}
1322
1323static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001324compiler_addop_load_const(struct compiler *c, PyObject *o)
1325{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001326 if (c->c_do_not_emit_bytecode) {
1327 return 1;
1328 }
1329
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001330 Py_ssize_t arg = compiler_add_const(c, o);
1331 if (arg < 0)
1332 return 0;
1333 return compiler_addop_i(c, LOAD_CONST, arg);
1334}
1335
1336static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001340 if (c->c_do_not_emit_bytecode) {
1341 return 1;
1342 }
1343
Victor Stinnerad9a0662013-11-19 22:23:20 +01001344 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return compiler_addop_i(c, opcode, arg);
1348}
1349
1350static int
1351compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001354 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001355
1356 if (c->c_do_not_emit_bytecode) {
1357 return 1;
1358 }
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1361 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363 arg = compiler_add_o(c, dict, mangled);
1364 Py_DECREF(mangled);
1365 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 return compiler_addop_i(c, opcode, arg);
1368}
1369
1370/* Add an opcode with an integer argument.
1371 Returns 0 on failure, 1 on success.
1372*/
1373
1374static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001375compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 struct instr *i;
1378 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001379
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001380 if (c->c_do_not_emit_bytecode) {
1381 return 1;
1382 }
1383
Victor Stinner2ad474b2016-03-01 23:34:47 +01001384 /* oparg value is unsigned, but a signed C int is usually used to store
1385 it in the C code (like Python/ceval.c).
1386
1387 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1388
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001389 The argument of a concrete bytecode instruction is limited to 8-bit.
1390 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1391 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001392 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 off = compiler_next_instr(c, c->u->u_curblock);
1395 if (off < 0)
1396 return 0;
1397 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001398 i->i_opcode = opcode;
1399 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 compiler_set_lineno(c, off);
1401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402}
1403
1404static int
1405compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 struct instr *i;
1408 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001410 if (c->c_do_not_emit_bytecode) {
1411 return 1;
1412 }
1413
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001414 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 assert(b != NULL);
1416 off = compiler_next_instr(c, c->u->u_curblock);
1417 if (off < 0)
1418 return 0;
1419 i = &c->u->u_curblock->b_instr[off];
1420 i->i_opcode = opcode;
1421 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (absolute)
1423 i->i_jabs = 1;
1424 else
1425 i->i_jrel = 1;
1426 compiler_set_lineno(c, off);
1427 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428}
1429
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001430/* NEXT_BLOCK() creates an implicit jump from the current block
1431 to the new block.
1432
1433 The returns inside this macro make it impossible to decref objects
1434 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (compiler_next_block((C)) == NULL) \
1438 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439}
1440
1441#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (!compiler_addop((C), (OP))) \
1443 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001446#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_addop((C), (OP))) { \
1448 compiler_exit_scope(c); \
1449 return 0; \
1450 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001451}
1452
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001453#define ADDOP_LOAD_CONST(C, O) { \
1454 if (!compiler_addop_load_const((C), (O))) \
1455 return 0; \
1456}
1457
1458/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1459#define ADDOP_LOAD_CONST_NEW(C, O) { \
1460 PyObject *__new_const = (O); \
1461 if (__new_const == NULL) { \
1462 return 0; \
1463 } \
1464 if (!compiler_addop_load_const((C), __new_const)) { \
1465 Py_DECREF(__new_const); \
1466 return 0; \
1467 } \
1468 Py_DECREF(__new_const); \
1469}
1470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001476/* Same as ADDOP_O, but steals a reference. */
1477#define ADDOP_N(C, OP, O, TYPE) { \
1478 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1479 Py_DECREF((O)); \
1480 return 0; \
1481 } \
1482 Py_DECREF((O)); \
1483}
1484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1487 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488}
1489
1490#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_i((C), (OP), (O))) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_j((C), (OP), (O), 1)) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_j((C), (OP), (O), 0)) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1506 the ASDL name to synthesize the name of the C type and the visit function.
1507*/
1508
1509#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (!compiler_visit_ ## TYPE((C), (V))) \
1511 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512}
1513
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001514#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!compiler_visit_ ## TYPE((C), (V))) { \
1516 compiler_exit_scope(c); \
1517 return 0; \
1518 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001519}
1520
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_visit_slice((C), (V), (CTX))) \
1523 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
1526#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 int _i; \
1528 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1529 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1530 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1531 if (!compiler_visit_ ## TYPE((C), elt)) \
1532 return 0; \
1533 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001536#define VISIT_SEQ_IN_SCOPE(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 compiler_exit_scope(c); \
1543 return 0; \
1544 } \
1545 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546}
1547
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001548/* These macros allows to check only for errors and not emmit bytecode
1549 * while visiting nodes.
1550*/
1551
1552#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1553 c->c_do_not_emit_bytecode++;
1554
1555#define END_DO_NOT_EMIT_BYTECODE \
1556 c->c_do_not_emit_bytecode--; \
1557}
1558
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001559/* Search if variable annotations are present statically in a block. */
1560
1561static int
1562find_ann(asdl_seq *stmts)
1563{
1564 int i, j, res = 0;
1565 stmt_ty st;
1566
1567 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1568 st = (stmt_ty)asdl_seq_GET(stmts, i);
1569 switch (st->kind) {
1570 case AnnAssign_kind:
1571 return 1;
1572 case For_kind:
1573 res = find_ann(st->v.For.body) ||
1574 find_ann(st->v.For.orelse);
1575 break;
1576 case AsyncFor_kind:
1577 res = find_ann(st->v.AsyncFor.body) ||
1578 find_ann(st->v.AsyncFor.orelse);
1579 break;
1580 case While_kind:
1581 res = find_ann(st->v.While.body) ||
1582 find_ann(st->v.While.orelse);
1583 break;
1584 case If_kind:
1585 res = find_ann(st->v.If.body) ||
1586 find_ann(st->v.If.orelse);
1587 break;
1588 case With_kind:
1589 res = find_ann(st->v.With.body);
1590 break;
1591 case AsyncWith_kind:
1592 res = find_ann(st->v.AsyncWith.body);
1593 break;
1594 case Try_kind:
1595 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1596 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1597 st->v.Try.handlers, j);
1598 if (find_ann(handler->v.ExceptHandler.body)) {
1599 return 1;
1600 }
1601 }
1602 res = find_ann(st->v.Try.body) ||
1603 find_ann(st->v.Try.finalbody) ||
1604 find_ann(st->v.Try.orelse);
1605 break;
1606 default:
1607 res = 0;
1608 }
1609 if (res) {
1610 break;
1611 }
1612 }
1613 return res;
1614}
1615
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001616/*
1617 * Frame block handling functions
1618 */
1619
1620static int
1621compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001622 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001623{
1624 struct fblockinfo *f;
1625 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1626 PyErr_SetString(PyExc_SyntaxError,
1627 "too many statically nested blocks");
1628 return 0;
1629 }
1630 f = &c->u->u_fblock[c->u->u_nfblocks++];
1631 f->fb_type = t;
1632 f->fb_block = b;
1633 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001634 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001635 return 1;
1636}
1637
1638static void
1639compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1640{
1641 struct compiler_unit *u = c->u;
1642 assert(u->u_nfblocks > 0);
1643 u->u_nfblocks--;
1644 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1645 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1646}
1647
Mark Shannonfee55262019-11-21 09:11:43 +00001648static int
1649compiler_call_exit_with_nones(struct compiler *c) {
1650 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1651 ADDOP(c, DUP_TOP);
1652 ADDOP(c, DUP_TOP);
1653 ADDOP_I(c, CALL_FUNCTION, 3);
1654 return 1;
1655}
1656
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001657/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001658 * popping the blocks will be restored afterwards, unless another
1659 * return, break or continue is found. In which case, the TOS will
1660 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001661 */
1662static int
1663compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1664 int preserve_tos)
1665{
1666 switch (info->fb_type) {
1667 case WHILE_LOOP:
1668 return 1;
1669
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001670 case FOR_LOOP:
1671 /* Pop the iterator */
1672 if (preserve_tos) {
1673 ADDOP(c, ROT_TWO);
1674 }
1675 ADDOP(c, POP_TOP);
1676 return 1;
1677
1678 case EXCEPT:
1679 ADDOP(c, POP_BLOCK);
1680 return 1;
1681
1682 case FINALLY_TRY:
1683 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001684 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001685 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1686 return 0;
1687 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001688 }
Mark Shannon88dce262019-12-30 09:53:36 +00001689 /* Emit the finally block, restoring the line number when done */
1690 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001691 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001692 c->u->u_lineno = saved_lineno;
1693 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001694 if (preserve_tos) {
1695 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001696 }
1697 return 1;
Mark Shannonfee55262019-11-21 09:11:43 +00001698
1699 case FINALLY_END:
1700 if (preserve_tos) {
1701 ADDOP(c, ROT_FOUR);
1702 }
1703 ADDOP(c, POP_TOP);
1704 ADDOP(c, POP_TOP);
1705 ADDOP(c, POP_TOP);
1706 if (preserve_tos) {
1707 ADDOP(c, ROT_FOUR);
1708 }
1709 ADDOP(c, POP_EXCEPT);
1710 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001711
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001712 case WITH:
1713 case ASYNC_WITH:
1714 ADDOP(c, POP_BLOCK);
1715 if (preserve_tos) {
1716 ADDOP(c, ROT_TWO);
1717 }
Mark Shannonfee55262019-11-21 09:11:43 +00001718 if(!compiler_call_exit_with_nones(c)) {
1719 return 0;
1720 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001721 if (info->fb_type == ASYNC_WITH) {
1722 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001723 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 ADDOP(c, YIELD_FROM);
1725 }
Mark Shannonfee55262019-11-21 09:11:43 +00001726 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 return 1;
1728
1729 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001730 if (info->fb_datum) {
1731 ADDOP(c, POP_BLOCK);
1732 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 if (preserve_tos) {
1734 ADDOP(c, ROT_FOUR);
1735 }
Mark Shannonfee55262019-11-21 09:11:43 +00001736 ADDOP(c, POP_EXCEPT);
1737 if (info->fb_datum) {
1738 ADDOP_LOAD_CONST(c, Py_None);
1739 compiler_nameop(c, info->fb_datum, Store);
1740 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001741 }
Mark Shannonfee55262019-11-21 09:11:43 +00001742 return 1;
1743
1744 case POP_VALUE:
1745 if (preserve_tos) {
1746 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001747 }
Mark Shannonfee55262019-11-21 09:11:43 +00001748 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 return 1;
1750 }
1751 Py_UNREACHABLE();
1752}
1753
Mark Shannonfee55262019-11-21 09:11:43 +00001754/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1755static int
1756compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1757 if (c->u->u_nfblocks == 0) {
1758 return 1;
1759 }
1760 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1761 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1762 *loop = top;
1763 return 1;
1764 }
1765 struct fblockinfo copy = *top;
1766 c->u->u_nfblocks--;
1767 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1768 return 0;
1769 }
1770 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1771 return 0;
1772 }
1773 c->u->u_fblock[c->u->u_nfblocks] = copy;
1774 c->u->u_nfblocks++;
1775 return 1;
1776}
1777
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001778/* Compile a sequence of statements, checking for a docstring
1779 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780
1781static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001782compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001784 int i = 0;
1785 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001786 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001787
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001788 /* Set current line number to the line number of first statement.
1789 This way line number for SETUP_ANNOTATIONS will always
1790 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301791 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001792 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1793 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001794 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001795 c->u->u_lineno = st->lineno;
1796 }
1797 /* Every annotated class and module should have __annotations__. */
1798 if (find_ann(stmts)) {
1799 ADDOP(c, SETUP_ANNOTATIONS);
1800 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001801 if (!asdl_seq_LEN(stmts))
1802 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001803 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001804 if (c->c_optimize < 2) {
1805 docstring = _PyAST_GetDocString(stmts);
1806 if (docstring) {
1807 i = 1;
1808 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1809 assert(st->kind == Expr_kind);
1810 VISIT(c, expr, st->v.Expr.value);
1811 if (!compiler_nameop(c, __doc__, Store))
1812 return 0;
1813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001815 for (; i < asdl_seq_LEN(stmts); i++)
1816 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818}
1819
1820static PyCodeObject *
1821compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 PyCodeObject *co;
1824 int addNone = 1;
1825 static PyObject *module;
1826 if (!module) {
1827 module = PyUnicode_InternFromString("<module>");
1828 if (!module)
1829 return NULL;
1830 }
1831 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001832 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 return NULL;
1834 switch (mod->kind) {
1835 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001836 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 compiler_exit_scope(c);
1838 return 0;
1839 }
1840 break;
1841 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001842 if (find_ann(mod->v.Interactive.body)) {
1843 ADDOP(c, SETUP_ANNOTATIONS);
1844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 c->c_interactive = 1;
1846 VISIT_SEQ_IN_SCOPE(c, stmt,
1847 mod->v.Interactive.body);
1848 break;
1849 case Expression_kind:
1850 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1851 addNone = 0;
1852 break;
1853 case Suite_kind:
1854 PyErr_SetString(PyExc_SystemError,
1855 "suite should not be possible");
1856 return 0;
1857 default:
1858 PyErr_Format(PyExc_SystemError,
1859 "module kind %d should not be possible",
1860 mod->kind);
1861 return 0;
1862 }
1863 co = assemble(c, addNone);
1864 compiler_exit_scope(c);
1865 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001866}
1867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868/* The test for LOCAL must come before the test for FREE in order to
1869 handle classes where name is both local and free. The local var is
1870 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001871*/
1872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873static int
1874get_ref_type(struct compiler *c, PyObject *name)
1875{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001876 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001877 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001878 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001879 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001880 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (scope == 0) {
1882 char buf[350];
1883 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001884 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001886 PyUnicode_AsUTF8(name),
1887 PyUnicode_AsUTF8(c->u->u_name),
1888 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1889 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1890 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1891 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 );
1893 Py_FatalError(buf);
1894 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897}
1898
1899static int
1900compiler_lookup_arg(PyObject *dict, PyObject *name)
1901{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001902 PyObject *v;
1903 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001905 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001906 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001912 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001913 if (qualname == NULL)
1914 qualname = co->co_name;
1915
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 if (free) {
1917 for (i = 0; i < free; ++i) {
1918 /* Bypass com_addop_varname because it will generate
1919 LOAD_DEREF but LOAD_CLOSURE is needed.
1920 */
1921 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1922 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 /* Special case: If a class contains a method with a
1925 free variable that has the same name as a method,
1926 the name will be considered free *and* local in the
1927 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001928 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001929 */
1930 reftype = get_ref_type(c, name);
1931 if (reftype == CELL)
1932 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1933 else /* (reftype == FREE) */
1934 arg = compiler_lookup_arg(c->u->u_freevars, name);
1935 if (arg == -1) {
1936 fprintf(stderr,
1937 "lookup %s in %s %d %d\n"
1938 "freevars of %s: %s\n",
1939 PyUnicode_AsUTF8(PyObject_Repr(name)),
1940 PyUnicode_AsUTF8(c->u->u_name),
1941 reftype, arg,
1942 PyUnicode_AsUTF8(co->co_name),
1943 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1944 Py_FatalError("compiler_make_closure()");
1945 }
1946 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001948 flags |= 0x08;
1949 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001951 ADDOP_LOAD_CONST(c, (PyObject*)co);
1952 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955}
1956
1957static int
1958compiler_decorators(struct compiler *c, asdl_seq* decos)
1959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (!decos)
1963 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1966 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1967 }
1968 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969}
1970
1971static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001972compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001974{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001975 /* Push a dict of keyword-only default values.
1976
1977 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1978 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001979 int i;
1980 PyObject *keys = NULL;
1981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1983 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1984 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1985 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001986 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 if (!mangled) {
1988 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 if (keys == NULL) {
1991 keys = PyList_New(1);
1992 if (keys == NULL) {
1993 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001994 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 }
1996 PyList_SET_ITEM(keys, 0, mangled);
1997 }
1998 else {
1999 int res = PyList_Append(keys, mangled);
2000 Py_DECREF(mangled);
2001 if (res == -1) {
2002 goto error;
2003 }
2004 }
2005 if (!compiler_visit_expr(c, default_)) {
2006 goto error;
2007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 }
2009 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002010 if (keys != NULL) {
2011 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2012 PyObject *keys_tuple = PyList_AsTuple(keys);
2013 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002014 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002016 assert(default_count > 0);
2017 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 }
2019 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002020 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 }
2022
2023error:
2024 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002025 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002026}
2027
2028static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002029compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2030{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002031 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002032 return 1;
2033}
2034
2035static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002036compiler_visit_argannotation(struct compiler *c, identifier id,
2037 expr_ty annotation, PyObject *names)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002040 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002041 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2042 VISIT(c, annexpr, annotation)
2043 }
2044 else {
2045 VISIT(c, expr, annotation);
2046 }
Victor Stinner065efc32014-02-18 22:07:56 +01002047 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002048 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002050 if (PyList_Append(names, mangled) < 0) {
2051 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002052 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002053 }
2054 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002056 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002057}
2058
2059static int
2060compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2061 PyObject *names)
2062{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 for (i = 0; i < asdl_seq_LEN(args); i++) {
2065 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 c,
2068 arg->arg,
2069 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002070 names))
2071 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002074}
2075
2076static int
2077compiler_visit_annotations(struct compiler *c, arguments_ty args,
2078 expr_ty returns)
2079{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002080 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002081 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002082
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002083 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 */
2085 static identifier return_str;
2086 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002087 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 names = PyList_New(0);
2089 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002090 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002091
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002092 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002094 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2095 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002096 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002097 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002098 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002102 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002103 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002104 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (!return_str) {
2108 return_str = PyUnicode_InternFromString("return");
2109 if (!return_str)
2110 goto error;
2111 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002112 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 goto error;
2114 }
2115
2116 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 PyObject *keytuple = PyList_AsTuple(names);
2119 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002120 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002121 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002124 else {
2125 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002126 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002127 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002128
2129error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002131 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002132}
2133
2134static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002135compiler_visit_defaults(struct compiler *c, arguments_ty args)
2136{
2137 VISIT_SEQ(c, expr, args->defaults);
2138 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2139 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140}
2141
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002142static Py_ssize_t
2143compiler_default_arguments(struct compiler *c, arguments_ty args)
2144{
2145 Py_ssize_t funcflags = 0;
2146 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002147 if (!compiler_visit_defaults(c, args))
2148 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002149 funcflags |= 0x01;
2150 }
2151 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002152 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002153 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002154 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002155 return -1;
2156 }
2157 else if (res > 0) {
2158 funcflags |= 0x02;
2159 }
2160 }
2161 return funcflags;
2162}
2163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164static int
Yury Selivanov75445082015-05-11 22:57:16 -04002165compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002168 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002169 arguments_ty args;
2170 expr_ty returns;
2171 identifier name;
2172 asdl_seq* decos;
2173 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002174 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002175 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002176 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002177 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178
Yury Selivanov75445082015-05-11 22:57:16 -04002179 if (is_async) {
2180 assert(s->kind == AsyncFunctionDef_kind);
2181
2182 args = s->v.AsyncFunctionDef.args;
2183 returns = s->v.AsyncFunctionDef.returns;
2184 decos = s->v.AsyncFunctionDef.decorator_list;
2185 name = s->v.AsyncFunctionDef.name;
2186 body = s->v.AsyncFunctionDef.body;
2187
2188 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2189 } else {
2190 assert(s->kind == FunctionDef_kind);
2191
2192 args = s->v.FunctionDef.args;
2193 returns = s->v.FunctionDef.returns;
2194 decos = s->v.FunctionDef.decorator_list;
2195 name = s->v.FunctionDef.name;
2196 body = s->v.FunctionDef.body;
2197
2198 scope_type = COMPILER_SCOPE_FUNCTION;
2199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (!compiler_decorators(c, decos))
2202 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002203
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002204 firstlineno = s->lineno;
2205 if (asdl_seq_LEN(decos)) {
2206 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2207 }
2208
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002209 funcflags = compiler_default_arguments(c, args);
2210 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002212 }
2213
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002214 annotations = compiler_visit_annotations(c, args, returns);
2215 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002216 return 0;
2217 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002218 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002219 funcflags |= 0x04;
2220 }
2221
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002222 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002223 return 0;
2224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225
INADA Naokicb41b272017-02-23 00:31:59 +09002226 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002227 if (c->c_optimize < 2) {
2228 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002229 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002230 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 compiler_exit_scope(c);
2232 return 0;
2233 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002236 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002238 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002240 qualname = c->u->u_qualname;
2241 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002243 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002244 Py_XDECREF(qualname);
2245 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002249 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002250 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* decorators */
2254 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2255 ADDOP_I(c, CALL_FUNCTION, 1);
2256 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257
Yury Selivanov75445082015-05-11 22:57:16 -04002258 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259}
2260
2261static int
2262compiler_class(struct compiler *c, stmt_ty s)
2263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyCodeObject *co;
2265 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002266 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (!compiler_decorators(c, decos))
2270 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002271
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002272 firstlineno = s->lineno;
2273 if (asdl_seq_LEN(decos)) {
2274 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2275 }
2276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* ultimately generate code for:
2278 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2279 where:
2280 <func> is a function/closure created from the class body;
2281 it has a single argument (__locals__) where the dict
2282 (or MutableSequence) representing the locals is passed
2283 <name> is the class name
2284 <bases> is the positional arguments and *varargs argument
2285 <keywords> is the keyword arguments and **kwds argument
2286 This borrows from compiler_call.
2287 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002290 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002291 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 return 0;
2293 /* this block represents what we do in the new scope */
2294 {
2295 /* use the class name for name mangling */
2296 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002297 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* load (global) __name__ ... */
2299 str = PyUnicode_InternFromString("__name__");
2300 if (!str || !compiler_nameop(c, str, Load)) {
2301 Py_XDECREF(str);
2302 compiler_exit_scope(c);
2303 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002304 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 Py_DECREF(str);
2306 /* ... and store it as __module__ */
2307 str = PyUnicode_InternFromString("__module__");
2308 if (!str || !compiler_nameop(c, str, Store)) {
2309 Py_XDECREF(str);
2310 compiler_exit_scope(c);
2311 return 0;
2312 }
2313 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002314 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002315 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002316 str = PyUnicode_InternFromString("__qualname__");
2317 if (!str || !compiler_nameop(c, str, Store)) {
2318 Py_XDECREF(str);
2319 compiler_exit_scope(c);
2320 return 0;
2321 }
2322 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002324 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 compiler_exit_scope(c);
2326 return 0;
2327 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002328 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002329 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002330 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002331 str = PyUnicode_InternFromString("__class__");
2332 if (str == NULL) {
2333 compiler_exit_scope(c);
2334 return 0;
2335 }
2336 i = compiler_lookup_arg(c->u->u_cellvars, str);
2337 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002338 if (i < 0) {
2339 compiler_exit_scope(c);
2340 return 0;
2341 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002342 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002345 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002346 str = PyUnicode_InternFromString("__classcell__");
2347 if (!str || !compiler_nameop(c, str, Store)) {
2348 Py_XDECREF(str);
2349 compiler_exit_scope(c);
2350 return 0;
2351 }
2352 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002354 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002355 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002356 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002357 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002358 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002359 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* create the code object */
2361 co = assemble(c, 1);
2362 }
2363 /* leave the new scope */
2364 compiler_exit_scope(c);
2365 if (co == NULL)
2366 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* 2. load the 'build_class' function */
2369 ADDOP(c, LOAD_BUILD_CLASS);
2370
2371 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002372 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 Py_DECREF(co);
2374
2375 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002376 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377
2378 /* 5. generate the rest of the code for the call */
2379 if (!compiler_call_helper(c, 2,
2380 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002381 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return 0;
2383
2384 /* 6. apply decorators */
2385 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2386 ADDOP_I(c, CALL_FUNCTION, 1);
2387 }
2388
2389 /* 7. store into <name> */
2390 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2391 return 0;
2392 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393}
2394
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002395/* Return 0 if the expression is a constant value except named singletons.
2396 Return 1 otherwise. */
2397static int
2398check_is_arg(expr_ty e)
2399{
2400 if (e->kind != Constant_kind) {
2401 return 1;
2402 }
2403 PyObject *value = e->v.Constant.value;
2404 return (value == Py_None
2405 || value == Py_False
2406 || value == Py_True
2407 || value == Py_Ellipsis);
2408}
2409
2410/* Check operands of identity chacks ("is" and "is not").
2411 Emit a warning if any operand is a constant except named singletons.
2412 Return 0 on error.
2413 */
2414static int
2415check_compare(struct compiler *c, expr_ty e)
2416{
2417 Py_ssize_t i, n;
2418 int left = check_is_arg(e->v.Compare.left);
2419 n = asdl_seq_LEN(e->v.Compare.ops);
2420 for (i = 0; i < n; i++) {
2421 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2422 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2423 if (op == Is || op == IsNot) {
2424 if (!right || !left) {
2425 const char *msg = (op == Is)
2426 ? "\"is\" with a literal. Did you mean \"==\"?"
2427 : "\"is not\" with a literal. Did you mean \"!=\"?";
2428 return compiler_warn(c, msg);
2429 }
2430 }
2431 left = right;
2432 }
2433 return 1;
2434}
2435
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002437cmpop(cmpop_ty op)
2438{
2439 switch (op) {
2440 case Eq:
2441 return PyCmp_EQ;
2442 case NotEq:
2443 return PyCmp_NE;
2444 case Lt:
2445 return PyCmp_LT;
2446 case LtE:
2447 return PyCmp_LE;
2448 case Gt:
2449 return PyCmp_GT;
2450 case GtE:
2451 return PyCmp_GE;
2452 case Is:
2453 return PyCmp_IS;
2454 case IsNot:
2455 return PyCmp_IS_NOT;
2456 case In:
2457 return PyCmp_IN;
2458 case NotIn:
2459 return PyCmp_NOT_IN;
2460 default:
2461 return PyCmp_BAD;
2462 }
2463}
2464
2465static int
2466compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2467{
2468 switch (e->kind) {
2469 case UnaryOp_kind:
2470 if (e->v.UnaryOp.op == Not)
2471 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2472 /* fallback to general implementation */
2473 break;
2474 case BoolOp_kind: {
2475 asdl_seq *s = e->v.BoolOp.values;
2476 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2477 assert(n >= 0);
2478 int cond2 = e->v.BoolOp.op == Or;
2479 basicblock *next2 = next;
2480 if (!cond2 != !cond) {
2481 next2 = compiler_new_block(c);
2482 if (next2 == NULL)
2483 return 0;
2484 }
2485 for (i = 0; i < n; ++i) {
2486 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2487 return 0;
2488 }
2489 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2490 return 0;
2491 if (next2 != next)
2492 compiler_use_next_block(c, next2);
2493 return 1;
2494 }
2495 case IfExp_kind: {
2496 basicblock *end, *next2;
2497 end = compiler_new_block(c);
2498 if (end == NULL)
2499 return 0;
2500 next2 = compiler_new_block(c);
2501 if (next2 == NULL)
2502 return 0;
2503 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2504 return 0;
2505 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2506 return 0;
2507 ADDOP_JREL(c, JUMP_FORWARD, end);
2508 compiler_use_next_block(c, next2);
2509 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2510 return 0;
2511 compiler_use_next_block(c, end);
2512 return 1;
2513 }
2514 case Compare_kind: {
2515 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2516 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002517 if (!check_compare(c, e)) {
2518 return 0;
2519 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002520 basicblock *cleanup = compiler_new_block(c);
2521 if (cleanup == NULL)
2522 return 0;
2523 VISIT(c, expr, e->v.Compare.left);
2524 for (i = 0; i < n; i++) {
2525 VISIT(c, expr,
2526 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2527 ADDOP(c, DUP_TOP);
2528 ADDOP(c, ROT_THREE);
2529 ADDOP_I(c, COMPARE_OP,
2530 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2531 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2532 NEXT_BLOCK(c);
2533 }
2534 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2535 ADDOP_I(c, COMPARE_OP,
2536 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2537 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2538 basicblock *end = compiler_new_block(c);
2539 if (end == NULL)
2540 return 0;
2541 ADDOP_JREL(c, JUMP_FORWARD, end);
2542 compiler_use_next_block(c, cleanup);
2543 ADDOP(c, POP_TOP);
2544 if (!cond) {
2545 ADDOP_JREL(c, JUMP_FORWARD, next);
2546 }
2547 compiler_use_next_block(c, end);
2548 return 1;
2549 }
2550 /* fallback to general implementation */
2551 break;
2552 }
2553 default:
2554 /* fallback to general implementation */
2555 break;
2556 }
2557
2558 /* general implementation */
2559 VISIT(c, expr, e);
2560 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2561 return 1;
2562}
2563
2564static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002565compiler_ifexp(struct compiler *c, expr_ty e)
2566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 basicblock *end, *next;
2568
2569 assert(e->kind == IfExp_kind);
2570 end = compiler_new_block(c);
2571 if (end == NULL)
2572 return 0;
2573 next = compiler_new_block(c);
2574 if (next == NULL)
2575 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002576 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2577 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 VISIT(c, expr, e->v.IfExp.body);
2579 ADDOP_JREL(c, JUMP_FORWARD, end);
2580 compiler_use_next_block(c, next);
2581 VISIT(c, expr, e->v.IfExp.orelse);
2582 compiler_use_next_block(c, end);
2583 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002584}
2585
2586static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587compiler_lambda(struct compiler *c, expr_ty e)
2588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002590 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002592 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 arguments_ty args = e->v.Lambda.args;
2594 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (!name) {
2597 name = PyUnicode_InternFromString("<lambda>");
2598 if (!name)
2599 return 0;
2600 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002602 funcflags = compiler_default_arguments(c, args);
2603 if (funcflags == -1) {
2604 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002606
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002607 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002608 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 /* Make None the first constant, so the lambda can't have a
2612 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002613 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002617 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2619 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2620 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002621 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 }
2623 else {
2624 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002625 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002627 qualname = c->u->u_qualname;
2628 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002630 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002633 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002634 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 Py_DECREF(co);
2636
2637 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638}
2639
2640static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641compiler_if(struct compiler *c, stmt_ty s)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 basicblock *end, *next;
2644 int constant;
2645 assert(s->kind == If_kind);
2646 end = compiler_new_block(c);
2647 if (end == NULL)
2648 return 0;
2649
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002650 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002651 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 * constant = 1: "if 1", "if 2", ...
2653 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002654 if (constant == 0) {
2655 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002657 END_DO_NOT_EMIT_BYTECODE
2658 if (s->v.If.orelse) {
2659 VISIT_SEQ(c, stmt, s->v.If.orelse);
2660 }
2661 } else if (constant == 1) {
2662 VISIT_SEQ(c, stmt, s->v.If.body);
2663 if (s->v.If.orelse) {
2664 BEGIN_DO_NOT_EMIT_BYTECODE
2665 VISIT_SEQ(c, stmt, s->v.If.orelse);
2666 END_DO_NOT_EMIT_BYTECODE
2667 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002669 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 next = compiler_new_block(c);
2671 if (next == NULL)
2672 return 0;
2673 }
Mark Shannonfee55262019-11-21 09:11:43 +00002674 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002676 }
2677 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002678 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002679 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002681 if (asdl_seq_LEN(s->v.If.orelse)) {
2682 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 compiler_use_next_block(c, next);
2684 VISIT_SEQ(c, stmt, s->v.If.orelse);
2685 }
2686 }
2687 compiler_use_next_block(c, end);
2688 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689}
2690
2691static int
2692compiler_for(struct compiler *c, stmt_ty s)
2693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 start = compiler_new_block(c);
2697 cleanup = compiler_new_block(c);
2698 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002699 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002701 }
2702 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 VISIT(c, expr, s->v.For.iter);
2706 ADDOP(c, GET_ITER);
2707 compiler_use_next_block(c, start);
2708 ADDOP_JREL(c, FOR_ITER, cleanup);
2709 VISIT(c, expr, s->v.For.target);
2710 VISIT_SEQ(c, stmt, s->v.For.body);
2711 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2712 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002713
2714 compiler_pop_fblock(c, FOR_LOOP, start);
2715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 VISIT_SEQ(c, stmt, s->v.For.orelse);
2717 compiler_use_next_block(c, end);
2718 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719}
2720
Yury Selivanov75445082015-05-11 22:57:16 -04002721
2722static int
2723compiler_async_for(struct compiler *c, stmt_ty s)
2724{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002725 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002726 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2727 c->u->u_ste->ste_coroutine = 1;
2728 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002729 return compiler_error(c, "'async for' outside async function");
2730 }
2731
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002732 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002733 except = compiler_new_block(c);
2734 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002735
Mark Shannonfee55262019-11-21 09:11:43 +00002736 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002737 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002738 }
Yury Selivanov75445082015-05-11 22:57:16 -04002739 VISIT(c, expr, s->v.AsyncFor.iter);
2740 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002741
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002742 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002743 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002744 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002745 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002746 /* SETUP_FINALLY to guard the __anext__ call */
2747 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002748 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002749 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002750 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002751 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002752
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002753 /* Success block for __anext__ */
2754 VISIT(c, expr, s->v.AsyncFor.target);
2755 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2756 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2757
2758 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002759
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002760 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002761 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002762 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002763
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002764 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002765 VISIT_SEQ(c, stmt, s->v.For.orelse);
2766
2767 compiler_use_next_block(c, end);
2768
2769 return 1;
2770}
2771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772static int
2773compiler_while(struct compiler *c, stmt_ty s)
2774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002776 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002779 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002780 // Push a dummy block so the VISIT_SEQ knows that we are
2781 // inside a while loop so it can correctly evaluate syntax
2782 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002783 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002784 return 0;
2785 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002786 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002787 // Remove the dummy block now that is not needed.
2788 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002789 END_DO_NOT_EMIT_BYTECODE
2790 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002792 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 return 1;
2794 }
2795 loop = compiler_new_block(c);
2796 end = compiler_new_block(c);
2797 if (constant == -1) {
2798 anchor = compiler_new_block(c);
2799 if (anchor == NULL)
2800 return 0;
2801 }
2802 if (loop == NULL || end == NULL)
2803 return 0;
2804 if (s->v.While.orelse) {
2805 orelse = compiler_new_block(c);
2806 if (orelse == NULL)
2807 return 0;
2808 }
2809 else
2810 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002813 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 return 0;
2815 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002816 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2817 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 }
2819 VISIT_SEQ(c, stmt, s->v.While.body);
2820 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 /* XXX should the two POP instructions be in a separate block
2823 if there is no else clause ?
2824 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002826 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002828 compiler_pop_fblock(c, WHILE_LOOP, loop);
2829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 if (orelse != NULL) /* what if orelse is just pass? */
2831 VISIT_SEQ(c, stmt, s->v.While.orelse);
2832 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835}
2836
2837static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002838compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002840 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002841 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002842 if (c->u->u_ste->ste_type != FunctionBlock)
2843 return compiler_error(c, "'return' outside function");
2844 if (s->v.Return.value != NULL &&
2845 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2846 {
2847 return compiler_error(
2848 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 if (preserve_tos) {
2851 VISIT(c, expr, s->v.Return.value);
2852 }
Mark Shannonfee55262019-11-21 09:11:43 +00002853 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2854 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002856 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002857 }
2858 else if (!preserve_tos) {
2859 VISIT(c, expr, s->v.Return.value);
2860 }
2861 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864}
2865
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002866static int
2867compiler_break(struct compiler *c)
2868{
Mark Shannonfee55262019-11-21 09:11:43 +00002869 struct fblockinfo *loop = NULL;
2870 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2871 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002872 }
Mark Shannonfee55262019-11-21 09:11:43 +00002873 if (loop == NULL) {
2874 return compiler_error(c, "'break' outside loop");
2875 }
2876 if (!compiler_unwind_fblock(c, loop, 0)) {
2877 return 0;
2878 }
2879 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2880 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881}
2882
2883static int
2884compiler_continue(struct compiler *c)
2885{
Mark Shannonfee55262019-11-21 09:11:43 +00002886 struct fblockinfo *loop = NULL;
2887 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2888 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002889 }
Mark Shannonfee55262019-11-21 09:11:43 +00002890 if (loop == NULL) {
2891 return compiler_error(c, "'continue' not properly in loop");
2892 }
2893 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2894 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895}
2896
2897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899
2900 SETUP_FINALLY L
2901 <code for body>
2902 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002903 <code for finalbody>
2904 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002905 L:
2906 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002907 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909 The special instructions use the block stack. Each block
2910 stack entry contains the instruction that created it (here
2911 SETUP_FINALLY), the level of the value stack at the time the
2912 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 Pushes the current value stack level and the label
2916 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002918 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002921 when a SETUP_FINALLY entry is found, the raised and the caught
2922 exceptions are pushed onto the value stack (and the exception
2923 condition is cleared), and the interpreter jumps to the label
2924 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925*/
2926
2927static int
2928compiler_try_finally(struct compiler *c, stmt_ty s)
2929{
Mark Shannonfee55262019-11-21 09:11:43 +00002930 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 body = compiler_new_block(c);
2933 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002934 exit = compiler_new_block(c);
2935 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002938 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 ADDOP_JREL(c, SETUP_FINALLY, end);
2940 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002941 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002943 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2944 if (!compiler_try_except(c, s))
2945 return 0;
2946 }
2947 else {
2948 VISIT_SEQ(c, stmt, s->v.Try.body);
2949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002951 compiler_pop_fblock(c, FINALLY_TRY, body);
2952 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2953 ADDOP_JREL(c, JUMP_FORWARD, exit);
2954 /* `finally` block */
2955 compiler_use_next_block(c, end);
2956 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2957 return 0;
2958 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2959 compiler_pop_fblock(c, FINALLY_END, end);
2960 ADDOP(c, RERAISE);
2961 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963}
2964
2965/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002966 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 (The contents of the value stack is shown in [], with the top
2968 at the right; 'tb' is trace-back info, 'val' the exception's
2969 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970
2971 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002972 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 [] <code for S>
2974 [] POP_BLOCK
2975 [] JUMP_FORWARD L0
2976
2977 [tb, val, exc] L1: DUP )
2978 [tb, val, exc, exc] <evaluate E1> )
2979 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2980 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2981 [tb, val, exc] POP
2982 [tb, val] <assign to V1> (or POP if no V1)
2983 [tb] POP
2984 [] <code for S1>
2985 JUMP_FORWARD L0
2986
2987 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002988 .............................etc.......................
2989
Mark Shannonfee55262019-11-21 09:11:43 +00002990 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991
2992 [] L0: <next statement>
2993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994 Of course, parts are not generated if Vi or Ei is not present.
2995*/
2996static int
2997compiler_try_except(struct compiler *c, stmt_ty s)
2998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003000 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 body = compiler_new_block(c);
3003 except = compiler_new_block(c);
3004 orelse = compiler_new_block(c);
3005 end = compiler_new_block(c);
3006 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3007 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003008 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003010 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003012 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 ADDOP(c, POP_BLOCK);
3014 compiler_pop_fblock(c, EXCEPT, body);
3015 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003016 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 compiler_use_next_block(c, except);
3018 for (i = 0; i < n; i++) {
3019 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003020 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 if (!handler->v.ExceptHandler.type && i < n-1)
3022 return compiler_error(c, "default 'except:' must be last");
3023 c->u->u_lineno_set = 0;
3024 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003025 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 except = compiler_new_block(c);
3027 if (except == NULL)
3028 return 0;
3029 if (handler->v.ExceptHandler.type) {
3030 ADDOP(c, DUP_TOP);
3031 VISIT(c, expr, handler->v.ExceptHandler.type);
3032 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3033 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3034 }
3035 ADDOP(c, POP_TOP);
3036 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003037 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003038
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003039 cleanup_end = compiler_new_block(c);
3040 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003041 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003042 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003043 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003044
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003045 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3046 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003048 /*
3049 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003050 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003051 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003052 try:
3053 # body
3054 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003055 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003056 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 /* second try: */
3060 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3061 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003062 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003063 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 /* second # body */
3066 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003067 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003068 ADDOP(c, POP_BLOCK);
3069 ADDOP(c, POP_EXCEPT);
3070 /* name = None; del name */
3071 ADDOP_LOAD_CONST(c, Py_None);
3072 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3073 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3074 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075
Mark Shannonfee55262019-11-21 09:11:43 +00003076 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003079 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003080 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083
Mark Shannonfee55262019-11-21 09:11:43 +00003084 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 }
3086 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003090 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092
Guido van Rossumb940e112007-01-10 16:19:56 +00003093 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 ADDOP(c, POP_TOP);
3095 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003096 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003099 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003100 ADDOP(c, POP_EXCEPT);
3101 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 compiler_use_next_block(c, except);
3104 }
Mark Shannonfee55262019-11-21 09:11:43 +00003105 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003107 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 compiler_use_next_block(c, end);
3109 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110}
3111
3112static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003113compiler_try(struct compiler *c, stmt_ty s) {
3114 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3115 return compiler_try_finally(c, s);
3116 else
3117 return compiler_try_except(c, s);
3118}
3119
3120
3121static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122compiler_import_as(struct compiler *c, identifier name, identifier asname)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* The IMPORT_NAME opcode was already generated. This function
3125 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003128 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003130 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3131 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003132 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003133 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003134 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003136 while (1) {
3137 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003139 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003140 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003141 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003142 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003144 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003145 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003146 if (dot == -1) {
3147 break;
3148 }
3149 ADDOP(c, ROT_TWO);
3150 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003152 if (!compiler_nameop(c, asname, Store)) {
3153 return 0;
3154 }
3155 ADDOP(c, POP_TOP);
3156 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 }
3158 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159}
3160
3161static int
3162compiler_import(struct compiler *c, stmt_ty s)
3163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* The Import node stores a module name like a.b.c as a single
3165 string. This is convenient for all cases except
3166 import a.b.c as d
3167 where we need to parse that string to extract the individual
3168 module names.
3169 XXX Perhaps change the representation to make this case simpler?
3170 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003171 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 for (i = 0; i < n; i++) {
3174 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3175 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003177 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3178 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 if (alias->asname) {
3182 r = compiler_import_as(c, alias->name, alias->asname);
3183 if (!r)
3184 return r;
3185 }
3186 else {
3187 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003188 Py_ssize_t dot = PyUnicode_FindChar(
3189 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003190 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003191 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003192 if (tmp == NULL)
3193 return 0;
3194 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003196 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 Py_DECREF(tmp);
3198 }
3199 if (!r)
3200 return r;
3201 }
3202 }
3203 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204}
3205
3206static int
3207compiler_from_import(struct compiler *c, stmt_ty s)
3208{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003209 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003210 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 if (!empty_string) {
3214 empty_string = PyUnicode_FromString("");
3215 if (!empty_string)
3216 return 0;
3217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003219 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003220
3221 names = PyTuple_New(n);
3222 if (!names)
3223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 /* build up the names */
3226 for (i = 0; i < n; i++) {
3227 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3228 Py_INCREF(alias->name);
3229 PyTuple_SET_ITEM(names, i, alias->name);
3230 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003233 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 Py_DECREF(names);
3235 return compiler_error(c, "from __future__ imports must occur "
3236 "at the beginning of the file");
3237 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003238 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 if (s->v.ImportFrom.module) {
3241 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3242 }
3243 else {
3244 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3245 }
3246 for (i = 0; i < n; i++) {
3247 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3248 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003250 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 assert(n == 1);
3252 ADDOP(c, IMPORT_STAR);
3253 return 1;
3254 }
3255
3256 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3257 store_name = alias->name;
3258 if (alias->asname)
3259 store_name = alias->asname;
3260
3261 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 return 0;
3263 }
3264 }
3265 /* remove imported module */
3266 ADDOP(c, POP_TOP);
3267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268}
3269
3270static int
3271compiler_assert(struct compiler *c, stmt_ty s)
3272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274
Georg Brandl8334fd92010-12-04 10:26:46 +00003275 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003278 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3279 {
3280 if (!compiler_warn(c, "assertion is always true, "
3281 "perhaps remove parentheses?"))
3282 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003283 return 0;
3284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 end = compiler_new_block(c);
3287 if (end == NULL)
3288 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003289 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3290 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003291 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 if (s->v.Assert.msg) {
3293 VISIT(c, expr, s->v.Assert.msg);
3294 ADDOP_I(c, CALL_FUNCTION, 1);
3295 }
3296 ADDOP_I(c, RAISE_VARARGS, 1);
3297 compiler_use_next_block(c, end);
3298 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299}
3300
3301static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003302compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3303{
3304 if (c->c_interactive && c->c_nestlevel <= 1) {
3305 VISIT(c, expr, value);
3306 ADDOP(c, PRINT_EXPR);
3307 return 1;
3308 }
3309
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003310 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003311 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003312 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003313 }
3314
3315 VISIT(c, expr, value);
3316 ADDOP(c, POP_TOP);
3317 return 1;
3318}
3319
3320static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321compiler_visit_stmt(struct compiler *c, stmt_ty s)
3322{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003323 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 /* Always assign a lineno to the next instruction for a stmt. */
3326 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003327 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 switch (s->kind) {
3331 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003332 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 case ClassDef_kind:
3334 return compiler_class(c, s);
3335 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003336 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 case Delete_kind:
3338 VISIT_SEQ(c, expr, s->v.Delete.targets)
3339 break;
3340 case Assign_kind:
3341 n = asdl_seq_LEN(s->v.Assign.targets);
3342 VISIT(c, expr, s->v.Assign.value);
3343 for (i = 0; i < n; i++) {
3344 if (i < n - 1)
3345 ADDOP(c, DUP_TOP);
3346 VISIT(c, expr,
3347 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3348 }
3349 break;
3350 case AugAssign_kind:
3351 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003352 case AnnAssign_kind:
3353 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 case For_kind:
3355 return compiler_for(c, s);
3356 case While_kind:
3357 return compiler_while(c, s);
3358 case If_kind:
3359 return compiler_if(c, s);
3360 case Raise_kind:
3361 n = 0;
3362 if (s->v.Raise.exc) {
3363 VISIT(c, expr, s->v.Raise.exc);
3364 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003365 if (s->v.Raise.cause) {
3366 VISIT(c, expr, s->v.Raise.cause);
3367 n++;
3368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003370 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003372 case Try_kind:
3373 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case Assert_kind:
3375 return compiler_assert(c, s);
3376 case Import_kind:
3377 return compiler_import(c, s);
3378 case ImportFrom_kind:
3379 return compiler_from_import(c, s);
3380 case Global_kind:
3381 case Nonlocal_kind:
3382 break;
3383 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003384 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 case Pass_kind:
3386 break;
3387 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003388 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 case Continue_kind:
3390 return compiler_continue(c);
3391 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003392 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003393 case AsyncFunctionDef_kind:
3394 return compiler_function(c, s, 1);
3395 case AsyncWith_kind:
3396 return compiler_async_with(c, s, 0);
3397 case AsyncFor_kind:
3398 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 }
Yury Selivanov75445082015-05-11 22:57:16 -04003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003402}
3403
3404static int
3405unaryop(unaryop_ty op)
3406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 switch (op) {
3408 case Invert:
3409 return UNARY_INVERT;
3410 case Not:
3411 return UNARY_NOT;
3412 case UAdd:
3413 return UNARY_POSITIVE;
3414 case USub:
3415 return UNARY_NEGATIVE;
3416 default:
3417 PyErr_Format(PyExc_SystemError,
3418 "unary op %d should not be possible", op);
3419 return 0;
3420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421}
3422
3423static int
3424binop(struct compiler *c, operator_ty op)
3425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 switch (op) {
3427 case Add:
3428 return BINARY_ADD;
3429 case Sub:
3430 return BINARY_SUBTRACT;
3431 case Mult:
3432 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003433 case MatMult:
3434 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 case Div:
3436 return BINARY_TRUE_DIVIDE;
3437 case Mod:
3438 return BINARY_MODULO;
3439 case Pow:
3440 return BINARY_POWER;
3441 case LShift:
3442 return BINARY_LSHIFT;
3443 case RShift:
3444 return BINARY_RSHIFT;
3445 case BitOr:
3446 return BINARY_OR;
3447 case BitXor:
3448 return BINARY_XOR;
3449 case BitAnd:
3450 return BINARY_AND;
3451 case FloorDiv:
3452 return BINARY_FLOOR_DIVIDE;
3453 default:
3454 PyErr_Format(PyExc_SystemError,
3455 "binary op %d should not be possible", op);
3456 return 0;
3457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458}
3459
3460static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461inplace_binop(struct compiler *c, operator_ty op)
3462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 switch (op) {
3464 case Add:
3465 return INPLACE_ADD;
3466 case Sub:
3467 return INPLACE_SUBTRACT;
3468 case Mult:
3469 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003470 case MatMult:
3471 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 case Div:
3473 return INPLACE_TRUE_DIVIDE;
3474 case Mod:
3475 return INPLACE_MODULO;
3476 case Pow:
3477 return INPLACE_POWER;
3478 case LShift:
3479 return INPLACE_LSHIFT;
3480 case RShift:
3481 return INPLACE_RSHIFT;
3482 case BitOr:
3483 return INPLACE_OR;
3484 case BitXor:
3485 return INPLACE_XOR;
3486 case BitAnd:
3487 return INPLACE_AND;
3488 case FloorDiv:
3489 return INPLACE_FLOOR_DIVIDE;
3490 default:
3491 PyErr_Format(PyExc_SystemError,
3492 "inplace binary op %d should not be possible", op);
3493 return 0;
3494 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495}
3496
3497static int
3498compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3499{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003500 int op, scope;
3501 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 PyObject *dict = c->u->u_names;
3505 PyObject *mangled;
3506 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003508 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3509 !_PyUnicode_EqualToASCIIString(name, "True") &&
3510 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003511
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003512 mangled = _Py_Mangle(c->u->u_private, name);
3513 if (!mangled)
3514 return 0;
3515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 op = 0;
3517 optype = OP_NAME;
3518 scope = PyST_GetScope(c->u->u_ste, mangled);
3519 switch (scope) {
3520 case FREE:
3521 dict = c->u->u_freevars;
3522 optype = OP_DEREF;
3523 break;
3524 case CELL:
3525 dict = c->u->u_cellvars;
3526 optype = OP_DEREF;
3527 break;
3528 case LOCAL:
3529 if (c->u->u_ste->ste_type == FunctionBlock)
3530 optype = OP_FAST;
3531 break;
3532 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003533 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 optype = OP_GLOBAL;
3535 break;
3536 case GLOBAL_EXPLICIT:
3537 optype = OP_GLOBAL;
3538 break;
3539 default:
3540 /* scope can be 0 */
3541 break;
3542 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003545 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 switch (optype) {
3548 case OP_DEREF:
3549 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003550 case Load:
3551 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3552 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003553 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003554 op = STORE_DEREF;
3555 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 case AugLoad:
3557 case AugStore:
3558 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003559 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 case Param:
3561 default:
3562 PyErr_SetString(PyExc_SystemError,
3563 "param invalid for deref variable");
3564 return 0;
3565 }
3566 break;
3567 case OP_FAST:
3568 switch (ctx) {
3569 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003570 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003571 op = STORE_FAST;
3572 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 case Del: op = DELETE_FAST; break;
3574 case AugLoad:
3575 case AugStore:
3576 break;
3577 case Param:
3578 default:
3579 PyErr_SetString(PyExc_SystemError,
3580 "param invalid for local variable");
3581 return 0;
3582 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003583 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 return 1;
3585 case OP_GLOBAL:
3586 switch (ctx) {
3587 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003588 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003589 op = STORE_GLOBAL;
3590 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 case Del: op = DELETE_GLOBAL; break;
3592 case AugLoad:
3593 case AugStore:
3594 break;
3595 case Param:
3596 default:
3597 PyErr_SetString(PyExc_SystemError,
3598 "param invalid for global variable");
3599 return 0;
3600 }
3601 break;
3602 case OP_NAME:
3603 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003604 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003605 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003606 op = STORE_NAME;
3607 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 case Del: op = DELETE_NAME; break;
3609 case AugLoad:
3610 case AugStore:
3611 break;
3612 case Param:
3613 default:
3614 PyErr_SetString(PyExc_SystemError,
3615 "param invalid for name variable");
3616 return 0;
3617 }
3618 break;
3619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 assert(op);
3622 arg = compiler_add_o(c, dict, mangled);
3623 Py_DECREF(mangled);
3624 if (arg < 0)
3625 return 0;
3626 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627}
3628
3629static int
3630compiler_boolop(struct compiler *c, expr_ty e)
3631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003633 int jumpi;
3634 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 assert(e->kind == BoolOp_kind);
3638 if (e->v.BoolOp.op == And)
3639 jumpi = JUMP_IF_FALSE_OR_POP;
3640 else
3641 jumpi = JUMP_IF_TRUE_OR_POP;
3642 end = compiler_new_block(c);
3643 if (end == NULL)
3644 return 0;
3645 s = e->v.BoolOp.values;
3646 n = asdl_seq_LEN(s) - 1;
3647 assert(n >= 0);
3648 for (i = 0; i < n; ++i) {
3649 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3650 ADDOP_JABS(c, jumpi, end);
3651 }
3652 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3653 compiler_use_next_block(c, end);
3654 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655}
3656
3657static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003658starunpack_helper(struct compiler *c, asdl_seq *elts,
3659 int single_op, int inner_op, int outer_op)
3660{
3661 Py_ssize_t n = asdl_seq_LEN(elts);
3662 Py_ssize_t i, nsubitems = 0, nseen = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003663 if (n > 2 && are_all_items_const(elts, 0, n)) {
3664 PyObject *folded = PyTuple_New(n);
3665 if (folded == NULL) {
3666 return 0;
3667 }
3668 PyObject *val;
3669 for (i = 0; i < n; i++) {
3670 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3671 Py_INCREF(val);
3672 PyTuple_SET_ITEM(folded, i, val);
3673 }
3674 if (outer_op == BUILD_SET_UNPACK) {
3675 Py_SETREF(folded, PyFrozenSet_New(folded));
3676 if (folded == NULL) {
3677 return 0;
3678 }
3679 }
3680 ADDOP_LOAD_CONST_NEW(c, folded);
3681 ADDOP_I(c, outer_op, 1);
3682 return 1;
3683 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003684 for (i = 0; i < n; i++) {
3685 expr_ty elt = asdl_seq_GET(elts, i);
3686 if (elt->kind == Starred_kind) {
3687 if (nseen) {
3688 ADDOP_I(c, inner_op, nseen);
3689 nseen = 0;
3690 nsubitems++;
3691 }
3692 VISIT(c, expr, elt->v.Starred.value);
3693 nsubitems++;
3694 }
3695 else {
3696 VISIT(c, expr, elt);
3697 nseen++;
3698 }
3699 }
3700 if (nsubitems) {
3701 if (nseen) {
3702 ADDOP_I(c, inner_op, nseen);
3703 nsubitems++;
3704 }
3705 ADDOP_I(c, outer_op, nsubitems);
3706 }
3707 else
3708 ADDOP_I(c, single_op, nseen);
3709 return 1;
3710}
3711
3712static int
3713assignment_helper(struct compiler *c, asdl_seq *elts)
3714{
3715 Py_ssize_t n = asdl_seq_LEN(elts);
3716 Py_ssize_t i;
3717 int seen_star = 0;
3718 for (i = 0; i < n; i++) {
3719 expr_ty elt = asdl_seq_GET(elts, i);
3720 if (elt->kind == Starred_kind && !seen_star) {
3721 if ((i >= (1 << 8)) ||
3722 (n-i-1 >= (INT_MAX >> 8)))
3723 return compiler_error(c,
3724 "too many expressions in "
3725 "star-unpacking assignment");
3726 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3727 seen_star = 1;
3728 asdl_seq_SET(elts, i, elt->v.Starred.value);
3729 }
3730 else if (elt->kind == Starred_kind) {
3731 return compiler_error(c,
3732 "two starred expressions in assignment");
3733 }
3734 }
3735 if (!seen_star) {
3736 ADDOP_I(c, UNPACK_SEQUENCE, n);
3737 }
3738 VISIT_SEQ(c, expr, elts);
3739 return 1;
3740}
3741
3742static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743compiler_list(struct compiler *c, expr_ty e)
3744{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003745 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003746 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003747 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 else if (e->v.List.ctx == Load) {
3750 return starunpack_helper(c, elts,
3751 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 else
3754 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756}
3757
3758static int
3759compiler_tuple(struct compiler *c, expr_ty e)
3760{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003762 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 return assignment_helper(c, elts);
3764 }
3765 else if (e->v.Tuple.ctx == Load) {
3766 return starunpack_helper(c, elts,
3767 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3768 }
3769 else
3770 VISIT_SEQ(c, expr, elts);
3771 return 1;
3772}
3773
3774static int
3775compiler_set(struct compiler *c, expr_ty e)
3776{
3777 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3778 BUILD_SET, BUILD_SET_UNPACK);
3779}
3780
3781static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003782are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3783{
3784 Py_ssize_t i;
3785 for (i = begin; i < end; i++) {
3786 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003787 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003788 return 0;
3789 }
3790 return 1;
3791}
3792
3793static int
3794compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3795{
3796 Py_ssize_t i, n = end - begin;
3797 PyObject *keys, *key;
3798 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3799 for (i = begin; i < end; i++) {
3800 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3801 }
3802 keys = PyTuple_New(n);
3803 if (keys == NULL) {
3804 return 0;
3805 }
3806 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003807 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003808 Py_INCREF(key);
3809 PyTuple_SET_ITEM(keys, i - begin, key);
3810 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003811 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003812 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3813 }
3814 else {
3815 for (i = begin; i < end; i++) {
3816 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3817 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3818 }
3819 ADDOP_I(c, BUILD_MAP, n);
3820 }
3821 return 1;
3822}
3823
3824static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003825compiler_dict(struct compiler *c, expr_ty e)
3826{
Victor Stinner976bb402016-03-23 11:36:19 +01003827 Py_ssize_t i, n, elements;
3828 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003829 int is_unpacking = 0;
3830 n = asdl_seq_LEN(e->v.Dict.values);
3831 containers = 0;
3832 elements = 0;
3833 for (i = 0; i < n; i++) {
3834 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3835 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003836 if (!compiler_subdict(c, e, i - elements, i))
3837 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003838 containers++;
3839 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003841 if (is_unpacking) {
3842 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3843 containers++;
3844 }
3845 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003846 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 }
3848 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003849 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003850 if (!compiler_subdict(c, e, n - elements, n))
3851 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003852 containers++;
3853 }
3854 /* If there is more than one dict, they need to be merged into a new
3855 * dict. If there is one dict and it's an unpacking, then it needs
3856 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003857 if (containers > 1 || is_unpacking) {
3858 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 }
3860 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861}
3862
3863static int
3864compiler_compare(struct compiler *c, expr_ty e)
3865{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003866 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003868 if (!check_compare(c, e)) {
3869 return 0;
3870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003872 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3873 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3874 if (n == 0) {
3875 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3876 ADDOP_I(c, COMPARE_OP,
3877 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3878 }
3879 else {
3880 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 if (cleanup == NULL)
3882 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003883 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 VISIT(c, expr,
3885 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003886 ADDOP(c, DUP_TOP);
3887 ADDOP(c, ROT_THREE);
3888 ADDOP_I(c, COMPARE_OP,
3889 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3890 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3891 NEXT_BLOCK(c);
3892 }
3893 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3894 ADDOP_I(c, COMPARE_OP,
3895 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 basicblock *end = compiler_new_block(c);
3897 if (end == NULL)
3898 return 0;
3899 ADDOP_JREL(c, JUMP_FORWARD, end);
3900 compiler_use_next_block(c, cleanup);
3901 ADDOP(c, ROT_TWO);
3902 ADDOP(c, POP_TOP);
3903 compiler_use_next_block(c, end);
3904 }
3905 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906}
3907
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003908static PyTypeObject *
3909infer_type(expr_ty e)
3910{
3911 switch (e->kind) {
3912 case Tuple_kind:
3913 return &PyTuple_Type;
3914 case List_kind:
3915 case ListComp_kind:
3916 return &PyList_Type;
3917 case Dict_kind:
3918 case DictComp_kind:
3919 return &PyDict_Type;
3920 case Set_kind:
3921 case SetComp_kind:
3922 return &PySet_Type;
3923 case GeneratorExp_kind:
3924 return &PyGen_Type;
3925 case Lambda_kind:
3926 return &PyFunction_Type;
3927 case JoinedStr_kind:
3928 case FormattedValue_kind:
3929 return &PyUnicode_Type;
3930 case Constant_kind:
3931 return e->v.Constant.value->ob_type;
3932 default:
3933 return NULL;
3934 }
3935}
3936
3937static int
3938check_caller(struct compiler *c, expr_ty e)
3939{
3940 switch (e->kind) {
3941 case Constant_kind:
3942 case Tuple_kind:
3943 case List_kind:
3944 case ListComp_kind:
3945 case Dict_kind:
3946 case DictComp_kind:
3947 case Set_kind:
3948 case SetComp_kind:
3949 case GeneratorExp_kind:
3950 case JoinedStr_kind:
3951 case FormattedValue_kind:
3952 return compiler_warn(c, "'%.200s' object is not callable; "
3953 "perhaps you missed a comma?",
3954 infer_type(e)->tp_name);
3955 default:
3956 return 1;
3957 }
3958}
3959
3960static int
3961check_subscripter(struct compiler *c, expr_ty e)
3962{
3963 PyObject *v;
3964
3965 switch (e->kind) {
3966 case Constant_kind:
3967 v = e->v.Constant.value;
3968 if (!(v == Py_None || v == Py_Ellipsis ||
3969 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3970 PyAnySet_Check(v)))
3971 {
3972 return 1;
3973 }
3974 /* fall through */
3975 case Set_kind:
3976 case SetComp_kind:
3977 case GeneratorExp_kind:
3978 case Lambda_kind:
3979 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3980 "perhaps you missed a comma?",
3981 infer_type(e)->tp_name);
3982 default:
3983 return 1;
3984 }
3985}
3986
3987static int
3988check_index(struct compiler *c, expr_ty e, slice_ty s)
3989{
3990 PyObject *v;
3991
3992 if (s->kind != Index_kind) {
3993 return 1;
3994 }
3995 PyTypeObject *index_type = infer_type(s->v.Index.value);
3996 if (index_type == NULL
3997 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3998 || index_type == &PySlice_Type) {
3999 return 1;
4000 }
4001
4002 switch (e->kind) {
4003 case Constant_kind:
4004 v = e->v.Constant.value;
4005 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4006 return 1;
4007 }
4008 /* fall through */
4009 case Tuple_kind:
4010 case List_kind:
4011 case ListComp_kind:
4012 case JoinedStr_kind:
4013 case FormattedValue_kind:
4014 return compiler_warn(c, "%.200s indices must be integers or slices, "
4015 "not %.200s; "
4016 "perhaps you missed a comma?",
4017 infer_type(e)->tp_name,
4018 index_type->tp_name);
4019 default:
4020 return 1;
4021 }
4022}
4023
Zackery Spytz97f5de02019-03-22 01:30:32 -06004024// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004026maybe_optimize_method_call(struct compiler *c, expr_ty e)
4027{
4028 Py_ssize_t argsl, i;
4029 expr_ty meth = e->v.Call.func;
4030 asdl_seq *args = e->v.Call.args;
4031
4032 /* Check that the call node is an attribute access, and that
4033 the call doesn't have keyword parameters. */
4034 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4035 asdl_seq_LEN(e->v.Call.keywords))
4036 return -1;
4037
4038 /* Check that there are no *varargs types of arguments. */
4039 argsl = asdl_seq_LEN(args);
4040 for (i = 0; i < argsl; i++) {
4041 expr_ty elt = asdl_seq_GET(args, i);
4042 if (elt->kind == Starred_kind) {
4043 return -1;
4044 }
4045 }
4046
4047 /* Alright, we can optimize the code. */
4048 VISIT(c, expr, meth->v.Attribute.value);
4049 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4050 VISIT_SEQ(c, expr, e->v.Call.args);
4051 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4052 return 1;
4053}
4054
4055static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004056compiler_call(struct compiler *c, expr_ty e)
4057{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004058 int ret = maybe_optimize_method_call(c, e);
4059 if (ret >= 0) {
4060 return ret;
4061 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004062 if (!check_caller(c, e->v.Call.func)) {
4063 return 0;
4064 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 VISIT(c, expr, e->v.Call.func);
4066 return compiler_call_helper(c, 0,
4067 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004068 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004069}
4070
Eric V. Smith235a6f02015-09-19 14:51:32 -04004071static int
4072compiler_joined_str(struct compiler *c, expr_ty e)
4073{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004074 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004075 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4076 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004077 return 1;
4078}
4079
Eric V. Smitha78c7952015-11-03 12:45:05 -05004080/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004081static int
4082compiler_formatted_value(struct compiler *c, expr_ty e)
4083{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004084 /* Our oparg encodes 2 pieces of information: the conversion
4085 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004086
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004087 Convert the conversion char to 3 bits:
4088 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004089 !s : 001 0x1 FVC_STR
4090 !r : 010 0x2 FVC_REPR
4091 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004092
Eric V. Smitha78c7952015-11-03 12:45:05 -05004093 next bit is whether or not we have a format spec:
4094 yes : 100 0x4
4095 no : 000 0x0
4096 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004097
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004098 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004099 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004100
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004101 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004102 VISIT(c, expr, e->v.FormattedValue.value);
4103
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004104 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004105 case 's': oparg = FVC_STR; break;
4106 case 'r': oparg = FVC_REPR; break;
4107 case 'a': oparg = FVC_ASCII; break;
4108 case -1: oparg = FVC_NONE; break;
4109 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004110 PyErr_Format(PyExc_SystemError,
4111 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004112 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004113 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004114 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004115 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004116 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004117 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004118 }
4119
Eric V. Smitha78c7952015-11-03 12:45:05 -05004120 /* And push our opcode and oparg */
4121 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004122
Eric V. Smith235a6f02015-09-19 14:51:32 -04004123 return 1;
4124}
4125
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004126static int
4127compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4128{
4129 Py_ssize_t i, n = end - begin;
4130 keyword_ty kw;
4131 PyObject *keys, *key;
4132 assert(n > 0);
4133 if (n > 1) {
4134 for (i = begin; i < end; i++) {
4135 kw = asdl_seq_GET(keywords, i);
4136 VISIT(c, expr, kw->value);
4137 }
4138 keys = PyTuple_New(n);
4139 if (keys == NULL) {
4140 return 0;
4141 }
4142 for (i = begin; i < end; i++) {
4143 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4144 Py_INCREF(key);
4145 PyTuple_SET_ITEM(keys, i - begin, key);
4146 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004147 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004148 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4149 }
4150 else {
4151 /* a for loop only executes once */
4152 for (i = begin; i < end; i++) {
4153 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004154 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004155 VISIT(c, expr, kw->value);
4156 }
4157 ADDOP_I(c, BUILD_MAP, n);
4158 }
4159 return 1;
4160}
4161
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004162/* shared code between compiler_call and compiler_class */
4163static int
4164compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004165 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004166 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004167 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004168{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004169 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004170 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004171
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004172 /* the number of tuples and dictionaries on the stack */
4173 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4174
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004175 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004176 nkwelts = asdl_seq_LEN(keywords);
4177
4178 for (i = 0; i < nkwelts; i++) {
4179 keyword_ty kw = asdl_seq_GET(keywords, i);
4180 if (kw->arg == NULL) {
4181 mustdictunpack = 1;
4182 break;
4183 }
4184 }
4185
4186 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004187 for (i = 0; i < nelts; i++) {
4188 expr_ty elt = asdl_seq_GET(args, i);
4189 if (elt->kind == Starred_kind) {
4190 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004191 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004192 if (nseen) {
4193 ADDOP_I(c, BUILD_TUPLE, nseen);
4194 nseen = 0;
4195 nsubargs++;
4196 }
4197 VISIT(c, expr, elt->v.Starred.value);
4198 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004199 }
4200 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004201 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004202 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004205
4206 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004207 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004208 if (nseen) {
4209 /* Pack up any trailing positional arguments. */
4210 ADDOP_I(c, BUILD_TUPLE, nseen);
4211 nsubargs++;
4212 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004213 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004214 /* If we ended up with more than one stararg, we need
4215 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004216 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004217 }
4218 else if (nsubargs == 0) {
4219 ADDOP_I(c, BUILD_TUPLE, 0);
4220 }
4221 nseen = 0; /* the number of keyword arguments on the stack following */
4222 for (i = 0; i < nkwelts; i++) {
4223 keyword_ty kw = asdl_seq_GET(keywords, i);
4224 if (kw->arg == NULL) {
4225 /* A keyword argument unpacking. */
4226 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004227 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4228 return 0;
4229 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004230 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004231 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004232 VISIT(c, expr, kw->value);
4233 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004234 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004235 else {
4236 nseen++;
4237 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004238 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004239 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004240 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004241 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004242 return 0;
4243 nsubkwargs++;
4244 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004245 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004247 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004248 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004249 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4250 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004252 else if (nkwelts) {
4253 PyObject *names;
4254 VISIT_SEQ(c, keyword, keywords);
4255 names = PyTuple_New(nkwelts);
4256 if (names == NULL) {
4257 return 0;
4258 }
4259 for (i = 0; i < nkwelts; i++) {
4260 keyword_ty kw = asdl_seq_GET(keywords, i);
4261 Py_INCREF(kw->arg);
4262 PyTuple_SET_ITEM(names, i, kw->arg);
4263 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004264 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004265 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4266 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004268 else {
4269 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4270 return 1;
4271 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272}
4273
Nick Coghlan650f0d02007-04-15 12:05:43 +00004274
4275/* List and set comprehensions and generator expressions work by creating a
4276 nested function to perform the actual iteration. This means that the
4277 iteration variables don't leak into the current scope.
4278 The defined function is called immediately following its definition, with the
4279 result of that call being the result of the expression.
4280 The LC/SC version returns the populated container, while the GE version is
4281 flagged in symtable.c as a generator, so it returns the generator object
4282 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004283
4284 Possible cleanups:
4285 - iterate over the generator sequence instead of using recursion
4286*/
4287
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004288
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004290compiler_comprehension_generator(struct compiler *c,
4291 asdl_seq *generators, int gen_index,
4292 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004294 comprehension_ty gen;
4295 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4296 if (gen->is_async) {
4297 return compiler_async_comprehension_generator(
4298 c, generators, gen_index, elt, val, type);
4299 } else {
4300 return compiler_sync_comprehension_generator(
4301 c, generators, gen_index, elt, val, type);
4302 }
4303}
4304
4305static int
4306compiler_sync_comprehension_generator(struct compiler *c,
4307 asdl_seq *generators, int gen_index,
4308 expr_ty elt, expr_ty val, int type)
4309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 /* generate code for the iterator, then each of the ifs,
4311 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 comprehension_ty gen;
4314 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004315 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 start = compiler_new_block(c);
4318 skip = compiler_new_block(c);
4319 if_cleanup = compiler_new_block(c);
4320 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4323 anchor == NULL)
4324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 if (gen_index == 0) {
4329 /* Receive outermost iter as an implicit argument */
4330 c->u->u_argcount = 1;
4331 ADDOP_I(c, LOAD_FAST, 0);
4332 }
4333 else {
4334 /* Sub-iter - calculate on the fly */
4335 VISIT(c, expr, gen->iter);
4336 ADDOP(c, GET_ITER);
4337 }
4338 compiler_use_next_block(c, start);
4339 ADDOP_JREL(c, FOR_ITER, anchor);
4340 NEXT_BLOCK(c);
4341 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 /* XXX this needs to be cleaned up...a lot! */
4344 n = asdl_seq_LEN(gen->ifs);
4345 for (i = 0; i < n; i++) {
4346 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004347 if (!compiler_jump_if(c, e, if_cleanup, 0))
4348 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 NEXT_BLOCK(c);
4350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 if (++gen_index < asdl_seq_LEN(generators))
4353 if (!compiler_comprehension_generator(c,
4354 generators, gen_index,
4355 elt, val, type))
4356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 /* only append after the last for generator */
4359 if (gen_index >= asdl_seq_LEN(generators)) {
4360 /* comprehension specific code */
4361 switch (type) {
4362 case COMP_GENEXP:
4363 VISIT(c, expr, elt);
4364 ADDOP(c, YIELD_VALUE);
4365 ADDOP(c, POP_TOP);
4366 break;
4367 case COMP_LISTCOMP:
4368 VISIT(c, expr, elt);
4369 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4370 break;
4371 case COMP_SETCOMP:
4372 VISIT(c, expr, elt);
4373 ADDOP_I(c, SET_ADD, gen_index + 1);
4374 break;
4375 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004376 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004379 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 ADDOP_I(c, MAP_ADD, gen_index + 1);
4381 break;
4382 default:
4383 return 0;
4384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 compiler_use_next_block(c, skip);
4387 }
4388 compiler_use_next_block(c, if_cleanup);
4389 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4390 compiler_use_next_block(c, anchor);
4391
4392 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393}
4394
4395static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396compiler_async_comprehension_generator(struct compiler *c,
4397 asdl_seq *generators, int gen_index,
4398 expr_ty elt, expr_ty val, int type)
4399{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004400 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004401 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004402 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004403 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004405 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004406
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004407 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004408 return 0;
4409 }
4410
4411 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4412
4413 if (gen_index == 0) {
4414 /* Receive outermost iter as an implicit argument */
4415 c->u->u_argcount = 1;
4416 ADDOP_I(c, LOAD_FAST, 0);
4417 }
4418 else {
4419 /* Sub-iter - calculate on the fly */
4420 VISIT(c, expr, gen->iter);
4421 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004422 }
4423
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004424 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004426 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004427 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004428 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004429 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004431 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004432
4433 n = asdl_seq_LEN(gen->ifs);
4434 for (i = 0; i < n; i++) {
4435 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004436 if (!compiler_jump_if(c, e, if_cleanup, 0))
4437 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004438 NEXT_BLOCK(c);
4439 }
4440
4441 if (++gen_index < asdl_seq_LEN(generators))
4442 if (!compiler_comprehension_generator(c,
4443 generators, gen_index,
4444 elt, val, type))
4445 return 0;
4446
4447 /* only append after the last for generator */
4448 if (gen_index >= asdl_seq_LEN(generators)) {
4449 /* comprehension specific code */
4450 switch (type) {
4451 case COMP_GENEXP:
4452 VISIT(c, expr, elt);
4453 ADDOP(c, YIELD_VALUE);
4454 ADDOP(c, POP_TOP);
4455 break;
4456 case COMP_LISTCOMP:
4457 VISIT(c, expr, elt);
4458 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4459 break;
4460 case COMP_SETCOMP:
4461 VISIT(c, expr, elt);
4462 ADDOP_I(c, SET_ADD, gen_index + 1);
4463 break;
4464 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004465 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004466 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004467 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004468 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004469 ADDOP_I(c, MAP_ADD, gen_index + 1);
4470 break;
4471 default:
4472 return 0;
4473 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004474 }
4475 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004476 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4477
4478 compiler_use_next_block(c, except);
4479 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480
4481 return 1;
4482}
4483
4484static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004485compiler_comprehension(struct compiler *c, expr_ty e, int type,
4486 identifier name, asdl_seq *generators, expr_ty elt,
4487 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004491 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492 int is_async_function = c->u->u_ste->ste_coroutine;
4493 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004494
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004496
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004497 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4498 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004499 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004501 }
4502
4503 is_async_generator = c->u->u_ste->ste_coroutine;
4504
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004505 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 compiler_error(c, "asynchronous comprehension outside of "
4507 "an asynchronous function");
4508 goto error_in_scope;
4509 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 if (type != COMP_GENEXP) {
4512 int op;
4513 switch (type) {
4514 case COMP_LISTCOMP:
4515 op = BUILD_LIST;
4516 break;
4517 case COMP_SETCOMP:
4518 op = BUILD_SET;
4519 break;
4520 case COMP_DICTCOMP:
4521 op = BUILD_MAP;
4522 break;
4523 default:
4524 PyErr_Format(PyExc_SystemError,
4525 "unknown comprehension type %d", type);
4526 goto error_in_scope;
4527 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 ADDOP_I(c, op, 0);
4530 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (!compiler_comprehension_generator(c, generators, 0, elt,
4533 val, type))
4534 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 if (type != COMP_GENEXP) {
4537 ADDOP(c, RETURN_VALUE);
4538 }
4539
4540 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004541 qualname = c->u->u_qualname;
4542 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004544 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 goto error;
4546
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004547 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004549 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 Py_DECREF(co);
4551
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004552 VISIT(c, expr, outermost->iter);
4553
4554 if (outermost->is_async) {
4555 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556 } else {
4557 ADDOP(c, GET_ITER);
4558 }
4559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561
4562 if (is_async_generator && type != COMP_GENEXP) {
4563 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004564 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004565 ADDOP(c, YIELD_FROM);
4566 }
4567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004569error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004571error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004572 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 Py_XDECREF(co);
4574 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004575}
4576
4577static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004578compiler_genexp(struct compiler *c, expr_ty e)
4579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 static identifier name;
4581 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004582 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (!name)
4584 return 0;
4585 }
4586 assert(e->kind == GeneratorExp_kind);
4587 return compiler_comprehension(c, e, COMP_GENEXP, name,
4588 e->v.GeneratorExp.generators,
4589 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004590}
4591
4592static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004593compiler_listcomp(struct compiler *c, expr_ty e)
4594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 static identifier name;
4596 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004597 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 if (!name)
4599 return 0;
4600 }
4601 assert(e->kind == ListComp_kind);
4602 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4603 e->v.ListComp.generators,
4604 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004605}
4606
4607static int
4608compiler_setcomp(struct compiler *c, expr_ty e)
4609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 static identifier name;
4611 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004612 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 if (!name)
4614 return 0;
4615 }
4616 assert(e->kind == SetComp_kind);
4617 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4618 e->v.SetComp.generators,
4619 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004620}
4621
4622
4623static int
4624compiler_dictcomp(struct compiler *c, expr_ty e)
4625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 static identifier name;
4627 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004628 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 if (!name)
4630 return 0;
4631 }
4632 assert(e->kind == DictComp_kind);
4633 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4634 e->v.DictComp.generators,
4635 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004636}
4637
4638
4639static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004640compiler_visit_keyword(struct compiler *c, keyword_ty k)
4641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 VISIT(c, expr, k->value);
4643 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004644}
4645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004647 whether they are true or false.
4648
4649 Return values: 1 for true, 0 for false, -1 for non-constant.
4650 */
4651
4652static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004653expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004655 if (e->kind == Constant_kind) {
4656 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004657 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004658 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004659}
4660
Mark Shannonfee55262019-11-21 09:11:43 +00004661static int
4662compiler_with_except_finish(struct compiler *c) {
4663 basicblock *exit;
4664 exit = compiler_new_block(c);
4665 if (exit == NULL)
4666 return 0;
4667 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4668 ADDOP(c, RERAISE);
4669 compiler_use_next_block(c, exit);
4670 ADDOP(c, POP_TOP);
4671 ADDOP(c, POP_TOP);
4672 ADDOP(c, POP_TOP);
4673 ADDOP(c, POP_EXCEPT);
4674 ADDOP(c, POP_TOP);
4675 return 1;
4676}
Yury Selivanov75445082015-05-11 22:57:16 -04004677
4678/*
4679 Implements the async with statement.
4680
4681 The semantics outlined in that PEP are as follows:
4682
4683 async with EXPR as VAR:
4684 BLOCK
4685
4686 It is implemented roughly as:
4687
4688 context = EXPR
4689 exit = context.__aexit__ # not calling it
4690 value = await context.__aenter__()
4691 try:
4692 VAR = value # if VAR present in the syntax
4693 BLOCK
4694 finally:
4695 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004696 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004697 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004698 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004699 if not (await exit(*exc)):
4700 raise
4701 */
4702static int
4703compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4704{
Mark Shannonfee55262019-11-21 09:11:43 +00004705 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004706 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4707
4708 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004709 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4710 c->u->u_ste->ste_coroutine = 1;
4711 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004712 return compiler_error(c, "'async with' outside async function");
4713 }
Yury Selivanov75445082015-05-11 22:57:16 -04004714
4715 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004716 final = compiler_new_block(c);
4717 exit = compiler_new_block(c);
4718 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004719 return 0;
4720
4721 /* Evaluate EXPR */
4722 VISIT(c, expr, item->context_expr);
4723
4724 ADDOP(c, BEFORE_ASYNC_WITH);
4725 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004726 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004727 ADDOP(c, YIELD_FROM);
4728
Mark Shannonfee55262019-11-21 09:11:43 +00004729 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004730
4731 /* SETUP_ASYNC_WITH pushes a finally block. */
4732 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004733 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004734 return 0;
4735 }
4736
4737 if (item->optional_vars) {
4738 VISIT(c, expr, item->optional_vars);
4739 }
4740 else {
4741 /* Discard result from context.__aenter__() */
4742 ADDOP(c, POP_TOP);
4743 }
4744
4745 pos++;
4746 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4747 /* BLOCK code */
4748 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4749 else if (!compiler_async_with(c, s, pos))
4750 return 0;
4751
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004752 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004753 ADDOP(c, POP_BLOCK);
4754 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004755
Mark Shannonfee55262019-11-21 09:11:43 +00004756 /* For successful outcome:
4757 * call __exit__(None, None, None)
4758 */
4759 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004760 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004761 ADDOP(c, GET_AWAITABLE);
4762 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4763 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004764
Mark Shannonfee55262019-11-21 09:11:43 +00004765 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004766
Mark Shannonfee55262019-11-21 09:11:43 +00004767 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4768
4769 /* For exceptional outcome: */
4770 compiler_use_next_block(c, final);
4771
4772 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004773 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004774 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004775 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004776 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004777
Mark Shannonfee55262019-11-21 09:11:43 +00004778compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004779 return 1;
4780}
4781
4782
Guido van Rossumc2e20742006-02-27 22:32:47 +00004783/*
4784 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004785 with EXPR as VAR:
4786 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004787 is implemented as:
4788 <code for EXPR>
4789 SETUP_WITH E
4790 <code to store to VAR> or POP_TOP
4791 <code for BLOCK>
4792 LOAD_CONST (None, None, None)
4793 CALL_FUNCTION_EX 0
4794 JUMP_FORWARD EXIT
4795 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4796 POP_JUMP_IF_TRUE T:
4797 RERAISE
4798 T: POP_TOP * 3 (remove exception from stack)
4799 POP_EXCEPT
4800 POP_TOP
4801 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004802 */
Mark Shannonfee55262019-11-21 09:11:43 +00004803
Guido van Rossumc2e20742006-02-27 22:32:47 +00004804static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004805compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004806{
Mark Shannonfee55262019-11-21 09:11:43 +00004807 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004808 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004809
4810 assert(s->kind == With_kind);
4811
Guido van Rossumc2e20742006-02-27 22:32:47 +00004812 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004813 final = compiler_new_block(c);
4814 exit = compiler_new_block(c);
4815 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004817
Thomas Wouters477c8d52006-05-27 19:21:47 +00004818 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004819 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004820 /* Will push bound __exit__ */
4821 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004822
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004823 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004824 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004825 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004826 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004827 }
4828
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004829 if (item->optional_vars) {
4830 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004831 }
4832 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004834 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004835 }
4836
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004837 pos++;
4838 if (pos == asdl_seq_LEN(s->v.With.items))
4839 /* BLOCK code */
4840 VISIT_SEQ(c, stmt, s->v.With.body)
4841 else if (!compiler_with(c, s, pos))
4842 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004843
Guido van Rossumc2e20742006-02-27 22:32:47 +00004844 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004845 compiler_pop_fblock(c, WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004846
4847 /* End of body; start the cleanup. */
4848
4849 /* For successful outcome:
4850 * call __exit__(None, None, None)
4851 */
4852 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004853 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004854 ADDOP(c, POP_TOP);
4855 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004856
Mark Shannonfee55262019-11-21 09:11:43 +00004857 /* For exceptional outcome: */
4858 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004859
Mark Shannonfee55262019-11-21 09:11:43 +00004860 ADDOP(c, WITH_EXCEPT_START);
4861 compiler_with_except_finish(c);
4862
4863 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004864 return 1;
4865}
4866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004867static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004868compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004871 case NamedExpr_kind:
4872 VISIT(c, expr, e->v.NamedExpr.value);
4873 ADDOP(c, DUP_TOP);
4874 VISIT(c, expr, e->v.NamedExpr.target);
4875 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 case BoolOp_kind:
4877 return compiler_boolop(c, e);
4878 case BinOp_kind:
4879 VISIT(c, expr, e->v.BinOp.left);
4880 VISIT(c, expr, e->v.BinOp.right);
4881 ADDOP(c, binop(c, e->v.BinOp.op));
4882 break;
4883 case UnaryOp_kind:
4884 VISIT(c, expr, e->v.UnaryOp.operand);
4885 ADDOP(c, unaryop(e->v.UnaryOp.op));
4886 break;
4887 case Lambda_kind:
4888 return compiler_lambda(c, e);
4889 case IfExp_kind:
4890 return compiler_ifexp(c, e);
4891 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004892 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004894 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 case GeneratorExp_kind:
4896 return compiler_genexp(c, e);
4897 case ListComp_kind:
4898 return compiler_listcomp(c, e);
4899 case SetComp_kind:
4900 return compiler_setcomp(c, e);
4901 case DictComp_kind:
4902 return compiler_dictcomp(c, e);
4903 case Yield_kind:
4904 if (c->u->u_ste->ste_type != FunctionBlock)
4905 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004906 if (e->v.Yield.value) {
4907 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 }
4909 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004910 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004911 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004912 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004914 case YieldFrom_kind:
4915 if (c->u->u_ste->ste_type != FunctionBlock)
4916 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004917
4918 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4919 return compiler_error(c, "'yield from' inside async function");
4920
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004921 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004922 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004923 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004924 ADDOP(c, YIELD_FROM);
4925 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004926 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004927 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4928 if (c->u->u_ste->ste_type != FunctionBlock){
4929 return compiler_error(c, "'await' outside function");
4930 }
Yury Selivanov75445082015-05-11 22:57:16 -04004931
Victor Stinner331a6a52019-05-27 16:39:22 +02004932 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004933 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4934 return compiler_error(c, "'await' outside async function");
4935 }
4936 }
Yury Selivanov75445082015-05-11 22:57:16 -04004937
4938 VISIT(c, expr, e->v.Await.value);
4939 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004940 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004941 ADDOP(c, YIELD_FROM);
4942 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 case Compare_kind:
4944 return compiler_compare(c, e);
4945 case Call_kind:
4946 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004947 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004948 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004949 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004950 case JoinedStr_kind:
4951 return compiler_joined_str(c, e);
4952 case FormattedValue_kind:
4953 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 /* The following exprs can be assignment targets. */
4955 case Attribute_kind:
4956 if (e->v.Attribute.ctx != AugStore)
4957 VISIT(c, expr, e->v.Attribute.value);
4958 switch (e->v.Attribute.ctx) {
4959 case AugLoad:
4960 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004961 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 case Load:
4963 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4964 break;
4965 case AugStore:
4966 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004967 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 case Store:
4969 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4970 break;
4971 case Del:
4972 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4973 break;
4974 case Param:
4975 default:
4976 PyErr_SetString(PyExc_SystemError,
4977 "param invalid in attribute expression");
4978 return 0;
4979 }
4980 break;
4981 case Subscript_kind:
4982 switch (e->v.Subscript.ctx) {
4983 case AugLoad:
4984 VISIT(c, expr, e->v.Subscript.value);
4985 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4986 break;
4987 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004988 if (!check_subscripter(c, e->v.Subscript.value)) {
4989 return 0;
4990 }
4991 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4992 return 0;
4993 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 VISIT(c, expr, e->v.Subscript.value);
4995 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4996 break;
4997 case AugStore:
4998 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4999 break;
5000 case Store:
5001 VISIT(c, expr, e->v.Subscript.value);
5002 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5003 break;
5004 case Del:
5005 VISIT(c, expr, e->v.Subscript.value);
5006 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5007 break;
5008 case Param:
5009 default:
5010 PyErr_SetString(PyExc_SystemError,
5011 "param invalid in subscript expression");
5012 return 0;
5013 }
5014 break;
5015 case Starred_kind:
5016 switch (e->v.Starred.ctx) {
5017 case Store:
5018 /* In all legitimate cases, the Starred node was already replaced
5019 * by compiler_list/compiler_tuple. XXX: is that okay? */
5020 return compiler_error(c,
5021 "starred assignment target must be in a list or tuple");
5022 default:
5023 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005024 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 case Name_kind:
5027 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5028 /* child nodes of List and Tuple will have expr_context set */
5029 case List_kind:
5030 return compiler_list(c, e);
5031 case Tuple_kind:
5032 return compiler_tuple(c, e);
5033 }
5034 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005035}
5036
5037static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005038compiler_visit_expr(struct compiler *c, expr_ty e)
5039{
5040 /* If expr e has a different line number than the last expr/stmt,
5041 set a new line number for the next instruction.
5042 */
5043 int old_lineno = c->u->u_lineno;
5044 int old_col_offset = c->u->u_col_offset;
5045 if (e->lineno != c->u->u_lineno) {
5046 c->u->u_lineno = e->lineno;
5047 c->u->u_lineno_set = 0;
5048 }
5049 /* Updating the column offset is always harmless. */
5050 c->u->u_col_offset = e->col_offset;
5051
5052 int res = compiler_visit_expr1(c, e);
5053
5054 if (old_lineno != c->u->u_lineno) {
5055 c->u->u_lineno = old_lineno;
5056 c->u->u_lineno_set = 0;
5057 }
5058 c->u->u_col_offset = old_col_offset;
5059 return res;
5060}
5061
5062static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005063compiler_augassign(struct compiler *c, stmt_ty s)
5064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 expr_ty e = s->v.AugAssign.target;
5066 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 switch (e->kind) {
5071 case Attribute_kind:
5072 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005073 AugLoad, e->lineno, e->col_offset,
5074 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 if (auge == NULL)
5076 return 0;
5077 VISIT(c, expr, auge);
5078 VISIT(c, expr, s->v.AugAssign.value);
5079 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5080 auge->v.Attribute.ctx = AugStore;
5081 VISIT(c, expr, auge);
5082 break;
5083 case Subscript_kind:
5084 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005085 AugLoad, e->lineno, e->col_offset,
5086 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 if (auge == NULL)
5088 return 0;
5089 VISIT(c, expr, auge);
5090 VISIT(c, expr, s->v.AugAssign.value);
5091 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5092 auge->v.Subscript.ctx = AugStore;
5093 VISIT(c, expr, auge);
5094 break;
5095 case Name_kind:
5096 if (!compiler_nameop(c, e->v.Name.id, Load))
5097 return 0;
5098 VISIT(c, expr, s->v.AugAssign.value);
5099 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5100 return compiler_nameop(c, e->v.Name.id, Store);
5101 default:
5102 PyErr_Format(PyExc_SystemError,
5103 "invalid node type (%d) for augmented assignment",
5104 e->kind);
5105 return 0;
5106 }
5107 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005108}
5109
5110static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005111check_ann_expr(struct compiler *c, expr_ty e)
5112{
5113 VISIT(c, expr, e);
5114 ADDOP(c, POP_TOP);
5115 return 1;
5116}
5117
5118static int
5119check_annotation(struct compiler *c, stmt_ty s)
5120{
5121 /* Annotations are only evaluated in a module or class. */
5122 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5123 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5124 return check_ann_expr(c, s->v.AnnAssign.annotation);
5125 }
5126 return 1;
5127}
5128
5129static int
5130check_ann_slice(struct compiler *c, slice_ty sl)
5131{
5132 switch(sl->kind) {
5133 case Index_kind:
5134 return check_ann_expr(c, sl->v.Index.value);
5135 case Slice_kind:
5136 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5137 return 0;
5138 }
5139 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5140 return 0;
5141 }
5142 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5143 return 0;
5144 }
5145 break;
5146 default:
5147 PyErr_SetString(PyExc_SystemError,
5148 "unexpected slice kind");
5149 return 0;
5150 }
5151 return 1;
5152}
5153
5154static int
5155check_ann_subscr(struct compiler *c, slice_ty sl)
5156{
5157 /* We check that everything in a subscript is defined at runtime. */
5158 Py_ssize_t i, n;
5159
5160 switch (sl->kind) {
5161 case Index_kind:
5162 case Slice_kind:
5163 if (!check_ann_slice(c, sl)) {
5164 return 0;
5165 }
5166 break;
5167 case ExtSlice_kind:
5168 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5169 for (i = 0; i < n; i++) {
5170 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5171 switch (subsl->kind) {
5172 case Index_kind:
5173 case Slice_kind:
5174 if (!check_ann_slice(c, subsl)) {
5175 return 0;
5176 }
5177 break;
5178 case ExtSlice_kind:
5179 default:
5180 PyErr_SetString(PyExc_SystemError,
5181 "extended slice invalid in nested slice");
5182 return 0;
5183 }
5184 }
5185 break;
5186 default:
5187 PyErr_Format(PyExc_SystemError,
5188 "invalid subscript kind %d", sl->kind);
5189 return 0;
5190 }
5191 return 1;
5192}
5193
5194static int
5195compiler_annassign(struct compiler *c, stmt_ty s)
5196{
5197 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005198 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005199
5200 assert(s->kind == AnnAssign_kind);
5201
5202 /* We perform the actual assignment first. */
5203 if (s->v.AnnAssign.value) {
5204 VISIT(c, expr, s->v.AnnAssign.value);
5205 VISIT(c, expr, targ);
5206 }
5207 switch (targ->kind) {
5208 case Name_kind:
5209 /* If we have a simple name in a module or class, store annotation. */
5210 if (s->v.AnnAssign.simple &&
5211 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5212 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005213 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5214 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5215 }
5216 else {
5217 VISIT(c, expr, s->v.AnnAssign.annotation);
5218 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005219 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005220 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005221 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005222 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005223 }
5224 break;
5225 case Attribute_kind:
5226 if (!s->v.AnnAssign.value &&
5227 !check_ann_expr(c, targ->v.Attribute.value)) {
5228 return 0;
5229 }
5230 break;
5231 case Subscript_kind:
5232 if (!s->v.AnnAssign.value &&
5233 (!check_ann_expr(c, targ->v.Subscript.value) ||
5234 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5235 return 0;
5236 }
5237 break;
5238 default:
5239 PyErr_Format(PyExc_SystemError,
5240 "invalid node type (%d) for annotated assignment",
5241 targ->kind);
5242 return 0;
5243 }
5244 /* Annotation is evaluated last. */
5245 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5246 return 0;
5247 }
5248 return 1;
5249}
5250
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005251/* Raises a SyntaxError and returns 0.
5252 If something goes wrong, a different exception may be raised.
5253*/
5254
5255static int
5256compiler_error(struct compiler *c, const char *errstr)
5257{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005258 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005260
Victor Stinner14e461d2013-08-26 22:28:21 +02005261 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 if (!loc) {
5263 Py_INCREF(Py_None);
5264 loc = Py_None;
5265 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005266 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005267 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (!u)
5269 goto exit;
5270 v = Py_BuildValue("(zO)", errstr, u);
5271 if (!v)
5272 goto exit;
5273 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005274 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005275 Py_DECREF(loc);
5276 Py_XDECREF(u);
5277 Py_XDECREF(v);
5278 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279}
5280
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005281/* Emits a SyntaxWarning and returns 1 on success.
5282 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5283 and returns 0.
5284*/
5285static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005286compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005287{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005288 va_list vargs;
5289#ifdef HAVE_STDARG_PROTOTYPES
5290 va_start(vargs, format);
5291#else
5292 va_start(vargs);
5293#endif
5294 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5295 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005296 if (msg == NULL) {
5297 return 0;
5298 }
5299 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5300 c->u->u_lineno, NULL, NULL) < 0)
5301 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005302 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005303 /* Replace the SyntaxWarning exception with a SyntaxError
5304 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005305 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005306 assert(PyUnicode_AsUTF8(msg) != NULL);
5307 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005308 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005309 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005310 return 0;
5311 }
5312 Py_DECREF(msg);
5313 return 1;
5314}
5315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005316static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317compiler_handle_subscr(struct compiler *c, const char *kind,
5318 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 /* XXX this code is duplicated */
5323 switch (ctx) {
5324 case AugLoad: /* fall through to Load */
5325 case Load: op = BINARY_SUBSCR; break;
5326 case AugStore:/* fall through to Store */
5327 case Store: op = STORE_SUBSCR; break;
5328 case Del: op = DELETE_SUBSCR; break;
5329 case Param:
5330 PyErr_Format(PyExc_SystemError,
5331 "invalid %s kind %d in subscript\n",
5332 kind, ctx);
5333 return 0;
5334 }
5335 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005336 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 }
5338 else if (ctx == AugStore) {
5339 ADDOP(c, ROT_THREE);
5340 }
5341 ADDOP(c, op);
5342 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005343}
5344
5345static int
5346compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 int n = 2;
5349 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 /* only handles the cases where BUILD_SLICE is emitted */
5352 if (s->v.Slice.lower) {
5353 VISIT(c, expr, s->v.Slice.lower);
5354 }
5355 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005356 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 if (s->v.Slice.upper) {
5360 VISIT(c, expr, s->v.Slice.upper);
5361 }
5362 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005363 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 }
5365
5366 if (s->v.Slice.step) {
5367 n++;
5368 VISIT(c, expr, s->v.Slice.step);
5369 }
5370 ADDOP_I(c, BUILD_SLICE, n);
5371 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372}
5373
5374static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5376 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 switch (s->kind) {
5379 case Slice_kind:
5380 return compiler_slice(c, s, ctx);
5381 case Index_kind:
5382 VISIT(c, expr, s->v.Index.value);
5383 break;
5384 case ExtSlice_kind:
5385 default:
5386 PyErr_SetString(PyExc_SystemError,
5387 "extended slice invalid in nested slice");
5388 return 0;
5389 }
5390 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005391}
5392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005393static int
5394compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5395{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005396 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 switch (s->kind) {
5398 case Index_kind:
5399 kindname = "index";
5400 if (ctx != AugStore) {
5401 VISIT(c, expr, s->v.Index.value);
5402 }
5403 break;
5404 case Slice_kind:
5405 kindname = "slice";
5406 if (ctx != AugStore) {
5407 if (!compiler_slice(c, s, ctx))
5408 return 0;
5409 }
5410 break;
5411 case ExtSlice_kind:
5412 kindname = "extended slice";
5413 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005414 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 for (i = 0; i < n; i++) {
5416 slice_ty sub = (slice_ty)asdl_seq_GET(
5417 s->v.ExtSlice.dims, i);
5418 if (!compiler_visit_nested_slice(c, sub, ctx))
5419 return 0;
5420 }
5421 ADDOP_I(c, BUILD_TUPLE, n);
5422 }
5423 break;
5424 default:
5425 PyErr_Format(PyExc_SystemError,
5426 "invalid subscript kind %d", s->kind);
5427 return 0;
5428 }
5429 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430}
5431
Thomas Wouters89f507f2006-12-13 04:49:30 +00005432/* End of the compiler section, beginning of the assembler section */
5433
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005434/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005435 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005436
5437 XXX must handle implicit jumps from one block to next
5438*/
5439
Thomas Wouters89f507f2006-12-13 04:49:30 +00005440struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 PyObject *a_bytecode; /* string containing bytecode */
5442 int a_offset; /* offset into bytecode */
5443 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005444 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 PyObject *a_lnotab; /* string containing lnotab */
5446 int a_lnotab_off; /* offset into lnotab */
5447 int a_lineno; /* last lineno of emitted instruction */
5448 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005449};
5450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451static void
T. Wouters99b54d62019-09-12 07:05:33 -07005452dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453{
T. Wouters99b54d62019-09-12 07:05:33 -07005454 int i, j;
5455
5456 /* Get rid of recursion for normal control flow.
5457 Since the number of blocks is limited, unused space in a_postorder
5458 (from a_nblocks to end) can be used as a stack for still not ordered
5459 blocks. */
5460 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005461 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005462 assert(a->a_nblocks < j);
5463 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 }
T. Wouters99b54d62019-09-12 07:05:33 -07005465 while (j < end) {
5466 b = a->a_postorder[j++];
5467 for (i = 0; i < b->b_iused; i++) {
5468 struct instr *instr = &b->b_instr[i];
5469 if (instr->i_jrel || instr->i_jabs)
5470 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005471 }
T. Wouters99b54d62019-09-12 07:05:33 -07005472 assert(a->a_nblocks < j);
5473 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005474 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475}
5476
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005477Py_LOCAL_INLINE(void)
5478stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005480 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005481 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005482 assert(b->b_startdepth < 0);
5483 b->b_startdepth = depth;
5484 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005485 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005486}
5487
5488/* Find the flow path that needs the largest stack. We assume that
5489 * cycles in the flow graph have no net effect on the stack depth.
5490 */
5491static int
5492stackdepth(struct compiler *c)
5493{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005494 basicblock *b, *entryblock = NULL;
5495 basicblock **stack, **sp;
5496 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 b->b_startdepth = INT_MIN;
5499 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005500 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 }
5502 if (!entryblock)
5503 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005504 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5505 if (!stack) {
5506 PyErr_NoMemory();
5507 return -1;
5508 }
5509
5510 sp = stack;
5511 stackdepth_push(&sp, entryblock, 0);
5512 while (sp != stack) {
5513 b = *--sp;
5514 int depth = b->b_startdepth;
5515 assert(depth >= 0);
5516 basicblock *next = b->b_next;
5517 for (int i = 0; i < b->b_iused; i++) {
5518 struct instr *instr = &b->b_instr[i];
5519 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5520 if (effect == PY_INVALID_STACK_EFFECT) {
5521 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5522 Py_FatalError("PyCompile_OpcodeStackEffect()");
5523 }
5524 int new_depth = depth + effect;
5525 if (new_depth > maxdepth) {
5526 maxdepth = new_depth;
5527 }
5528 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5529 if (instr->i_jrel || instr->i_jabs) {
5530 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5531 assert(effect != PY_INVALID_STACK_EFFECT);
5532 int target_depth = depth + effect;
5533 if (target_depth > maxdepth) {
5534 maxdepth = target_depth;
5535 }
5536 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005537 stackdepth_push(&sp, instr->i_target, target_depth);
5538 }
5539 depth = new_depth;
5540 if (instr->i_opcode == JUMP_ABSOLUTE ||
5541 instr->i_opcode == JUMP_FORWARD ||
5542 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005543 instr->i_opcode == RAISE_VARARGS ||
5544 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005545 {
5546 /* remaining code is dead */
5547 next = NULL;
5548 break;
5549 }
5550 }
5551 if (next != NULL) {
5552 stackdepth_push(&sp, next, depth);
5553 }
5554 }
5555 PyObject_Free(stack);
5556 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005557}
5558
5559static int
5560assemble_init(struct assembler *a, int nblocks, int firstlineno)
5561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 memset(a, 0, sizeof(struct assembler));
5563 a->a_lineno = firstlineno;
5564 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5565 if (!a->a_bytecode)
5566 return 0;
5567 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5568 if (!a->a_lnotab)
5569 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005570 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 PyErr_NoMemory();
5572 return 0;
5573 }
T. Wouters99b54d62019-09-12 07:05:33 -07005574 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005576 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 PyErr_NoMemory();
5578 return 0;
5579 }
5580 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005581}
5582
5583static void
5584assemble_free(struct assembler *a)
5585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 Py_XDECREF(a->a_bytecode);
5587 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005588 if (a->a_postorder)
5589 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005590}
5591
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005592static int
5593blocksize(basicblock *b)
5594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 int i;
5596 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005599 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005600 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005601}
5602
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005603/* Appends a pair to the end of the line number table, a_lnotab, representing
5604 the instruction's bytecode offset and line number. See
5605 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005606
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005607static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005608assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005611 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005613
Serhiy Storchakaab874002016-09-11 13:48:15 +03005614 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 if(d_bytecode == 0 && d_lineno == 0)
5620 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 if (d_bytecode > 255) {
5623 int j, nbytes, ncodes = d_bytecode / 255;
5624 nbytes = a->a_lnotab_off + 2 * ncodes;
5625 len = PyBytes_GET_SIZE(a->a_lnotab);
5626 if (nbytes >= len) {
5627 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5628 len = nbytes;
5629 else if (len <= INT_MAX / 2)
5630 len *= 2;
5631 else {
5632 PyErr_NoMemory();
5633 return 0;
5634 }
5635 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5636 return 0;
5637 }
5638 lnotab = (unsigned char *)
5639 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5640 for (j = 0; j < ncodes; j++) {
5641 *lnotab++ = 255;
5642 *lnotab++ = 0;
5643 }
5644 d_bytecode -= ncodes * 255;
5645 a->a_lnotab_off += ncodes * 2;
5646 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005647 assert(0 <= d_bytecode && d_bytecode <= 255);
5648
5649 if (d_lineno < -128 || 127 < d_lineno) {
5650 int j, nbytes, ncodes, k;
5651 if (d_lineno < 0) {
5652 k = -128;
5653 /* use division on positive numbers */
5654 ncodes = (-d_lineno) / 128;
5655 }
5656 else {
5657 k = 127;
5658 ncodes = d_lineno / 127;
5659 }
5660 d_lineno -= ncodes * k;
5661 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 nbytes = a->a_lnotab_off + 2 * ncodes;
5663 len = PyBytes_GET_SIZE(a->a_lnotab);
5664 if (nbytes >= len) {
5665 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5666 len = nbytes;
5667 else if (len <= INT_MAX / 2)
5668 len *= 2;
5669 else {
5670 PyErr_NoMemory();
5671 return 0;
5672 }
5673 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5674 return 0;
5675 }
5676 lnotab = (unsigned char *)
5677 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5678 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005679 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 d_bytecode = 0;
5681 for (j = 1; j < ncodes; j++) {
5682 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005683 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 a->a_lnotab_off += ncodes * 2;
5686 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005687 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 len = PyBytes_GET_SIZE(a->a_lnotab);
5690 if (a->a_lnotab_off + 2 >= len) {
5691 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5692 return 0;
5693 }
5694 lnotab = (unsigned char *)
5695 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 a->a_lnotab_off += 2;
5698 if (d_bytecode) {
5699 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005700 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 }
5702 else { /* First line of a block; def stmt, etc. */
5703 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005704 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 }
5706 a->a_lineno = i->i_lineno;
5707 a->a_lineno_off = a->a_offset;
5708 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005709}
5710
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005711/* assemble_emit()
5712 Extend the bytecode with a new instruction.
5713 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005714*/
5715
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005716static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005717assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005718{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005719 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005721 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005722
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005723 arg = i->i_oparg;
5724 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 if (i->i_lineno && !assemble_lnotab(a, i))
5726 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005727 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 if (len > PY_SSIZE_T_MAX / 2)
5729 return 0;
5730 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5731 return 0;
5732 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005733 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005735 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005737}
5738
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005739static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005740assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005743 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 /* Compute the size of each block and fixup jump args.
5747 Replace block pointer with position in bytecode. */
5748 do {
5749 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005750 for (i = a->a_nblocks - 1; i >= 0; i--) {
5751 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 bsize = blocksize(b);
5753 b->b_offset = totsize;
5754 totsize += bsize;
5755 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005756 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5758 bsize = b->b_offset;
5759 for (i = 0; i < b->b_iused; i++) {
5760 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005761 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 /* Relative jumps are computed relative to
5763 the instruction pointer after fetching
5764 the jump instruction.
5765 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005766 bsize += isize;
5767 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005769 if (instr->i_jrel) {
5770 instr->i_oparg -= bsize;
5771 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005772 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005773 if (instrsize(instr->i_oparg) != isize) {
5774 extended_arg_recompile = 1;
5775 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 }
5778 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 /* XXX: This is an awful hack that could hurt performance, but
5781 on the bright side it should work until we come up
5782 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005784 The issue is that in the first loop blocksize() is called
5785 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005786 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 So we loop until we stop seeing new EXTENDED_ARGs.
5790 The only EXTENDED_ARGs that could be popping up are
5791 ones in jump instructions. So this should converge
5792 fairly quickly.
5793 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005794 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005795}
5796
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005797static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005798dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005801 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 tuple = PyTuple_New(size);
5804 if (tuple == NULL)
5805 return NULL;
5806 while (PyDict_Next(dict, &pos, &k, &v)) {
5807 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005808 Py_INCREF(k);
5809 assert((i - offset) < size);
5810 assert((i - offset) >= 0);
5811 PyTuple_SET_ITEM(tuple, i - offset, k);
5812 }
5813 return tuple;
5814}
5815
5816static PyObject *
5817consts_dict_keys_inorder(PyObject *dict)
5818{
5819 PyObject *consts, *k, *v;
5820 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5821
5822 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5823 if (consts == NULL)
5824 return NULL;
5825 while (PyDict_Next(dict, &pos, &k, &v)) {
5826 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005827 /* The keys of the dictionary can be tuples wrapping a contant.
5828 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5829 * the object we want is always second. */
5830 if (PyTuple_CheckExact(k)) {
5831 k = PyTuple_GET_ITEM(k, 1);
5832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005834 assert(i < size);
5835 assert(i >= 0);
5836 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005838 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005839}
5840
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005841static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005842compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005845 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005847 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 if (ste->ste_nested)
5849 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005850 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005852 if (!ste->ste_generator && ste->ste_coroutine)
5853 flags |= CO_COROUTINE;
5854 if (ste->ste_generator && ste->ste_coroutine)
5855 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 if (ste->ste_varargs)
5857 flags |= CO_VARARGS;
5858 if (ste->ste_varkeywords)
5859 flags |= CO_VARKEYWORDS;
5860 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 /* (Only) inherit compilerflags in PyCF_MASK */
5863 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005864
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005865 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5866 ste->ste_coroutine &&
5867 !ste->ste_generator) {
5868 flags |= CO_COROUTINE;
5869 }
5870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005872}
5873
INADA Naokic2e16072018-11-26 21:23:22 +09005874// Merge *tuple* with constant cache.
5875// Unlike merge_consts_recursive(), this function doesn't work recursively.
5876static int
5877merge_const_tuple(struct compiler *c, PyObject **tuple)
5878{
5879 assert(PyTuple_CheckExact(*tuple));
5880
5881 PyObject *key = _PyCode_ConstantKey(*tuple);
5882 if (key == NULL) {
5883 return 0;
5884 }
5885
5886 // t is borrowed reference
5887 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5888 Py_DECREF(key);
5889 if (t == NULL) {
5890 return 0;
5891 }
5892 if (t == key) { // tuple is new constant.
5893 return 1;
5894 }
5895
5896 PyObject *u = PyTuple_GET_ITEM(t, 1);
5897 Py_INCREF(u);
5898 Py_DECREF(*tuple);
5899 *tuple = u;
5900 return 1;
5901}
5902
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005903static PyCodeObject *
5904makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 PyObject *tmp;
5907 PyCodeObject *co = NULL;
5908 PyObject *consts = NULL;
5909 PyObject *names = NULL;
5910 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911 PyObject *name = NULL;
5912 PyObject *freevars = NULL;
5913 PyObject *cellvars = NULL;
5914 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005915 Py_ssize_t nlocals;
5916 int nlocals_int;
5917 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005918 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005919
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005920 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 names = dict_keys_inorder(c->u->u_names, 0);
5922 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5923 if (!consts || !names || !varnames)
5924 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5927 if (!cellvars)
5928 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005929 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 if (!freevars)
5931 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005932
INADA Naokic2e16072018-11-26 21:23:22 +09005933 if (!merge_const_tuple(c, &names) ||
5934 !merge_const_tuple(c, &varnames) ||
5935 !merge_const_tuple(c, &cellvars) ||
5936 !merge_const_tuple(c, &freevars))
5937 {
5938 goto error;
5939 }
5940
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005941 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005942 assert(nlocals < INT_MAX);
5943 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 flags = compute_code_flags(c);
5946 if (flags < 0)
5947 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5950 if (!bytecode)
5951 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5954 if (!tmp)
5955 goto error;
5956 Py_DECREF(consts);
5957 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005958 if (!merge_const_tuple(c, &consts)) {
5959 goto error;
5960 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005961
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005962 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005963 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005964 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005965 maxdepth = stackdepth(c);
5966 if (maxdepth < 0) {
5967 goto error;
5968 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005969 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5970 posonlyargcount, kwonlyargcount, nlocals_int,
5971 maxdepth, flags, bytecode, consts, names,
5972 varnames, freevars, cellvars, c->c_filename,
5973 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005974 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 Py_XDECREF(consts);
5976 Py_XDECREF(names);
5977 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 Py_XDECREF(name);
5979 Py_XDECREF(freevars);
5980 Py_XDECREF(cellvars);
5981 Py_XDECREF(bytecode);
5982 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005983}
5984
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005985
5986/* For debugging purposes only */
5987#if 0
5988static void
5989dump_instr(const struct instr *i)
5990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005991 const char *jrel = i->i_jrel ? "jrel " : "";
5992 const char *jabs = i->i_jabs ? "jabs " : "";
5993 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005996 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005998 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6000 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006001}
6002
6003static void
6004dump_basicblock(const basicblock *b)
6005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 const char *seen = b->b_seen ? "seen " : "";
6007 const char *b_return = b->b_return ? "return " : "";
6008 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6009 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6010 if (b->b_instr) {
6011 int i;
6012 for (i = 0; i < b->b_iused; i++) {
6013 fprintf(stderr, " [%02d] ", i);
6014 dump_instr(b->b_instr + i);
6015 }
6016 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006017}
6018#endif
6019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006020static PyCodeObject *
6021assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 basicblock *b, *entryblock;
6024 struct assembler a;
6025 int i, j, nblocks;
6026 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 /* Make sure every block that falls off the end returns None.
6029 XXX NEXT_BLOCK() isn't quite right, because if the last
6030 block ends with a jump or return b_next shouldn't set.
6031 */
6032 if (!c->u->u_curblock->b_return) {
6033 NEXT_BLOCK(c);
6034 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006035 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006036 ADDOP(c, RETURN_VALUE);
6037 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006039 nblocks = 0;
6040 entryblock = NULL;
6041 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6042 nblocks++;
6043 entryblock = b;
6044 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006046 /* Set firstlineno if it wasn't explicitly set. */
6047 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006048 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6050 else
6051 c->u->u_firstlineno = 1;
6052 }
6053 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6054 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006055 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006057 /* Can't modify the bytecode after computing jump offsets. */
6058 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006059
T. Wouters99b54d62019-09-12 07:05:33 -07006060 /* Emit code in reverse postorder from dfs. */
6061 for (i = a.a_nblocks - 1; i >= 0; i--) {
6062 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 for (j = 0; j < b->b_iused; j++)
6064 if (!assemble_emit(&a, &b->b_instr[j]))
6065 goto error;
6066 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006068 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6069 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006070 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006071 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006073 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006074 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 assemble_free(&a);
6076 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006077}
Georg Brandl8334fd92010-12-04 10:26:46 +00006078
6079#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006080PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006081PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6082 PyArena *arena)
6083{
6084 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6085}