blob: 04b8fe46e194d5d6474f59f570c566d549b8d62d [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800200static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200201static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500203static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400204static int compiler_async_with(struct compiler *, stmt_ty, int);
205static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100206static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400208 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500209static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400210static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700212static int compiler_sync_comprehension_generator(
213 struct compiler *c,
214 asdl_seq *generators, int gen_index,
215 expr_ty elt, expr_ty val, int type);
216
217static int compiler_async_comprehension_generator(
218 struct compiler *c,
219 asdl_seq *generators, int gen_index,
220 expr_ty elt, expr_ty val, int type);
221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000223static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400225#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* Name mangling: __private becomes _classname__private.
231 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 PyObject *result;
233 size_t nlen, plen, ipriv;
234 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 PyUnicode_READ_CHAR(ident, 0) != '_' ||
237 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident;
240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 nlen = PyUnicode_GET_LENGTH(ident);
242 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 The only time a name with a dot can occur is when
246 we are compiling an import statement that has a
247 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 TODO(jhylton): Decide whether we want to support
250 mangling of the module name, e.g. __M.X.
251 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
253 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
254 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_INCREF(ident);
256 return ident; /* Don't mangle __whatever__ */
257 }
258 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 ipriv = 0;
260 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
261 ipriv++;
262 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_INCREF(ident);
264 return ident; /* Don't mangle if class is just underscores */
265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000267
Antoine Pitrou55bff892013-04-06 21:21:04 +0200268 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
269 PyErr_SetString(PyExc_OverflowError,
270 "private identifier too large to be mangled");
271 return NULL;
272 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
275 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
276 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
277
278 result = PyUnicode_New(1 + nlen + plen, maxchar);
279 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
282 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200283 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
284 Py_DECREF(result);
285 return NULL;
286 }
287 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
288 Py_DECREF(result);
289 return NULL;
290 }
Victor Stinner8f825062012-04-27 13:55:39 +0200291 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000293}
294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295static int
296compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299
INADA Naokic2e16072018-11-26 21:23:22 +0900300 c->c_const_cache = PyDict_New();
301 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900303 }
304
305 c->c_stack = PyList_New(0);
306 if (!c->c_stack) {
307 Py_CLEAR(c->c_const_cache);
308 return 0;
309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312}
313
314PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200315PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
316 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 struct compiler c;
319 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200320 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200322 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!__doc__) {
325 __doc__ = PyUnicode_InternFromString("__doc__");
326 if (!__doc__)
327 return NULL;
328 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000329 if (!__annotations__) {
330 __annotations__ = PyUnicode_InternFromString("__annotations__");
331 if (!__annotations__)
332 return NULL;
333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!compiler_init(&c))
335 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 c.c_filename = filename;
338 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200339 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (c.c_future == NULL)
341 goto finally;
342 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 flags = &local_flags;
344 }
345 merged = c.c_future->ff_features | flags->cf_flags;
346 c.c_future->ff_features = merged;
347 flags->cf_flags = merged;
348 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200349 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100351 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200353 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900354 goto finally;
355 }
356
Victor Stinner14e461d2013-08-26 22:28:21 +0200357 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (c.c_st == NULL) {
359 if (!PyErr_Occurred())
360 PyErr_SetString(PyExc_SystemError, "no symtable");
361 goto finally;
362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Thomas Wouters1175c432006-02-27 22:49:54 +0000366 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 compiler_free(&c);
368 assert(co || PyErr_Occurred());
369 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370}
371
372PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200373PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
374 int optimize, PyArena *arena)
375{
376 PyObject *filename;
377 PyCodeObject *co;
378 filename = PyUnicode_DecodeFSDefault(filename_str);
379 if (filename == NULL)
380 return NULL;
381 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
382 Py_DECREF(filename);
383 return co;
384
385}
386
387PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388PyNode_Compile(struct _node *n, const char *filename)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyCodeObject *co = NULL;
391 mod_ty mod;
392 PyArena *arena = PyArena_New();
393 if (!arena)
394 return NULL;
395 mod = PyAST_FromNode(n, NULL, filename, arena);
396 if (mod)
397 co = PyAST_Compile(mod, filename, NULL, arena);
398 PyArena_Free(arena);
399 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000400}
401
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (c->c_st)
406 PySymtable_Free(c->c_st);
407 if (c->c_future)
408 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200409 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900410 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000412}
413
Guido van Rossum79f25d91997-04-29 20:08:16 +0000414static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_ssize_t i, n;
418 PyObject *v, *k;
419 PyObject *dict = PyDict_New();
420 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 n = PyList_Size(list);
423 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100424 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (!v) {
426 Py_DECREF(dict);
427 return NULL;
428 }
429 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300430 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(v);
432 Py_DECREF(dict);
433 return NULL;
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(v);
436 }
437 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438}
439
440/* Return new dict containing names from src that match scope(s).
441
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000442src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444values are integers, starting at offset and increasing by one for
445each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446*/
447
448static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100449dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700451 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500453 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 assert(offset >= 0);
456 if (dest == NULL)
457 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Meador Inge2ca63152012-07-18 14:20:11 -0500459 /* Sort the keys so that we have a deterministic order on the indexes
460 saved in the returned dictionary. These indexes are used as indexes
461 into the free and cell var storage. Therefore if they aren't
462 deterministic, then the generated bytecode is not deterministic.
463 */
464 sorted_keys = PyDict_Keys(src);
465 if (sorted_keys == NULL)
466 return NULL;
467 if (PyList_Sort(sorted_keys) != 0) {
468 Py_DECREF(sorted_keys);
469 return NULL;
470 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500471 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500472
473 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* XXX this should probably be a macro in symtable.h */
475 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500476 k = PyList_GET_ITEM(sorted_keys, key_i);
477 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 assert(PyLong_Check(v));
479 vi = PyLong_AS_LONG(v);
480 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300483 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_DECREF(dest);
487 return NULL;
488 }
489 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300490 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(item);
493 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
496 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
498 }
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000501}
502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503static void
504compiler_unit_check(struct compiler_unit *u)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 basicblock *block;
507 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700508 assert((uintptr_t)block != 0xcbcbcbcbU);
509 assert((uintptr_t)block != 0xfbfbfbfbU);
510 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (block->b_instr != NULL) {
512 assert(block->b_ialloc > 0);
513 assert(block->b_iused > 0);
514 assert(block->b_ialloc >= block->b_iused);
515 }
516 else {
517 assert (block->b_iused == 0);
518 assert (block->b_ialloc == 0);
519 }
520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521}
522
523static void
524compiler_unit_free(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 compiler_unit_check(u);
529 b = u->u_blocks;
530 while (b != NULL) {
531 if (b->b_instr)
532 PyObject_Free((void *)b->b_instr);
533 next = b->b_list;
534 PyObject_Free((void *)b);
535 b = next;
536 }
537 Py_CLEAR(u->u_ste);
538 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400539 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_CLEAR(u->u_consts);
541 Py_CLEAR(u->u_names);
542 Py_CLEAR(u->u_varnames);
543 Py_CLEAR(u->u_freevars);
544 Py_CLEAR(u->u_cellvars);
545 Py_CLEAR(u->u_private);
546 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547}
548
549static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100550compiler_enter_scope(struct compiler *c, identifier name,
551 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100554 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
557 struct compiler_unit));
558 if (!u) {
559 PyErr_NoMemory();
560 return 0;
561 }
562 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100563 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100565 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 u->u_kwonlyargcount = 0;
567 u->u_ste = PySymtable_Lookup(c->c_st, key);
568 if (!u->u_ste) {
569 compiler_unit_free(u);
570 return 0;
571 }
572 Py_INCREF(name);
573 u->u_name = name;
574 u->u_varnames = list2dict(u->u_ste->ste_varnames);
575 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
576 if (!u->u_varnames || !u->u_cellvars) {
577 compiler_unit_free(u);
578 return 0;
579 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000581 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300583 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 int res;
585 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200586 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 name = _PyUnicode_FromId(&PyId___class__);
588 if (!name) {
589 compiler_unit_free(u);
590 return 0;
591 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300592 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (res < 0) {
594 compiler_unit_free(u);
595 return 0;
596 }
597 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200600 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (!u->u_freevars) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_blocks = NULL;
607 u->u_nfblocks = 0;
608 u->u_firstlineno = lineno;
609 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000610 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_lineno_set = 0;
612 u->u_consts = PyDict_New();
613 if (!u->u_consts) {
614 compiler_unit_free(u);
615 return 0;
616 }
617 u->u_names = PyDict_New();
618 if (!u->u_names) {
619 compiler_unit_free(u);
620 return 0;
621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Push the old compiler_unit on the stack. */
626 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400627 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
629 Py_XDECREF(capsule);
630 compiler_unit_free(u);
631 return 0;
632 }
633 Py_DECREF(capsule);
634 u->u_private = c->u->u_private;
635 Py_XINCREF(u->u_private);
636 }
637 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100640
641 block = compiler_new_block(c);
642 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100644 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400646 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
647 if (!compiler_set_qualname(c))
648 return 0;
649 }
650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652}
653
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000654static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655compiler_exit_scope(struct compiler *c)
656{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100657 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 c->c_nestlevel--;
661 compiler_unit_free(c->u);
662 /* Restore c->u to the parent unit. */
663 n = PyList_GET_SIZE(c->c_stack) - 1;
664 if (n >= 0) {
665 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400666 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(c->u);
668 /* we are deleting from a list so this really shouldn't fail */
669 if (PySequence_DelItem(c->c_stack, n) < 0)
670 Py_FatalError("compiler_exit_scope()");
671 compiler_unit_check(c->u);
672 }
673 else
674 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678static int
679compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 _Py_static_string(dot_locals, ".<locals>");
683 Py_ssize_t stack_size;
684 struct compiler_unit *u = c->u;
685 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100686
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400689 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 if (stack_size > 1) {
691 int scope, force_global = 0;
692 struct compiler_unit *parent;
693 PyObject *mangled, *capsule;
694
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400695 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400696 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 assert(parent);
698
Yury Selivanov75445082015-05-11 22:57:16 -0400699 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
700 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
701 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 assert(u->u_name);
703 mangled = _Py_Mangle(parent->u_private, u->u_name);
704 if (!mangled)
705 return 0;
706 scope = PyST_GetScope(parent->u_ste, mangled);
707 Py_DECREF(mangled);
708 assert(scope != GLOBAL_IMPLICIT);
709 if (scope == GLOBAL_EXPLICIT)
710 force_global = 1;
711 }
712
713 if (!force_global) {
714 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400715 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400716 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
717 dot_locals_str = _PyUnicode_FromId(&dot_locals);
718 if (dot_locals_str == NULL)
719 return 0;
720 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
721 if (base == NULL)
722 return 0;
723 }
724 else {
725 Py_INCREF(parent->u_qualname);
726 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728 }
729 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 if (base != NULL) {
732 dot_str = _PyUnicode_FromId(&dot);
733 if (dot_str == NULL) {
734 Py_DECREF(base);
735 return 0;
736 }
737 name = PyUnicode_Concat(base, dot_str);
738 Py_DECREF(base);
739 if (name == NULL)
740 return 0;
741 PyUnicode_Append(&name, u->u_name);
742 if (name == NULL)
743 return 0;
744 }
745 else {
746 Py_INCREF(u->u_name);
747 name = u->u_name;
748 }
749 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100750
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400751 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100752}
753
Eric V. Smith235a6f02015-09-19 14:51:32 -0400754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755/* Allocate a new block and return a pointer to it.
756 Returns NULL on error.
757*/
758
759static basicblock *
760compiler_new_block(struct compiler *c)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 basicblock *b;
763 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 u = c->u;
766 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
767 if (b == NULL) {
768 PyErr_NoMemory();
769 return NULL;
770 }
771 memset((void *)b, 0, sizeof(basicblock));
772 /* Extend the singly linked list of blocks with new block. */
773 b->b_list = u->u_blocks;
774 u->u_blocks = b;
775 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779compiler_next_block(struct compiler *c)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 basicblock *block = compiler_new_block(c);
782 if (block == NULL)
783 return NULL;
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789static basicblock *
790compiler_use_next_block(struct compiler *c, basicblock *block)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(block != NULL);
793 c->u->u_curblock->b_next = block;
794 c->u->u_curblock = block;
795 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796}
797
798/* Returns the offset of the next instruction in the current block's
799 b_instr array. Resizes the b_instr as necessary.
800 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802
803static int
804compiler_next_instr(struct compiler *c, basicblock *b)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(b != NULL);
807 if (b->b_instr == NULL) {
808 b->b_instr = (struct instr *)PyObject_Malloc(
809 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
810 if (b->b_instr == NULL) {
811 PyErr_NoMemory();
812 return -1;
813 }
814 b->b_ialloc = DEFAULT_BLOCK_SIZE;
815 memset((char *)b->b_instr, 0,
816 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
817 }
818 else if (b->b_iused == b->b_ialloc) {
819 struct instr *tmp;
820 size_t oldsize, newsize;
821 oldsize = b->b_ialloc * sizeof(struct instr);
822 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000823
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700824 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_NoMemory();
826 return -1;
827 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (newsize == 0) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 b->b_ialloc <<= 1;
834 tmp = (struct instr *)PyObject_Realloc(
835 (void *)b->b_instr, newsize);
836 if (tmp == NULL) {
837 PyErr_NoMemory();
838 return -1;
839 }
840 b->b_instr = tmp;
841 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
842 }
843 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844}
845
Christian Heimes2202f872008-02-06 14:31:34 +0000846/* Set the i_lineno member of the instruction at offset off if the
847 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 already been set. If it has been set, the call has no effect.
849
Christian Heimes2202f872008-02-06 14:31:34 +0000850 The line number is reset in the following cases:
851 - when entering a new scope
852 - on each statement
853 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200854 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000855 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858static void
859compiler_set_lineno(struct compiler *c, int off)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 basicblock *b;
862 if (c->u->u_lineno_set)
863 return;
864 c->u->u_lineno_set = 1;
865 b = c->u->u_curblock;
866 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867}
868
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200869/* Return the stack effect of opcode with argument oparg.
870
871 Some opcodes have different stack effect when jump to the target and
872 when not jump. The 'jump' parameter specifies the case:
873
874 * 0 -- when not jump
875 * 1 -- when jump
876 * -1 -- maximal
877 */
878/* XXX Make the stack effect of WITH_CLEANUP_START and
879 WITH_CLEANUP_FINISH deterministic. */
880static int
881stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300884 case NOP:
885 case EXTENDED_ARG:
886 return 0;
887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case POP_TOP:
890 return -1;
891 case ROT_TWO:
892 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200893 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return 0;
895 case DUP_TOP:
896 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000897 case DUP_TOP_TWO:
898 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case UNARY_POSITIVE:
902 case UNARY_NEGATIVE:
903 case UNARY_NOT:
904 case UNARY_INVERT:
905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case SET_ADD:
908 case LIST_APPEND:
909 return -1;
910 case MAP_ADD:
911 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000912
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200913 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_POWER:
915 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400916 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_MODULO:
918 case BINARY_ADD:
919 case BINARY_SUBTRACT:
920 case BINARY_SUBSCR:
921 case BINARY_FLOOR_DIVIDE:
922 case BINARY_TRUE_DIVIDE:
923 return -1;
924 case INPLACE_FLOOR_DIVIDE:
925 case INPLACE_TRUE_DIVIDE:
926 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case INPLACE_ADD:
929 case INPLACE_SUBTRACT:
930 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400931 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case INPLACE_MODULO:
933 return -1;
934 case STORE_SUBSCR:
935 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case DELETE_SUBSCR:
937 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case BINARY_LSHIFT:
940 case BINARY_RSHIFT:
941 case BINARY_AND:
942 case BINARY_XOR:
943 case BINARY_OR:
944 return -1;
945 case INPLACE_POWER:
946 return -1;
947 case GET_ITER:
948 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case PRINT_EXPR:
951 return -1;
952 case LOAD_BUILD_CLASS:
953 return 1;
954 case INPLACE_LSHIFT:
955 case INPLACE_RSHIFT:
956 case INPLACE_AND:
957 case INPLACE_XOR:
958 case INPLACE_OR:
959 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* 1 in the normal flow.
963 * Restore the stack position and push 6 values before jumping to
964 * the handler if an exception be raised. */
965 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case RETURN_VALUE:
967 return -1;
968 case IMPORT_STAR:
969 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700970 case SETUP_ANNOTATIONS:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case YIELD_VALUE:
973 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500974 case YIELD_FROM:
975 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case POP_BLOCK:
977 return 0;
978 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_NAME:
982 return -1;
983 case DELETE_NAME:
984 return 0;
985 case UNPACK_SEQUENCE:
986 return oparg-1;
987 case UNPACK_EX:
988 return (oparg&0xFF) + (oparg>>8);
989 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200990 /* -1 at end of iterator, 1 if continue iterating. */
991 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case STORE_ATTR:
994 return -2;
995 case DELETE_ATTR:
996 return -1;
997 case STORE_GLOBAL:
998 return -1;
999 case DELETE_GLOBAL:
1000 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CONST:
1002 return 1;
1003 case LOAD_NAME:
1004 return 1;
1005 case BUILD_TUPLE:
1006 case BUILD_LIST:
1007 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001008 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 1-oparg;
1010 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001011 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001012 case BUILD_CONST_KEY_MAP:
1013 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case LOAD_ATTR:
1015 return 0;
1016 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001017 case IS_OP:
1018 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001020 case JUMP_IF_NOT_EXC_MATCH:
1021 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case IMPORT_NAME:
1023 return -1;
1024 case IMPORT_FROM:
1025 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001027 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case JUMP_ABSOLUTE:
1030 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 case JUMP_IF_TRUE_OR_POP:
1033 case JUMP_IF_FALSE_OR_POP:
1034 return jump ? 0 : -1;
1035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case POP_JUMP_IF_FALSE:
1037 case POP_JUMP_IF_TRUE:
1038 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case LOAD_GLOBAL:
1041 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001042
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001043 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001045 /* 0 in the normal flow.
1046 * Restore the stack position and push 6 values before jumping to
1047 * the handler if an exception be raised. */
1048 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001049 case RERAISE:
1050 return -3;
1051
1052 case WITH_EXCEPT_START:
1053 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case LOAD_FAST:
1056 return 1;
1057 case STORE_FAST:
1058 return -1;
1059 case DELETE_FAST:
1060 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 case RAISE_VARARGS:
1063 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001064
1065 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001067 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001068 case CALL_METHOD:
1069 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001071 return -oparg-1;
1072 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001073 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001074 case MAKE_FUNCTION:
1075 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1076 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 case BUILD_SLICE:
1078 if (oparg == 3)
1079 return -2;
1080 else
1081 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001083 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 case LOAD_CLOSURE:
1085 return 1;
1086 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001087 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 return 1;
1089 case STORE_DEREF:
1090 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001091 case DELETE_DEREF:
1092 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001093
1094 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001095 case GET_AWAITABLE:
1096 return 0;
1097 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098 /* 0 in the normal flow.
1099 * Restore the stack position to the position before the result
1100 * of __aenter__ and push 6 values before jumping to the handler
1101 * if an exception be raised. */
1102 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001103 case BEFORE_ASYNC_WITH:
1104 return 1;
1105 case GET_AITER:
1106 return 0;
1107 case GET_ANEXT:
1108 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001109 case GET_YIELD_FROM_ITER:
1110 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001111 case END_ASYNC_FOR:
1112 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001113 case FORMAT_VALUE:
1114 /* If there's a fmt_spec on the stack, we go from 2->1,
1115 else 1->1. */
1116 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001117 case LOAD_METHOD:
1118 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001119 case LOAD_ASSERTION_ERROR:
1120 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001121 case LIST_TO_TUPLE:
1122 return 0;
1123 case LIST_EXTEND:
1124 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001125 case DICT_MERGE:
1126 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001127 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001129 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Larry Hastings3a907972013-11-23 14:49:22 -08001131 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132}
1133
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001134int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001135PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1136{
1137 return stack_effect(opcode, oparg, jump);
1138}
1139
1140int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001141PyCompile_OpcodeStackEffect(int opcode, int oparg)
1142{
1143 return stack_effect(opcode, oparg, -1);
1144}
1145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146/* Add an opcode with no argument.
1147 Returns 0 on failure, 1 on success.
1148*/
1149
1150static int
1151compiler_addop(struct compiler *c, int opcode)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 basicblock *b;
1154 struct instr *i;
1155 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001156 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001157 if (c->c_do_not_emit_bytecode) {
1158 return 1;
1159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 off = compiler_next_instr(c, c->u->u_curblock);
1161 if (off < 0)
1162 return 0;
1163 b = c->u->u_curblock;
1164 i = &b->b_instr[off];
1165 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001166 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (opcode == RETURN_VALUE)
1168 b->b_return = 1;
1169 compiler_set_lineno(c, off);
1170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171}
1172
Victor Stinnerf8e32212013-11-19 23:56:34 +01001173static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1175{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001176 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001179 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001181 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001183 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001184 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001185 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return -1;
1188 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001189 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 Py_DECREF(v);
1191 return -1;
1192 }
1193 Py_DECREF(v);
1194 }
1195 else
1196 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001197 return arg;
1198}
1199
INADA Naokic2e16072018-11-26 21:23:22 +09001200// Merge const *o* recursively and return constant key object.
1201static PyObject*
1202merge_consts_recursive(struct compiler *c, PyObject *o)
1203{
1204 // None and Ellipsis are singleton, and key is the singleton.
1205 // No need to merge object and key.
1206 if (o == Py_None || o == Py_Ellipsis) {
1207 Py_INCREF(o);
1208 return o;
1209 }
1210
1211 PyObject *key = _PyCode_ConstantKey(o);
1212 if (key == NULL) {
1213 return NULL;
1214 }
1215
1216 // t is borrowed reference
1217 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1218 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001219 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001220 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001221 Py_DECREF(key);
1222 return t;
1223 }
1224
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001226 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001227 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001228 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 Py_ssize_t len = PyTuple_GET_SIZE(o);
1230 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001231 PyObject *item = PyTuple_GET_ITEM(o, i);
1232 PyObject *u = merge_consts_recursive(c, item);
1233 if (u == NULL) {
1234 Py_DECREF(key);
1235 return NULL;
1236 }
1237
1238 // See _PyCode_ConstantKey()
1239 PyObject *v; // borrowed
1240 if (PyTuple_CheckExact(u)) {
1241 v = PyTuple_GET_ITEM(u, 1);
1242 }
1243 else {
1244 v = u;
1245 }
1246 if (v != item) {
1247 Py_INCREF(v);
1248 PyTuple_SET_ITEM(o, i, v);
1249 Py_DECREF(item);
1250 }
1251
1252 Py_DECREF(u);
1253 }
1254 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001255 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001256 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001257 // constant keys.
1258 // See _PyCode_ConstantKey() for detail.
1259 assert(PyTuple_CheckExact(key));
1260 assert(PyTuple_GET_SIZE(key) == 2);
1261
1262 Py_ssize_t len = PySet_GET_SIZE(o);
1263 if (len == 0) { // empty frozenset should not be re-created.
1264 return key;
1265 }
1266 PyObject *tuple = PyTuple_New(len);
1267 if (tuple == NULL) {
1268 Py_DECREF(key);
1269 return NULL;
1270 }
1271 Py_ssize_t i = 0, pos = 0;
1272 PyObject *item;
1273 Py_hash_t hash;
1274 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1275 PyObject *k = merge_consts_recursive(c, item);
1276 if (k == NULL) {
1277 Py_DECREF(tuple);
1278 Py_DECREF(key);
1279 return NULL;
1280 }
1281 PyObject *u;
1282 if (PyTuple_CheckExact(k)) {
1283 u = PyTuple_GET_ITEM(k, 1);
1284 Py_INCREF(u);
1285 Py_DECREF(k);
1286 }
1287 else {
1288 u = k;
1289 }
1290 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1291 i++;
1292 }
1293
1294 // Instead of rewriting o, we create new frozenset and embed in the
1295 // key tuple. Caller should get merged frozenset from the key tuple.
1296 PyObject *new = PyFrozenSet_New(tuple);
1297 Py_DECREF(tuple);
1298 if (new == NULL) {
1299 Py_DECREF(key);
1300 return NULL;
1301 }
1302 assert(PyTuple_GET_ITEM(key, 1) == o);
1303 Py_DECREF(o);
1304 PyTuple_SET_ITEM(key, 1, new);
1305 }
INADA Naokic2e16072018-11-26 21:23:22 +09001306
1307 return key;
1308}
1309
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310static Py_ssize_t
1311compiler_add_const(struct compiler *c, PyObject *o)
1312{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001313 if (c->c_do_not_emit_bytecode) {
1314 return 0;
1315 }
1316
INADA Naokic2e16072018-11-26 21:23:22 +09001317 PyObject *key = merge_consts_recursive(c, o);
1318 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001319 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001320 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001321
INADA Naokic2e16072018-11-26 21:23:22 +09001322 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1323 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325}
1326
1327static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001328compiler_addop_load_const(struct compiler *c, PyObject *o)
1329{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001330 if (c->c_do_not_emit_bytecode) {
1331 return 1;
1332 }
1333
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001334 Py_ssize_t arg = compiler_add_const(c, o);
1335 if (arg < 0)
1336 return 0;
1337 return compiler_addop_i(c, LOAD_CONST, arg);
1338}
1339
1340static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001344 if (c->c_do_not_emit_bytecode) {
1345 return 1;
1346 }
1347
Victor Stinnerad9a0662013-11-19 22:23:20 +01001348 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001350 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351 return compiler_addop_i(c, opcode, arg);
1352}
1353
1354static int
1355compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001358 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001359
1360 if (c->c_do_not_emit_bytecode) {
1361 return 1;
1362 }
1363
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1365 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 arg = compiler_add_o(c, dict, mangled);
1368 Py_DECREF(mangled);
1369 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001370 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 return compiler_addop_i(c, opcode, arg);
1372}
1373
1374/* Add an opcode with an integer argument.
1375 Returns 0 on failure, 1 on success.
1376*/
1377
1378static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001379compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 struct instr *i;
1382 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001383
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001384 if (c->c_do_not_emit_bytecode) {
1385 return 1;
1386 }
1387
Victor Stinner2ad474b2016-03-01 23:34:47 +01001388 /* oparg value is unsigned, but a signed C int is usually used to store
1389 it in the C code (like Python/ceval.c).
1390
1391 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1392
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001393 The argument of a concrete bytecode instruction is limited to 8-bit.
1394 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1395 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001396 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 off = compiler_next_instr(c, c->u->u_curblock);
1399 if (off < 0)
1400 return 0;
1401 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001402 i->i_opcode = opcode;
1403 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 compiler_set_lineno(c, off);
1405 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406}
1407
1408static int
1409compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 struct instr *i;
1412 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001414 if (c->c_do_not_emit_bytecode) {
1415 return 1;
1416 }
1417
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001418 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 assert(b != NULL);
1420 off = compiler_next_instr(c, c->u->u_curblock);
1421 if (off < 0)
1422 return 0;
1423 i = &c->u->u_curblock->b_instr[off];
1424 i->i_opcode = opcode;
1425 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (absolute)
1427 i->i_jabs = 1;
1428 else
1429 i->i_jrel = 1;
1430 compiler_set_lineno(c, off);
1431 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432}
1433
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001434/* NEXT_BLOCK() creates an implicit jump from the current block
1435 to the new block.
1436
1437 The returns inside this macro make it impossible to decref objects
1438 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (compiler_next_block((C)) == NULL) \
1442 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443}
1444
1445#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_addop((C), (OP))) \
1447 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448}
1449
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001450#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (!compiler_addop((C), (OP))) { \
1452 compiler_exit_scope(c); \
1453 return 0; \
1454 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001455}
1456
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001457#define ADDOP_LOAD_CONST(C, O) { \
1458 if (!compiler_addop_load_const((C), (O))) \
1459 return 0; \
1460}
1461
1462/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1463#define ADDOP_LOAD_CONST_NEW(C, O) { \
1464 PyObject *__new_const = (O); \
1465 if (__new_const == NULL) { \
1466 return 0; \
1467 } \
1468 if (!compiler_addop_load_const((C), __new_const)) { \
1469 Py_DECREF(__new_const); \
1470 return 0; \
1471 } \
1472 Py_DECREF(__new_const); \
1473}
1474
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1477 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478}
1479
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001480/* Same as ADDOP_O, but steals a reference. */
1481#define ADDOP_N(C, OP, O, TYPE) { \
1482 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1483 Py_DECREF((O)); \
1484 return 0; \
1485 } \
1486 Py_DECREF((O)); \
1487}
1488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1491 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492}
1493
1494#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 if (!compiler_addop_i((C), (OP), (O))) \
1496 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497}
1498
1499#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (!compiler_addop_j((C), (OP), (O), 1)) \
1501 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502}
1503
1504#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (!compiler_addop_j((C), (OP), (O), 0)) \
1506 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507}
1508
Mark Shannon9af0e472020-01-14 10:12:45 +00001509
1510#define ADDOP_COMPARE(C, CMP) { \
1511 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1512 return 0; \
1513}
1514
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1516 the ASDL name to synthesize the name of the C type and the visit function.
1517*/
1518
1519#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) \
1521 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522}
1523
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_visit_ ## TYPE((C), (V))) { \
1526 compiler_exit_scope(c); \
1527 return 0; \
1528 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001529}
1530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (!compiler_visit_slice((C), (V), (CTX))) \
1533 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
1536#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int _i; \
1538 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1539 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1540 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1541 if (!compiler_visit_ ## TYPE((C), elt)) \
1542 return 0; \
1543 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544}
1545
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 int _i; \
1548 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1549 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1550 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1551 if (!compiler_visit_ ## TYPE((C), elt)) { \
1552 compiler_exit_scope(c); \
1553 return 0; \
1554 } \
1555 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001556}
1557
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001558/* These macros allows to check only for errors and not emmit bytecode
1559 * while visiting nodes.
1560*/
1561
1562#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1563 c->c_do_not_emit_bytecode++;
1564
1565#define END_DO_NOT_EMIT_BYTECODE \
1566 c->c_do_not_emit_bytecode--; \
1567}
1568
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001569/* Search if variable annotations are present statically in a block. */
1570
1571static int
1572find_ann(asdl_seq *stmts)
1573{
1574 int i, j, res = 0;
1575 stmt_ty st;
1576
1577 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1578 st = (stmt_ty)asdl_seq_GET(stmts, i);
1579 switch (st->kind) {
1580 case AnnAssign_kind:
1581 return 1;
1582 case For_kind:
1583 res = find_ann(st->v.For.body) ||
1584 find_ann(st->v.For.orelse);
1585 break;
1586 case AsyncFor_kind:
1587 res = find_ann(st->v.AsyncFor.body) ||
1588 find_ann(st->v.AsyncFor.orelse);
1589 break;
1590 case While_kind:
1591 res = find_ann(st->v.While.body) ||
1592 find_ann(st->v.While.orelse);
1593 break;
1594 case If_kind:
1595 res = find_ann(st->v.If.body) ||
1596 find_ann(st->v.If.orelse);
1597 break;
1598 case With_kind:
1599 res = find_ann(st->v.With.body);
1600 break;
1601 case AsyncWith_kind:
1602 res = find_ann(st->v.AsyncWith.body);
1603 break;
1604 case Try_kind:
1605 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1606 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1607 st->v.Try.handlers, j);
1608 if (find_ann(handler->v.ExceptHandler.body)) {
1609 return 1;
1610 }
1611 }
1612 res = find_ann(st->v.Try.body) ||
1613 find_ann(st->v.Try.finalbody) ||
1614 find_ann(st->v.Try.orelse);
1615 break;
1616 default:
1617 res = 0;
1618 }
1619 if (res) {
1620 break;
1621 }
1622 }
1623 return res;
1624}
1625
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001626/*
1627 * Frame block handling functions
1628 */
1629
1630static int
1631compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001632 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001633{
1634 struct fblockinfo *f;
1635 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1636 PyErr_SetString(PyExc_SyntaxError,
1637 "too many statically nested blocks");
1638 return 0;
1639 }
1640 f = &c->u->u_fblock[c->u->u_nfblocks++];
1641 f->fb_type = t;
1642 f->fb_block = b;
1643 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001644 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001645 return 1;
1646}
1647
1648static void
1649compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1650{
1651 struct compiler_unit *u = c->u;
1652 assert(u->u_nfblocks > 0);
1653 u->u_nfblocks--;
1654 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1655 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1656}
1657
Mark Shannonfee55262019-11-21 09:11:43 +00001658static int
1659compiler_call_exit_with_nones(struct compiler *c) {
1660 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1661 ADDOP(c, DUP_TOP);
1662 ADDOP(c, DUP_TOP);
1663 ADDOP_I(c, CALL_FUNCTION, 3);
1664 return 1;
1665}
1666
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001667/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001668 * popping the blocks will be restored afterwards, unless another
1669 * return, break or continue is found. In which case, the TOS will
1670 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001671 */
1672static int
1673compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1674 int preserve_tos)
1675{
1676 switch (info->fb_type) {
1677 case WHILE_LOOP:
1678 return 1;
1679
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001680 case FOR_LOOP:
1681 /* Pop the iterator */
1682 if (preserve_tos) {
1683 ADDOP(c, ROT_TWO);
1684 }
1685 ADDOP(c, POP_TOP);
1686 return 1;
1687
1688 case EXCEPT:
1689 ADDOP(c, POP_BLOCK);
1690 return 1;
1691
1692 case FINALLY_TRY:
1693 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001694 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001695 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1696 return 0;
1697 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001698 }
Mark Shannon88dce262019-12-30 09:53:36 +00001699 /* Emit the finally block, restoring the line number when done */
1700 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001701 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001702 c->u->u_lineno = saved_lineno;
1703 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001704 if (preserve_tos) {
1705 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001706 }
1707 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001708
Mark Shannonfee55262019-11-21 09:11:43 +00001709 case FINALLY_END:
1710 if (preserve_tos) {
1711 ADDOP(c, ROT_FOUR);
1712 }
1713 ADDOP(c, POP_TOP);
1714 ADDOP(c, POP_TOP);
1715 ADDOP(c, POP_TOP);
1716 if (preserve_tos) {
1717 ADDOP(c, ROT_FOUR);
1718 }
1719 ADDOP(c, POP_EXCEPT);
1720 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001721
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001722 case WITH:
1723 case ASYNC_WITH:
1724 ADDOP(c, POP_BLOCK);
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_TWO);
1727 }
Mark Shannonfee55262019-11-21 09:11:43 +00001728 if(!compiler_call_exit_with_nones(c)) {
1729 return 0;
1730 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001731 if (info->fb_type == ASYNC_WITH) {
1732 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001733 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001734 ADDOP(c, YIELD_FROM);
1735 }
Mark Shannonfee55262019-11-21 09:11:43 +00001736 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 return 1;
1738
1739 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001740 if (info->fb_datum) {
1741 ADDOP(c, POP_BLOCK);
1742 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001743 if (preserve_tos) {
1744 ADDOP(c, ROT_FOUR);
1745 }
Mark Shannonfee55262019-11-21 09:11:43 +00001746 ADDOP(c, POP_EXCEPT);
1747 if (info->fb_datum) {
1748 ADDOP_LOAD_CONST(c, Py_None);
1749 compiler_nameop(c, info->fb_datum, Store);
1750 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001751 }
Mark Shannonfee55262019-11-21 09:11:43 +00001752 return 1;
1753
1754 case POP_VALUE:
1755 if (preserve_tos) {
1756 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001757 }
Mark Shannonfee55262019-11-21 09:11:43 +00001758 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001759 return 1;
1760 }
1761 Py_UNREACHABLE();
1762}
1763
Mark Shannonfee55262019-11-21 09:11:43 +00001764/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1765static int
1766compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1767 if (c->u->u_nfblocks == 0) {
1768 return 1;
1769 }
1770 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1771 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1772 *loop = top;
1773 return 1;
1774 }
1775 struct fblockinfo copy = *top;
1776 c->u->u_nfblocks--;
1777 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1778 return 0;
1779 }
1780 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1781 return 0;
1782 }
1783 c->u->u_fblock[c->u->u_nfblocks] = copy;
1784 c->u->u_nfblocks++;
1785 return 1;
1786}
1787
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001788/* Compile a sequence of statements, checking for a docstring
1789 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790
1791static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001792compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001794 int i = 0;
1795 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001796 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001797
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001798 /* Set current line number to the line number of first statement.
1799 This way line number for SETUP_ANNOTATIONS will always
1800 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301801 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001802 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1803 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001804 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001805 c->u->u_lineno = st->lineno;
1806 }
1807 /* Every annotated class and module should have __annotations__. */
1808 if (find_ann(stmts)) {
1809 ADDOP(c, SETUP_ANNOTATIONS);
1810 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001811 if (!asdl_seq_LEN(stmts))
1812 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001813 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001814 if (c->c_optimize < 2) {
1815 docstring = _PyAST_GetDocString(stmts);
1816 if (docstring) {
1817 i = 1;
1818 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1819 assert(st->kind == Expr_kind);
1820 VISIT(c, expr, st->v.Expr.value);
1821 if (!compiler_nameop(c, __doc__, Store))
1822 return 0;
1823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001825 for (; i < asdl_seq_LEN(stmts); i++)
1826 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828}
1829
1830static PyCodeObject *
1831compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyCodeObject *co;
1834 int addNone = 1;
1835 static PyObject *module;
1836 if (!module) {
1837 module = PyUnicode_InternFromString("<module>");
1838 if (!module)
1839 return NULL;
1840 }
1841 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001842 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return NULL;
1844 switch (mod->kind) {
1845 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001846 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 compiler_exit_scope(c);
1848 return 0;
1849 }
1850 break;
1851 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001852 if (find_ann(mod->v.Interactive.body)) {
1853 ADDOP(c, SETUP_ANNOTATIONS);
1854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 c->c_interactive = 1;
1856 VISIT_SEQ_IN_SCOPE(c, stmt,
1857 mod->v.Interactive.body);
1858 break;
1859 case Expression_kind:
1860 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1861 addNone = 0;
1862 break;
1863 case Suite_kind:
1864 PyErr_SetString(PyExc_SystemError,
1865 "suite should not be possible");
1866 return 0;
1867 default:
1868 PyErr_Format(PyExc_SystemError,
1869 "module kind %d should not be possible",
1870 mod->kind);
1871 return 0;
1872 }
1873 co = assemble(c, addNone);
1874 compiler_exit_scope(c);
1875 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001876}
1877
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878/* The test for LOCAL must come before the test for FREE in order to
1879 handle classes where name is both local and free. The local var is
1880 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001881*/
1882
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883static int
1884get_ref_type(struct compiler *c, PyObject *name)
1885{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001886 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001887 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001888 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001889 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001890 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (scope == 0) {
1892 char buf[350];
1893 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001894 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001896 PyUnicode_AsUTF8(name),
1897 PyUnicode_AsUTF8(c->u->u_name),
1898 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1899 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 );
1903 Py_FatalError(buf);
1904 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
1910compiler_lookup_arg(PyObject *dict, PyObject *name)
1911{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001912 PyObject *v;
1913 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001915 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001916 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917}
1918
1919static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001920compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001922 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001923 if (qualname == NULL)
1924 qualname = co->co_name;
1925
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001926 if (free) {
1927 for (i = 0; i < free; ++i) {
1928 /* Bypass com_addop_varname because it will generate
1929 LOAD_DEREF but LOAD_CLOSURE is needed.
1930 */
1931 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1932 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001934 /* Special case: If a class contains a method with a
1935 free variable that has the same name as a method,
1936 the name will be considered free *and* local in the
1937 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001938 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001939 */
1940 reftype = get_ref_type(c, name);
1941 if (reftype == CELL)
1942 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1943 else /* (reftype == FREE) */
1944 arg = compiler_lookup_arg(c->u->u_freevars, name);
1945 if (arg == -1) {
1946 fprintf(stderr,
1947 "lookup %s in %s %d %d\n"
1948 "freevars of %s: %s\n",
1949 PyUnicode_AsUTF8(PyObject_Repr(name)),
1950 PyUnicode_AsUTF8(c->u->u_name),
1951 reftype, arg,
1952 PyUnicode_AsUTF8(co->co_name),
1953 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1954 Py_FatalError("compiler_make_closure()");
1955 }
1956 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001958 flags |= 0x08;
1959 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001961 ADDOP_LOAD_CONST(c, (PyObject*)co);
1962 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001963 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965}
1966
1967static int
1968compiler_decorators(struct compiler *c, asdl_seq* decos)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 if (!decos)
1973 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1976 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1977 }
1978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979}
1980
1981static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001982compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001984{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001985 /* Push a dict of keyword-only default values.
1986
1987 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1988 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001989 int i;
1990 PyObject *keys = NULL;
1991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1993 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1994 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1995 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001996 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001997 if (!mangled) {
1998 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002000 if (keys == NULL) {
2001 keys = PyList_New(1);
2002 if (keys == NULL) {
2003 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002004 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 }
2006 PyList_SET_ITEM(keys, 0, mangled);
2007 }
2008 else {
2009 int res = PyList_Append(keys, mangled);
2010 Py_DECREF(mangled);
2011 if (res == -1) {
2012 goto error;
2013 }
2014 }
2015 if (!compiler_visit_expr(c, default_)) {
2016 goto error;
2017 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 }
2019 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 if (keys != NULL) {
2021 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2022 PyObject *keys_tuple = PyList_AsTuple(keys);
2023 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002024 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002025 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 assert(default_count > 0);
2027 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002028 }
2029 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002030 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002031 }
2032
2033error:
2034 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002036}
2037
2038static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002039compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2040{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002041 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002042 return 1;
2043}
2044
2045static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002046compiler_visit_argannotation(struct compiler *c, identifier id,
2047 expr_ty annotation, PyObject *names)
2048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002050 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002051 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2052 VISIT(c, annexpr, annotation)
2053 }
2054 else {
2055 VISIT(c, expr, annotation);
2056 }
Victor Stinner065efc32014-02-18 22:07:56 +01002057 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002058 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002059 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 if (PyList_Append(names, mangled) < 0) {
2061 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002062 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002063 }
2064 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002067}
2068
2069static int
2070compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2071 PyObject *names)
2072{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 for (i = 0; i < asdl_seq_LEN(args); i++) {
2075 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002076 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 c,
2078 arg->arg,
2079 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002080 names))
2081 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002083 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002084}
2085
2086static int
2087compiler_visit_annotations(struct compiler *c, arguments_ty args,
2088 expr_ty returns)
2089{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002090 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002091 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002092
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002093 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 */
2095 static identifier return_str;
2096 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002097 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 names = PyList_New(0);
2099 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002100 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002101
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002102 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002104 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2105 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002106 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002107 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002108 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002110 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002112 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002113 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002114 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (!return_str) {
2118 return_str = PyUnicode_InternFromString("return");
2119 if (!return_str)
2120 goto error;
2121 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002122 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 goto error;
2124 }
2125
2126 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002128 PyObject *keytuple = PyList_AsTuple(names);
2129 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002130 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002131 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002132 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002134 else {
2135 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002136 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002137 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002138
2139error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002141 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002142}
2143
2144static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002145compiler_visit_defaults(struct compiler *c, arguments_ty args)
2146{
2147 VISIT_SEQ(c, expr, args->defaults);
2148 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150}
2151
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002152static Py_ssize_t
2153compiler_default_arguments(struct compiler *c, arguments_ty args)
2154{
2155 Py_ssize_t funcflags = 0;
2156 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002157 if (!compiler_visit_defaults(c, args))
2158 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002159 funcflags |= 0x01;
2160 }
2161 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002162 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002163 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002164 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 return -1;
2166 }
2167 else if (res > 0) {
2168 funcflags |= 0x02;
2169 }
2170 }
2171 return funcflags;
2172}
2173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174static int
Yury Selivanov75445082015-05-11 22:57:16 -04002175compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002178 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002179 arguments_ty args;
2180 expr_ty returns;
2181 identifier name;
2182 asdl_seq* decos;
2183 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002184 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002185 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002186 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002187 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188
Yury Selivanov75445082015-05-11 22:57:16 -04002189 if (is_async) {
2190 assert(s->kind == AsyncFunctionDef_kind);
2191
2192 args = s->v.AsyncFunctionDef.args;
2193 returns = s->v.AsyncFunctionDef.returns;
2194 decos = s->v.AsyncFunctionDef.decorator_list;
2195 name = s->v.AsyncFunctionDef.name;
2196 body = s->v.AsyncFunctionDef.body;
2197
2198 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2199 } else {
2200 assert(s->kind == FunctionDef_kind);
2201
2202 args = s->v.FunctionDef.args;
2203 returns = s->v.FunctionDef.returns;
2204 decos = s->v.FunctionDef.decorator_list;
2205 name = s->v.FunctionDef.name;
2206 body = s->v.FunctionDef.body;
2207
2208 scope_type = COMPILER_SCOPE_FUNCTION;
2209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (!compiler_decorators(c, decos))
2212 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002213
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002214 firstlineno = s->lineno;
2215 if (asdl_seq_LEN(decos)) {
2216 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2217 }
2218
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002219 funcflags = compiler_default_arguments(c, args);
2220 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002222 }
2223
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002224 annotations = compiler_visit_annotations(c, args, returns);
2225 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002226 return 0;
2227 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002228 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002229 funcflags |= 0x04;
2230 }
2231
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002232 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002233 return 0;
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235
INADA Naokicb41b272017-02-23 00:31:59 +09002236 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002237 if (c->c_optimize < 2) {
2238 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002239 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002240 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 compiler_exit_scope(c);
2242 return 0;
2243 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002246 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002248 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002250 qualname = c->u->u_qualname;
2251 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002253 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002254 Py_XDECREF(qualname);
2255 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002259 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002260 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* decorators */
2264 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2265 ADDOP_I(c, CALL_FUNCTION, 1);
2266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267
Yury Selivanov75445082015-05-11 22:57:16 -04002268 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269}
2270
2271static int
2272compiler_class(struct compiler *c, stmt_ty s)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyCodeObject *co;
2275 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002276 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (!compiler_decorators(c, decos))
2280 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002281
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002282 firstlineno = s->lineno;
2283 if (asdl_seq_LEN(decos)) {
2284 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2285 }
2286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* ultimately generate code for:
2288 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2289 where:
2290 <func> is a function/closure created from the class body;
2291 it has a single argument (__locals__) where the dict
2292 (or MutableSequence) representing the locals is passed
2293 <name> is the class name
2294 <bases> is the positional arguments and *varargs argument
2295 <keywords> is the keyword arguments and **kwds argument
2296 This borrows from compiler_call.
2297 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002300 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002301 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 return 0;
2303 /* this block represents what we do in the new scope */
2304 {
2305 /* use the class name for name mangling */
2306 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002307 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* load (global) __name__ ... */
2309 str = PyUnicode_InternFromString("__name__");
2310 if (!str || !compiler_nameop(c, str, Load)) {
2311 Py_XDECREF(str);
2312 compiler_exit_scope(c);
2313 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_DECREF(str);
2316 /* ... and store it as __module__ */
2317 str = PyUnicode_InternFromString("__module__");
2318 if (!str || !compiler_nameop(c, str, Store)) {
2319 Py_XDECREF(str);
2320 compiler_exit_scope(c);
2321 return 0;
2322 }
2323 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002324 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002325 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002326 str = PyUnicode_InternFromString("__qualname__");
2327 if (!str || !compiler_nameop(c, str, Store)) {
2328 Py_XDECREF(str);
2329 compiler_exit_scope(c);
2330 return 0;
2331 }
2332 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002334 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 compiler_exit_scope(c);
2336 return 0;
2337 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002338 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002339 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002340 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002341 str = PyUnicode_InternFromString("__class__");
2342 if (str == NULL) {
2343 compiler_exit_scope(c);
2344 return 0;
2345 }
2346 i = compiler_lookup_arg(c->u->u_cellvars, str);
2347 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002348 if (i < 0) {
2349 compiler_exit_scope(c);
2350 return 0;
2351 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002352 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002355 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002356 str = PyUnicode_InternFromString("__classcell__");
2357 if (!str || !compiler_nameop(c, str, Store)) {
2358 Py_XDECREF(str);
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002364 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002365 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002366 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002367 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002368 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002369 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* create the code object */
2371 co = assemble(c, 1);
2372 }
2373 /* leave the new scope */
2374 compiler_exit_scope(c);
2375 if (co == NULL)
2376 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* 2. load the 'build_class' function */
2379 ADDOP(c, LOAD_BUILD_CLASS);
2380
2381 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002382 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 Py_DECREF(co);
2384
2385 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002386 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387
2388 /* 5. generate the rest of the code for the call */
2389 if (!compiler_call_helper(c, 2,
2390 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002391 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return 0;
2393
2394 /* 6. apply decorators */
2395 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2396 ADDOP_I(c, CALL_FUNCTION, 1);
2397 }
2398
2399 /* 7. store into <name> */
2400 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2401 return 0;
2402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403}
2404
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002405/* Return 0 if the expression is a constant value except named singletons.
2406 Return 1 otherwise. */
2407static int
2408check_is_arg(expr_ty e)
2409{
2410 if (e->kind != Constant_kind) {
2411 return 1;
2412 }
2413 PyObject *value = e->v.Constant.value;
2414 return (value == Py_None
2415 || value == Py_False
2416 || value == Py_True
2417 || value == Py_Ellipsis);
2418}
2419
2420/* Check operands of identity chacks ("is" and "is not").
2421 Emit a warning if any operand is a constant except named singletons.
2422 Return 0 on error.
2423 */
2424static int
2425check_compare(struct compiler *c, expr_ty e)
2426{
2427 Py_ssize_t i, n;
2428 int left = check_is_arg(e->v.Compare.left);
2429 n = asdl_seq_LEN(e->v.Compare.ops);
2430 for (i = 0; i < n; i++) {
2431 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2432 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2433 if (op == Is || op == IsNot) {
2434 if (!right || !left) {
2435 const char *msg = (op == Is)
2436 ? "\"is\" with a literal. Did you mean \"==\"?"
2437 : "\"is not\" with a literal. Did you mean \"!=\"?";
2438 return compiler_warn(c, msg);
2439 }
2440 }
2441 left = right;
2442 }
2443 return 1;
2444}
2445
Mark Shannon9af0e472020-01-14 10:12:45 +00002446static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002447{
Mark Shannon9af0e472020-01-14 10:12:45 +00002448 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449 switch (op) {
2450 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002451 cmp = Py_EQ;
2452 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002453 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002454 cmp = Py_NE;
2455 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002456 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002457 cmp = Py_LT;
2458 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002459 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002460 cmp = Py_LE;
2461 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002462 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002463 cmp = Py_GT;
2464 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002465 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002466 cmp = Py_GE;
2467 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002468 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002469 ADDOP_I(c, IS_OP, 0);
2470 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002471 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002472 ADDOP_I(c, IS_OP, 1);
2473 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002474 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002475 ADDOP_I(c, CONTAINS_OP, 0);
2476 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002478 ADDOP_I(c, CONTAINS_OP, 1);
2479 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002480 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 ADDOP_I(c, COMPARE_OP, cmp);
2484 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485}
2486
Mark Shannon9af0e472020-01-14 10:12:45 +00002487
2488
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489static int
2490compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2491{
2492 switch (e->kind) {
2493 case UnaryOp_kind:
2494 if (e->v.UnaryOp.op == Not)
2495 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2496 /* fallback to general implementation */
2497 break;
2498 case BoolOp_kind: {
2499 asdl_seq *s = e->v.BoolOp.values;
2500 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2501 assert(n >= 0);
2502 int cond2 = e->v.BoolOp.op == Or;
2503 basicblock *next2 = next;
2504 if (!cond2 != !cond) {
2505 next2 = compiler_new_block(c);
2506 if (next2 == NULL)
2507 return 0;
2508 }
2509 for (i = 0; i < n; ++i) {
2510 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2511 return 0;
2512 }
2513 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2514 return 0;
2515 if (next2 != next)
2516 compiler_use_next_block(c, next2);
2517 return 1;
2518 }
2519 case IfExp_kind: {
2520 basicblock *end, *next2;
2521 end = compiler_new_block(c);
2522 if (end == NULL)
2523 return 0;
2524 next2 = compiler_new_block(c);
2525 if (next2 == NULL)
2526 return 0;
2527 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2528 return 0;
2529 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2530 return 0;
2531 ADDOP_JREL(c, JUMP_FORWARD, end);
2532 compiler_use_next_block(c, next2);
2533 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2534 return 0;
2535 compiler_use_next_block(c, end);
2536 return 1;
2537 }
2538 case Compare_kind: {
2539 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2540 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002541 if (!check_compare(c, e)) {
2542 return 0;
2543 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002544 basicblock *cleanup = compiler_new_block(c);
2545 if (cleanup == NULL)
2546 return 0;
2547 VISIT(c, expr, e->v.Compare.left);
2548 for (i = 0; i < n; i++) {
2549 VISIT(c, expr,
2550 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2551 ADDOP(c, DUP_TOP);
2552 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002553 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002554 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2555 NEXT_BLOCK(c);
2556 }
2557 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002558 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002559 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2560 basicblock *end = compiler_new_block(c);
2561 if (end == NULL)
2562 return 0;
2563 ADDOP_JREL(c, JUMP_FORWARD, end);
2564 compiler_use_next_block(c, cleanup);
2565 ADDOP(c, POP_TOP);
2566 if (!cond) {
2567 ADDOP_JREL(c, JUMP_FORWARD, next);
2568 }
2569 compiler_use_next_block(c, end);
2570 return 1;
2571 }
2572 /* fallback to general implementation */
2573 break;
2574 }
2575 default:
2576 /* fallback to general implementation */
2577 break;
2578 }
2579
2580 /* general implementation */
2581 VISIT(c, expr, e);
2582 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2583 return 1;
2584}
2585
2586static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002587compiler_ifexp(struct compiler *c, expr_ty e)
2588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 basicblock *end, *next;
2590
2591 assert(e->kind == IfExp_kind);
2592 end = compiler_new_block(c);
2593 if (end == NULL)
2594 return 0;
2595 next = compiler_new_block(c);
2596 if (next == NULL)
2597 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002598 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2599 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 VISIT(c, expr, e->v.IfExp.body);
2601 ADDOP_JREL(c, JUMP_FORWARD, end);
2602 compiler_use_next_block(c, next);
2603 VISIT(c, expr, e->v.IfExp.orelse);
2604 compiler_use_next_block(c, end);
2605 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002606}
2607
2608static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609compiler_lambda(struct compiler *c, expr_ty e)
2610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002612 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002614 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 arguments_ty args = e->v.Lambda.args;
2616 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 if (!name) {
2619 name = PyUnicode_InternFromString("<lambda>");
2620 if (!name)
2621 return 0;
2622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002624 funcflags = compiler_default_arguments(c, args);
2625 if (funcflags == -1) {
2626 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002628
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002629 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002630 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 /* Make None the first constant, so the lambda can't have a
2634 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002635 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002639 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2641 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2642 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002643 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 }
2645 else {
2646 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002647 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002649 qualname = c->u->u_qualname;
2650 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002652 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002655 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002656 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 Py_DECREF(co);
2658
2659 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660}
2661
2662static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663compiler_if(struct compiler *c, stmt_ty s)
2664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 basicblock *end, *next;
2666 int constant;
2667 assert(s->kind == If_kind);
2668 end = compiler_new_block(c);
2669 if (end == NULL)
2670 return 0;
2671
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002672 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002673 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 * constant = 1: "if 1", "if 2", ...
2675 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002676 if (constant == 0) {
2677 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002679 END_DO_NOT_EMIT_BYTECODE
2680 if (s->v.If.orelse) {
2681 VISIT_SEQ(c, stmt, s->v.If.orelse);
2682 }
2683 } else if (constant == 1) {
2684 VISIT_SEQ(c, stmt, s->v.If.body);
2685 if (s->v.If.orelse) {
2686 BEGIN_DO_NOT_EMIT_BYTECODE
2687 VISIT_SEQ(c, stmt, s->v.If.orelse);
2688 END_DO_NOT_EMIT_BYTECODE
2689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002691 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 next = compiler_new_block(c);
2693 if (next == NULL)
2694 return 0;
2695 }
Mark Shannonfee55262019-11-21 09:11:43 +00002696 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002698 }
2699 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002700 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002701 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002703 if (asdl_seq_LEN(s->v.If.orelse)) {
2704 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 compiler_use_next_block(c, next);
2706 VISIT_SEQ(c, stmt, s->v.If.orelse);
2707 }
2708 }
2709 compiler_use_next_block(c, end);
2710 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711}
2712
2713static int
2714compiler_for(struct compiler *c, stmt_ty s)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 start = compiler_new_block(c);
2719 cleanup = compiler_new_block(c);
2720 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002721 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002723 }
2724 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 VISIT(c, expr, s->v.For.iter);
2728 ADDOP(c, GET_ITER);
2729 compiler_use_next_block(c, start);
2730 ADDOP_JREL(c, FOR_ITER, cleanup);
2731 VISIT(c, expr, s->v.For.target);
2732 VISIT_SEQ(c, stmt, s->v.For.body);
2733 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2734 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002735
2736 compiler_pop_fblock(c, FOR_LOOP, start);
2737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 VISIT_SEQ(c, stmt, s->v.For.orelse);
2739 compiler_use_next_block(c, end);
2740 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741}
2742
Yury Selivanov75445082015-05-11 22:57:16 -04002743
2744static int
2745compiler_async_for(struct compiler *c, stmt_ty s)
2746{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002747 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002748 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2749 c->u->u_ste->ste_coroutine = 1;
2750 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002751 return compiler_error(c, "'async for' outside async function");
2752 }
2753
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002754 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002755 except = compiler_new_block(c);
2756 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002757
Mark Shannonfee55262019-11-21 09:11:43 +00002758 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002759 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002760 }
Yury Selivanov75445082015-05-11 22:57:16 -04002761 VISIT(c, expr, s->v.AsyncFor.iter);
2762 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002763
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002764 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002765 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002767 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002768 /* SETUP_FINALLY to guard the __anext__ call */
2769 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002770 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002771 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002772 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002774
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002775 /* Success block for __anext__ */
2776 VISIT(c, expr, s->v.AsyncFor.target);
2777 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2778 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2779
2780 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002781
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002782 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002783 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002784 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002785
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002786 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002787 VISIT_SEQ(c, stmt, s->v.For.orelse);
2788
2789 compiler_use_next_block(c, end);
2790
2791 return 1;
2792}
2793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794static int
2795compiler_while(struct compiler *c, stmt_ty s)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002798 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002801 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002802 // Push a dummy block so the VISIT_SEQ knows that we are
2803 // inside a while loop so it can correctly evaluate syntax
2804 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002805 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002806 return 0;
2807 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002808 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002809 // Remove the dummy block now that is not needed.
2810 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002811 END_DO_NOT_EMIT_BYTECODE
2812 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 return 1;
2816 }
2817 loop = compiler_new_block(c);
2818 end = compiler_new_block(c);
2819 if (constant == -1) {
2820 anchor = compiler_new_block(c);
2821 if (anchor == NULL)
2822 return 0;
2823 }
2824 if (loop == NULL || end == NULL)
2825 return 0;
2826 if (s->v.While.orelse) {
2827 orelse = compiler_new_block(c);
2828 if (orelse == NULL)
2829 return 0;
2830 }
2831 else
2832 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002835 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 0;
2837 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002838 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2839 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 }
2841 VISIT_SEQ(c, stmt, s->v.While.body);
2842 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* XXX should the two POP instructions be in a separate block
2845 if there is no else clause ?
2846 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002848 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 compiler_pop_fblock(c, WHILE_LOOP, loop);
2851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 if (orelse != NULL) /* what if orelse is just pass? */
2853 VISIT_SEQ(c, stmt, s->v.While.orelse);
2854 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857}
2858
2859static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002860compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002863 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002864 if (c->u->u_ste->ste_type != FunctionBlock)
2865 return compiler_error(c, "'return' outside function");
2866 if (s->v.Return.value != NULL &&
2867 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2868 {
2869 return compiler_error(
2870 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002872 if (preserve_tos) {
2873 VISIT(c, expr, s->v.Return.value);
2874 }
Mark Shannonfee55262019-11-21 09:11:43 +00002875 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2876 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002878 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 }
2880 else if (!preserve_tos) {
2881 VISIT(c, expr, s->v.Return.value);
2882 }
2883 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886}
2887
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002888static int
2889compiler_break(struct compiler *c)
2890{
Mark Shannonfee55262019-11-21 09:11:43 +00002891 struct fblockinfo *loop = NULL;
2892 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2893 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002894 }
Mark Shannonfee55262019-11-21 09:11:43 +00002895 if (loop == NULL) {
2896 return compiler_error(c, "'break' outside loop");
2897 }
2898 if (!compiler_unwind_fblock(c, loop, 0)) {
2899 return 0;
2900 }
2901 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2902 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002903}
2904
2905static int
2906compiler_continue(struct compiler *c)
2907{
Mark Shannonfee55262019-11-21 09:11:43 +00002908 struct fblockinfo *loop = NULL;
2909 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2910 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002911 }
Mark Shannonfee55262019-11-21 09:11:43 +00002912 if (loop == NULL) {
2913 return compiler_error(c, "'continue' not properly in loop");
2914 }
2915 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2916 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002917}
2918
2919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
2922 SETUP_FINALLY L
2923 <code for body>
2924 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002925 <code for finalbody>
2926 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927 L:
2928 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002929 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 The special instructions use the block stack. Each block
2932 stack entry contains the instruction that created it (here
2933 SETUP_FINALLY), the level of the value stack at the time the
2934 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 Pushes the current value stack level and the label
2938 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002943 when a SETUP_FINALLY entry is found, the raised and the caught
2944 exceptions are pushed onto the value stack (and the exception
2945 condition is cleared), and the interpreter jumps to the label
2946 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947*/
2948
2949static int
2950compiler_try_finally(struct compiler *c, stmt_ty s)
2951{
Mark Shannonfee55262019-11-21 09:11:43 +00002952 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 body = compiler_new_block(c);
2955 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002956 exit = compiler_new_block(c);
2957 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002960 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 ADDOP_JREL(c, SETUP_FINALLY, end);
2962 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002963 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002965 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2966 if (!compiler_try_except(c, s))
2967 return 0;
2968 }
2969 else {
2970 VISIT_SEQ(c, stmt, s->v.Try.body);
2971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002973 compiler_pop_fblock(c, FINALLY_TRY, body);
2974 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2975 ADDOP_JREL(c, JUMP_FORWARD, exit);
2976 /* `finally` block */
2977 compiler_use_next_block(c, end);
2978 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2979 return 0;
2980 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2981 compiler_pop_fblock(c, FINALLY_END, end);
2982 ADDOP(c, RERAISE);
2983 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985}
2986
2987/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002988 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 (The contents of the value stack is shown in [], with the top
2990 at the right; 'tb' is trace-back info, 'val' the exception's
2991 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992
2993 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002994 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 [] <code for S>
2996 [] POP_BLOCK
2997 [] JUMP_FORWARD L0
2998
2999 [tb, val, exc] L1: DUP )
3000 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003001 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 [tb, val, exc] POP
3003 [tb, val] <assign to V1> (or POP if no V1)
3004 [tb] POP
3005 [] <code for S1>
3006 JUMP_FORWARD L0
3007
3008 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 .............................etc.......................
3010
Mark Shannonfee55262019-11-21 09:11:43 +00003011 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012
3013 [] L0: <next statement>
3014
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 Of course, parts are not generated if Vi or Ei is not present.
3016*/
3017static int
3018compiler_try_except(struct compiler *c, stmt_ty s)
3019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003021 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 body = compiler_new_block(c);
3024 except = compiler_new_block(c);
3025 orelse = compiler_new_block(c);
3026 end = compiler_new_block(c);
3027 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3028 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003029 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003031 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003033 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 ADDOP(c, POP_BLOCK);
3035 compiler_pop_fblock(c, EXCEPT, body);
3036 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003037 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 compiler_use_next_block(c, except);
3039 for (i = 0; i < n; i++) {
3040 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003041 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 if (!handler->v.ExceptHandler.type && i < n-1)
3043 return compiler_error(c, "default 'except:' must be last");
3044 c->u->u_lineno_set = 0;
3045 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003046 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 except = compiler_new_block(c);
3048 if (except == NULL)
3049 return 0;
3050 if (handler->v.ExceptHandler.type) {
3051 ADDOP(c, DUP_TOP);
3052 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003053 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 }
3055 ADDOP(c, POP_TOP);
3056 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003058
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 cleanup_end = compiler_new_block(c);
3060 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003061 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003062 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003063 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003064
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3066 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 /*
3069 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003070 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003071 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003072 try:
3073 # body
3074 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003075 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003076 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 /* second try: */
3080 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3081 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003082 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 /* second # body */
3086 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003087 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003088 ADDOP(c, POP_BLOCK);
3089 ADDOP(c, POP_EXCEPT);
3090 /* name = None; del name */
3091 ADDOP_LOAD_CONST(c, Py_None);
3092 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3093 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3094 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095
Mark Shannonfee55262019-11-21 09:11:43 +00003096 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003099 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003100 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103
Mark Shannonfee55262019-11-21 09:11:43 +00003104 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 }
3106 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003110 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112
Guido van Rossumb940e112007-01-10 16:19:56 +00003113 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003114 ADDOP(c, POP_TOP);
3115 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003116 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003119 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003120 ADDOP(c, POP_EXCEPT);
3121 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 compiler_use_next_block(c, except);
3124 }
Mark Shannonfee55262019-11-21 09:11:43 +00003125 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003127 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 compiler_use_next_block(c, end);
3129 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130}
3131
3132static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003133compiler_try(struct compiler *c, stmt_ty s) {
3134 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3135 return compiler_try_finally(c, s);
3136 else
3137 return compiler_try_except(c, s);
3138}
3139
3140
3141static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142compiler_import_as(struct compiler *c, identifier name, identifier asname)
3143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* The IMPORT_NAME opcode was already generated. This function
3145 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003148 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003150 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3151 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003152 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003153 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003156 while (1) {
3157 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003159 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003160 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003161 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003162 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003164 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003165 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003166 if (dot == -1) {
3167 break;
3168 }
3169 ADDOP(c, ROT_TWO);
3170 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003172 if (!compiler_nameop(c, asname, Store)) {
3173 return 0;
3174 }
3175 ADDOP(c, POP_TOP);
3176 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 }
3178 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179}
3180
3181static int
3182compiler_import(struct compiler *c, stmt_ty s)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 /* The Import node stores a module name like a.b.c as a single
3185 string. This is convenient for all cases except
3186 import a.b.c as d
3187 where we need to parse that string to extract the individual
3188 module names.
3189 XXX Perhaps change the representation to make this case simpler?
3190 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003191 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 for (i = 0; i < n; i++) {
3194 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3195 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003197 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3198 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 if (alias->asname) {
3202 r = compiler_import_as(c, alias->name, alias->asname);
3203 if (!r)
3204 return r;
3205 }
3206 else {
3207 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003208 Py_ssize_t dot = PyUnicode_FindChar(
3209 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003210 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003211 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003212 if (tmp == NULL)
3213 return 0;
3214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003216 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 Py_DECREF(tmp);
3218 }
3219 if (!r)
3220 return r;
3221 }
3222 }
3223 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224}
3225
3226static int
3227compiler_from_import(struct compiler *c, stmt_ty s)
3228{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003229 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003230 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 if (!empty_string) {
3234 empty_string = PyUnicode_FromString("");
3235 if (!empty_string)
3236 return 0;
3237 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003239 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003240
3241 names = PyTuple_New(n);
3242 if (!names)
3243 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 /* build up the names */
3246 for (i = 0; i < n; i++) {
3247 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3248 Py_INCREF(alias->name);
3249 PyTuple_SET_ITEM(names, i, alias->name);
3250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003253 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 Py_DECREF(names);
3255 return compiler_error(c, "from __future__ imports must occur "
3256 "at the beginning of the file");
3257 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003258 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (s->v.ImportFrom.module) {
3261 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3262 }
3263 else {
3264 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3265 }
3266 for (i = 0; i < n; i++) {
3267 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3268 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003270 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 assert(n == 1);
3272 ADDOP(c, IMPORT_STAR);
3273 return 1;
3274 }
3275
3276 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3277 store_name = alias->name;
3278 if (alias->asname)
3279 store_name = alias->asname;
3280
3281 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return 0;
3283 }
3284 }
3285 /* remove imported module */
3286 ADDOP(c, POP_TOP);
3287 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288}
3289
3290static int
3291compiler_assert(struct compiler *c, stmt_ty s)
3292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294
Georg Brandl8334fd92010-12-04 10:26:46 +00003295 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003298 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3299 {
3300 if (!compiler_warn(c, "assertion is always true, "
3301 "perhaps remove parentheses?"))
3302 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003303 return 0;
3304 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 end = compiler_new_block(c);
3307 if (end == NULL)
3308 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003309 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3310 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003311 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 if (s->v.Assert.msg) {
3313 VISIT(c, expr, s->v.Assert.msg);
3314 ADDOP_I(c, CALL_FUNCTION, 1);
3315 }
3316 ADDOP_I(c, RAISE_VARARGS, 1);
3317 compiler_use_next_block(c, end);
3318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319}
3320
3321static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003322compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3323{
3324 if (c->c_interactive && c->c_nestlevel <= 1) {
3325 VISIT(c, expr, value);
3326 ADDOP(c, PRINT_EXPR);
3327 return 1;
3328 }
3329
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003330 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003331 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003332 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003333 }
3334
3335 VISIT(c, expr, value);
3336 ADDOP(c, POP_TOP);
3337 return 1;
3338}
3339
3340static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003341compiler_visit_stmt(struct compiler *c, stmt_ty s)
3342{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003343 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 /* Always assign a lineno to the next instruction for a stmt. */
3346 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003347 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 switch (s->kind) {
3351 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003352 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 case ClassDef_kind:
3354 return compiler_class(c, s);
3355 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003356 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 case Delete_kind:
3358 VISIT_SEQ(c, expr, s->v.Delete.targets)
3359 break;
3360 case Assign_kind:
3361 n = asdl_seq_LEN(s->v.Assign.targets);
3362 VISIT(c, expr, s->v.Assign.value);
3363 for (i = 0; i < n; i++) {
3364 if (i < n - 1)
3365 ADDOP(c, DUP_TOP);
3366 VISIT(c, expr,
3367 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3368 }
3369 break;
3370 case AugAssign_kind:
3371 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003372 case AnnAssign_kind:
3373 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case For_kind:
3375 return compiler_for(c, s);
3376 case While_kind:
3377 return compiler_while(c, s);
3378 case If_kind:
3379 return compiler_if(c, s);
3380 case Raise_kind:
3381 n = 0;
3382 if (s->v.Raise.exc) {
3383 VISIT(c, expr, s->v.Raise.exc);
3384 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003385 if (s->v.Raise.cause) {
3386 VISIT(c, expr, s->v.Raise.cause);
3387 n++;
3388 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003390 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003392 case Try_kind:
3393 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 case Assert_kind:
3395 return compiler_assert(c, s);
3396 case Import_kind:
3397 return compiler_import(c, s);
3398 case ImportFrom_kind:
3399 return compiler_from_import(c, s);
3400 case Global_kind:
3401 case Nonlocal_kind:
3402 break;
3403 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003404 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 case Pass_kind:
3406 break;
3407 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003408 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 case Continue_kind:
3410 return compiler_continue(c);
3411 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003412 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003413 case AsyncFunctionDef_kind:
3414 return compiler_function(c, s, 1);
3415 case AsyncWith_kind:
3416 return compiler_async_with(c, s, 0);
3417 case AsyncFor_kind:
3418 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 }
Yury Selivanov75445082015-05-11 22:57:16 -04003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422}
3423
3424static int
3425unaryop(unaryop_ty op)
3426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 switch (op) {
3428 case Invert:
3429 return UNARY_INVERT;
3430 case Not:
3431 return UNARY_NOT;
3432 case UAdd:
3433 return UNARY_POSITIVE;
3434 case USub:
3435 return UNARY_NEGATIVE;
3436 default:
3437 PyErr_Format(PyExc_SystemError,
3438 "unary op %d should not be possible", op);
3439 return 0;
3440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003441}
3442
3443static int
3444binop(struct compiler *c, operator_ty op)
3445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 switch (op) {
3447 case Add:
3448 return BINARY_ADD;
3449 case Sub:
3450 return BINARY_SUBTRACT;
3451 case Mult:
3452 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003453 case MatMult:
3454 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 case Div:
3456 return BINARY_TRUE_DIVIDE;
3457 case Mod:
3458 return BINARY_MODULO;
3459 case Pow:
3460 return BINARY_POWER;
3461 case LShift:
3462 return BINARY_LSHIFT;
3463 case RShift:
3464 return BINARY_RSHIFT;
3465 case BitOr:
3466 return BINARY_OR;
3467 case BitXor:
3468 return BINARY_XOR;
3469 case BitAnd:
3470 return BINARY_AND;
3471 case FloorDiv:
3472 return BINARY_FLOOR_DIVIDE;
3473 default:
3474 PyErr_Format(PyExc_SystemError,
3475 "binary op %d should not be possible", op);
3476 return 0;
3477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481inplace_binop(struct compiler *c, operator_ty op)
3482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 switch (op) {
3484 case Add:
3485 return INPLACE_ADD;
3486 case Sub:
3487 return INPLACE_SUBTRACT;
3488 case Mult:
3489 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003490 case MatMult:
3491 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 case Div:
3493 return INPLACE_TRUE_DIVIDE;
3494 case Mod:
3495 return INPLACE_MODULO;
3496 case Pow:
3497 return INPLACE_POWER;
3498 case LShift:
3499 return INPLACE_LSHIFT;
3500 case RShift:
3501 return INPLACE_RSHIFT;
3502 case BitOr:
3503 return INPLACE_OR;
3504 case BitXor:
3505 return INPLACE_XOR;
3506 case BitAnd:
3507 return INPLACE_AND;
3508 case FloorDiv:
3509 return INPLACE_FLOOR_DIVIDE;
3510 default:
3511 PyErr_Format(PyExc_SystemError,
3512 "inplace binary op %d should not be possible", op);
3513 return 0;
3514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515}
3516
3517static int
3518compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3519{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003520 int op, scope;
3521 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 PyObject *dict = c->u->u_names;
3525 PyObject *mangled;
3526 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003528 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3529 !_PyUnicode_EqualToASCIIString(name, "True") &&
3530 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003531
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003532 mangled = _Py_Mangle(c->u->u_private, name);
3533 if (!mangled)
3534 return 0;
3535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 op = 0;
3537 optype = OP_NAME;
3538 scope = PyST_GetScope(c->u->u_ste, mangled);
3539 switch (scope) {
3540 case FREE:
3541 dict = c->u->u_freevars;
3542 optype = OP_DEREF;
3543 break;
3544 case CELL:
3545 dict = c->u->u_cellvars;
3546 optype = OP_DEREF;
3547 break;
3548 case LOCAL:
3549 if (c->u->u_ste->ste_type == FunctionBlock)
3550 optype = OP_FAST;
3551 break;
3552 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003553 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 optype = OP_GLOBAL;
3555 break;
3556 case GLOBAL_EXPLICIT:
3557 optype = OP_GLOBAL;
3558 break;
3559 default:
3560 /* scope can be 0 */
3561 break;
3562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003565 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 switch (optype) {
3568 case OP_DEREF:
3569 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003570 case Load:
3571 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3572 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003573 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003574 op = STORE_DEREF;
3575 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 case AugLoad:
3577 case AugStore:
3578 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003579 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 case Param:
3581 default:
3582 PyErr_SetString(PyExc_SystemError,
3583 "param invalid for deref variable");
3584 return 0;
3585 }
3586 break;
3587 case OP_FAST:
3588 switch (ctx) {
3589 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003590 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003591 op = STORE_FAST;
3592 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 case Del: op = DELETE_FAST; break;
3594 case AugLoad:
3595 case AugStore:
3596 break;
3597 case Param:
3598 default:
3599 PyErr_SetString(PyExc_SystemError,
3600 "param invalid for local variable");
3601 return 0;
3602 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003603 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 return 1;
3605 case OP_GLOBAL:
3606 switch (ctx) {
3607 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003608 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003609 op = STORE_GLOBAL;
3610 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 case Del: op = DELETE_GLOBAL; break;
3612 case AugLoad:
3613 case AugStore:
3614 break;
3615 case Param:
3616 default:
3617 PyErr_SetString(PyExc_SystemError,
3618 "param invalid for global variable");
3619 return 0;
3620 }
3621 break;
3622 case OP_NAME:
3623 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003624 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003625 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003626 op = STORE_NAME;
3627 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 case Del: op = DELETE_NAME; break;
3629 case AugLoad:
3630 case AugStore:
3631 break;
3632 case Param:
3633 default:
3634 PyErr_SetString(PyExc_SystemError,
3635 "param invalid for name variable");
3636 return 0;
3637 }
3638 break;
3639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 assert(op);
3642 arg = compiler_add_o(c, dict, mangled);
3643 Py_DECREF(mangled);
3644 if (arg < 0)
3645 return 0;
3646 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647}
3648
3649static int
3650compiler_boolop(struct compiler *c, expr_ty e)
3651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003653 int jumpi;
3654 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 assert(e->kind == BoolOp_kind);
3658 if (e->v.BoolOp.op == And)
3659 jumpi = JUMP_IF_FALSE_OR_POP;
3660 else
3661 jumpi = JUMP_IF_TRUE_OR_POP;
3662 end = compiler_new_block(c);
3663 if (end == NULL)
3664 return 0;
3665 s = e->v.BoolOp.values;
3666 n = asdl_seq_LEN(s) - 1;
3667 assert(n >= 0);
3668 for (i = 0; i < n; ++i) {
3669 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3670 ADDOP_JABS(c, jumpi, end);
3671 }
3672 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3673 compiler_use_next_block(c, end);
3674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675}
3676
3677static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003678starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3679 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003680{
3681 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003682 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003683 if (n > 2 && are_all_items_const(elts, 0, n)) {
3684 PyObject *folded = PyTuple_New(n);
3685 if (folded == NULL) {
3686 return 0;
3687 }
3688 PyObject *val;
3689 for (i = 0; i < n; i++) {
3690 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3691 Py_INCREF(val);
3692 PyTuple_SET_ITEM(folded, i, val);
3693 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003694 if (tuple) {
3695 ADDOP_LOAD_CONST_NEW(c, folded);
3696 } else {
3697 if (add == SET_ADD) {
3698 Py_SETREF(folded, PyFrozenSet_New(folded));
3699 if (folded == NULL) {
3700 return 0;
3701 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003702 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003703 ADDOP_I(c, build, pushed);
3704 ADDOP_LOAD_CONST_NEW(c, folded);
3705 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003706 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003707 return 1;
3708 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003709
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 for (i = 0; i < n; i++) {
3711 expr_ty elt = asdl_seq_GET(elts, i);
3712 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003713 seen_star = 1;
3714 }
3715 }
3716 if (seen_star) {
3717 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) {
3721 if (seen_star == 0) {
3722 ADDOP_I(c, build, i+pushed);
3723 seen_star = 1;
3724 }
3725 VISIT(c, expr, elt->v.Starred.value);
3726 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003728 else {
3729 VISIT(c, expr, elt);
3730 if (seen_star) {
3731 ADDOP_I(c, add, 1);
3732 }
3733 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003735 assert(seen_star);
3736 if (tuple) {
3737 ADDOP(c, LIST_TO_TUPLE);
3738 }
3739 }
3740 else {
3741 for (i = 0; i < n; i++) {
3742 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003744 }
3745 if (tuple) {
3746 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3747 } else {
3748 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 }
3750 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 return 1;
3752}
3753
3754static int
3755assignment_helper(struct compiler *c, asdl_seq *elts)
3756{
3757 Py_ssize_t n = asdl_seq_LEN(elts);
3758 Py_ssize_t i;
3759 int seen_star = 0;
3760 for (i = 0; i < n; i++) {
3761 expr_ty elt = asdl_seq_GET(elts, i);
3762 if (elt->kind == Starred_kind && !seen_star) {
3763 if ((i >= (1 << 8)) ||
3764 (n-i-1 >= (INT_MAX >> 8)))
3765 return compiler_error(c,
3766 "too many expressions in "
3767 "star-unpacking assignment");
3768 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3769 seen_star = 1;
3770 asdl_seq_SET(elts, i, elt->v.Starred.value);
3771 }
3772 else if (elt->kind == Starred_kind) {
3773 return compiler_error(c,
3774 "two starred expressions in assignment");
3775 }
3776 }
3777 if (!seen_star) {
3778 ADDOP_I(c, UNPACK_SEQUENCE, n);
3779 }
3780 VISIT_SEQ(c, expr, elts);
3781 return 1;
3782}
3783
3784static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785compiler_list(struct compiler *c, expr_ty e)
3786{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003787 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003788 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003792 return starunpack_helper(c, elts, 0, BUILD_LIST,
3793 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 else
3796 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798}
3799
3800static int
3801compiler_tuple(struct compiler *c, expr_ty e)
3802{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003804 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 return assignment_helper(c, elts);
3806 }
3807 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003808 return starunpack_helper(c, elts, 0, BUILD_LIST,
3809 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 }
3811 else
3812 VISIT_SEQ(c, expr, elts);
3813 return 1;
3814}
3815
3816static int
3817compiler_set(struct compiler *c, expr_ty e)
3818{
Mark Shannon13bc1392020-01-23 09:25:17 +00003819 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3820 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821}
3822
3823static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003824are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3825{
3826 Py_ssize_t i;
3827 for (i = begin; i < end; i++) {
3828 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003829 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003830 return 0;
3831 }
3832 return 1;
3833}
3834
3835static int
3836compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3837{
3838 Py_ssize_t i, n = end - begin;
3839 PyObject *keys, *key;
3840 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3841 for (i = begin; i < end; i++) {
3842 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3843 }
3844 keys = PyTuple_New(n);
3845 if (keys == NULL) {
3846 return 0;
3847 }
3848 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003849 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003850 Py_INCREF(key);
3851 PyTuple_SET_ITEM(keys, i - begin, key);
3852 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003853 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003854 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3855 }
3856 else {
3857 for (i = begin; i < end; i++) {
3858 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3859 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3860 }
3861 ADDOP_I(c, BUILD_MAP, n);
3862 }
3863 return 1;
3864}
3865
3866static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003867compiler_dict(struct compiler *c, expr_ty e)
3868{
Victor Stinner976bb402016-03-23 11:36:19 +01003869 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003870 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871 int is_unpacking = 0;
3872 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003873 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003874 elements = 0;
3875 for (i = 0; i < n; i++) {
3876 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 if (elements) {
3879 if (!compiler_subdict(c, e, i - elements, i)) {
3880 return 0;
3881 }
3882 if (have_dict) {
3883 ADDOP_I(c, DICT_UPDATE, 1);
3884 }
3885 have_dict = 1;
3886 elements = 0;
3887 }
3888 if (have_dict == 0) {
3889 ADDOP_I(c, BUILD_MAP, 0);
3890 have_dict = 1;
3891 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003892 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003893 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003894 }
3895 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003896 if (elements == 0xFFFF) {
3897 if (!compiler_subdict(c, e, i - elements, i)) {
3898 return 0;
3899 }
3900 if (have_dict) {
3901 ADDOP_I(c, DICT_UPDATE, 1);
3902 }
3903 have_dict = 1;
3904 elements = 0;
3905 }
3906 else {
3907 elements++;
3908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 }
3910 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003911 if (elements) {
3912 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003913 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003914 }
3915 if (have_dict) {
3916 ADDOP_I(c, DICT_UPDATE, 1);
3917 }
3918 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003919 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003920 if (!have_dict) {
3921 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 }
3923 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003924}
3925
3926static int
3927compiler_compare(struct compiler *c, expr_ty e)
3928{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003929 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003931 if (!check_compare(c, e)) {
3932 return 0;
3933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003935 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3936 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3937 if (n == 0) {
3938 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003939 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003940 }
3941 else {
3942 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 if (cleanup == NULL)
3944 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003945 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 VISIT(c, expr,
3947 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003948 ADDOP(c, DUP_TOP);
3949 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003950 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003951 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3952 NEXT_BLOCK(c);
3953 }
3954 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003955 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 basicblock *end = compiler_new_block(c);
3957 if (end == NULL)
3958 return 0;
3959 ADDOP_JREL(c, JUMP_FORWARD, end);
3960 compiler_use_next_block(c, cleanup);
3961 ADDOP(c, ROT_TWO);
3962 ADDOP(c, POP_TOP);
3963 compiler_use_next_block(c, end);
3964 }
3965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966}
3967
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003968static PyTypeObject *
3969infer_type(expr_ty e)
3970{
3971 switch (e->kind) {
3972 case Tuple_kind:
3973 return &PyTuple_Type;
3974 case List_kind:
3975 case ListComp_kind:
3976 return &PyList_Type;
3977 case Dict_kind:
3978 case DictComp_kind:
3979 return &PyDict_Type;
3980 case Set_kind:
3981 case SetComp_kind:
3982 return &PySet_Type;
3983 case GeneratorExp_kind:
3984 return &PyGen_Type;
3985 case Lambda_kind:
3986 return &PyFunction_Type;
3987 case JoinedStr_kind:
3988 case FormattedValue_kind:
3989 return &PyUnicode_Type;
3990 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003991 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003992 default:
3993 return NULL;
3994 }
3995}
3996
3997static int
3998check_caller(struct compiler *c, expr_ty e)
3999{
4000 switch (e->kind) {
4001 case Constant_kind:
4002 case Tuple_kind:
4003 case List_kind:
4004 case ListComp_kind:
4005 case Dict_kind:
4006 case DictComp_kind:
4007 case Set_kind:
4008 case SetComp_kind:
4009 case GeneratorExp_kind:
4010 case JoinedStr_kind:
4011 case FormattedValue_kind:
4012 return compiler_warn(c, "'%.200s' object is not callable; "
4013 "perhaps you missed a comma?",
4014 infer_type(e)->tp_name);
4015 default:
4016 return 1;
4017 }
4018}
4019
4020static int
4021check_subscripter(struct compiler *c, expr_ty e)
4022{
4023 PyObject *v;
4024
4025 switch (e->kind) {
4026 case Constant_kind:
4027 v = e->v.Constant.value;
4028 if (!(v == Py_None || v == Py_Ellipsis ||
4029 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4030 PyAnySet_Check(v)))
4031 {
4032 return 1;
4033 }
4034 /* fall through */
4035 case Set_kind:
4036 case SetComp_kind:
4037 case GeneratorExp_kind:
4038 case Lambda_kind:
4039 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4040 "perhaps you missed a comma?",
4041 infer_type(e)->tp_name);
4042 default:
4043 return 1;
4044 }
4045}
4046
4047static int
4048check_index(struct compiler *c, expr_ty e, slice_ty s)
4049{
4050 PyObject *v;
4051
4052 if (s->kind != Index_kind) {
4053 return 1;
4054 }
4055 PyTypeObject *index_type = infer_type(s->v.Index.value);
4056 if (index_type == NULL
4057 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4058 || index_type == &PySlice_Type) {
4059 return 1;
4060 }
4061
4062 switch (e->kind) {
4063 case Constant_kind:
4064 v = e->v.Constant.value;
4065 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4066 return 1;
4067 }
4068 /* fall through */
4069 case Tuple_kind:
4070 case List_kind:
4071 case ListComp_kind:
4072 case JoinedStr_kind:
4073 case FormattedValue_kind:
4074 return compiler_warn(c, "%.200s indices must be integers or slices, "
4075 "not %.200s; "
4076 "perhaps you missed a comma?",
4077 infer_type(e)->tp_name,
4078 index_type->tp_name);
4079 default:
4080 return 1;
4081 }
4082}
4083
Zackery Spytz97f5de02019-03-22 01:30:32 -06004084// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004086maybe_optimize_method_call(struct compiler *c, expr_ty e)
4087{
4088 Py_ssize_t argsl, i;
4089 expr_ty meth = e->v.Call.func;
4090 asdl_seq *args = e->v.Call.args;
4091
4092 /* Check that the call node is an attribute access, and that
4093 the call doesn't have keyword parameters. */
4094 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4095 asdl_seq_LEN(e->v.Call.keywords))
4096 return -1;
4097
4098 /* Check that there are no *varargs types of arguments. */
4099 argsl = asdl_seq_LEN(args);
4100 for (i = 0; i < argsl; i++) {
4101 expr_ty elt = asdl_seq_GET(args, i);
4102 if (elt->kind == Starred_kind) {
4103 return -1;
4104 }
4105 }
4106
4107 /* Alright, we can optimize the code. */
4108 VISIT(c, expr, meth->v.Attribute.value);
4109 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4110 VISIT_SEQ(c, expr, e->v.Call.args);
4111 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4112 return 1;
4113}
4114
4115static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116compiler_call(struct compiler *c, expr_ty e)
4117{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004118 int ret = maybe_optimize_method_call(c, e);
4119 if (ret >= 0) {
4120 return ret;
4121 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004122 if (!check_caller(c, e->v.Call.func)) {
4123 return 0;
4124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 VISIT(c, expr, e->v.Call.func);
4126 return compiler_call_helper(c, 0,
4127 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004128 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004129}
4130
Eric V. Smith235a6f02015-09-19 14:51:32 -04004131static int
4132compiler_joined_str(struct compiler *c, expr_ty e)
4133{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004134 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004135 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4136 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004137 return 1;
4138}
4139
Eric V. Smitha78c7952015-11-03 12:45:05 -05004140/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004141static int
4142compiler_formatted_value(struct compiler *c, expr_ty e)
4143{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004144 /* Our oparg encodes 2 pieces of information: the conversion
4145 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004146
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004147 Convert the conversion char to 3 bits:
4148 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004149 !s : 001 0x1 FVC_STR
4150 !r : 010 0x2 FVC_REPR
4151 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004152
Eric V. Smitha78c7952015-11-03 12:45:05 -05004153 next bit is whether or not we have a format spec:
4154 yes : 100 0x4
4155 no : 000 0x0
4156 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004158 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004160
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004161 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162 VISIT(c, expr, e->v.FormattedValue.value);
4163
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004164 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 case 's': oparg = FVC_STR; break;
4166 case 'r': oparg = FVC_REPR; break;
4167 case 'a': oparg = FVC_ASCII; break;
4168 case -1: oparg = FVC_NONE; break;
4169 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004170 PyErr_Format(PyExc_SystemError,
4171 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004172 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 }
4179
Eric V. Smitha78c7952015-11-03 12:45:05 -05004180 /* And push our opcode and oparg */
4181 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004182
Eric V. Smith235a6f02015-09-19 14:51:32 -04004183 return 1;
4184}
4185
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004186static int
4187compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4188{
4189 Py_ssize_t i, n = end - begin;
4190 keyword_ty kw;
4191 PyObject *keys, *key;
4192 assert(n > 0);
4193 if (n > 1) {
4194 for (i = begin; i < end; i++) {
4195 kw = asdl_seq_GET(keywords, i);
4196 VISIT(c, expr, kw->value);
4197 }
4198 keys = PyTuple_New(n);
4199 if (keys == NULL) {
4200 return 0;
4201 }
4202 for (i = begin; i < end; i++) {
4203 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4204 Py_INCREF(key);
4205 PyTuple_SET_ITEM(keys, i - begin, key);
4206 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004207 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004208 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4209 }
4210 else {
4211 /* a for loop only executes once */
4212 for (i = begin; i < end; i++) {
4213 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004214 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004215 VISIT(c, expr, kw->value);
4216 }
4217 ADDOP_I(c, BUILD_MAP, n);
4218 }
4219 return 1;
4220}
4221
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004222/* shared code between compiler_call and compiler_class */
4223static int
4224compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004225 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004226 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004227 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004228{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004230
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004231 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004232 nkwelts = asdl_seq_LEN(keywords);
4233
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004234 for (i = 0; i < nelts; i++) {
4235 expr_ty elt = asdl_seq_GET(args, i);
4236 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004237 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004238 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004239 }
4240 for (i = 0; i < nkwelts; i++) {
4241 keyword_ty kw = asdl_seq_GET(keywords, i);
4242 if (kw->arg == NULL) {
4243 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246
Mark Shannon13bc1392020-01-23 09:25:17 +00004247 /* No * or ** args, so can use faster calling sequence */
4248 for (i = 0; i < nelts; i++) {
4249 expr_ty elt = asdl_seq_GET(args, i);
4250 assert(elt->kind != Starred_kind);
4251 VISIT(c, expr, elt);
4252 }
4253 if (nkwelts) {
4254 PyObject *names;
4255 VISIT_SEQ(c, keyword, keywords);
4256 names = PyTuple_New(nkwelts);
4257 if (names == NULL) {
4258 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004259 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004260 for (i = 0; i < nkwelts; i++) {
4261 keyword_ty kw = asdl_seq_GET(keywords, i);
4262 Py_INCREF(kw->arg);
4263 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004265 ADDOP_LOAD_CONST_NEW(c, names);
4266 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4267 return 1;
4268 }
4269 else {
4270 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4271 return 1;
4272 }
4273
4274ex_call:
4275
4276 /* Do positional arguments. */
4277 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4278 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4279 }
4280 else if (starunpack_helper(c, args, n, BUILD_LIST,
4281 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4282 return 0;
4283 }
4284 /* Then keyword arguments */
4285 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004286 /* Has a new dict been pushed */
4287 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004288
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004289 nseen = 0; /* the number of keyword arguments on the stack following */
4290 for (i = 0; i < nkwelts; i++) {
4291 keyword_ty kw = asdl_seq_GET(keywords, i);
4292 if (kw->arg == NULL) {
4293 /* A keyword argument unpacking. */
4294 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004295 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004296 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004297 }
4298 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004299 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004300 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004301 if (!have_dict) {
4302 ADDOP_I(c, BUILD_MAP, 0);
4303 have_dict = 1;
4304 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004305 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004307 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004308 else {
4309 nseen++;
4310 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004311 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004312 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004313 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004314 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004315 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004316 }
4317 if (have_dict) {
4318 ADDOP_I(c, DICT_MERGE, 1);
4319 }
4320 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004321 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004322 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004324 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326}
4327
Nick Coghlan650f0d02007-04-15 12:05:43 +00004328
4329/* List and set comprehensions and generator expressions work by creating a
4330 nested function to perform the actual iteration. This means that the
4331 iteration variables don't leak into the current scope.
4332 The defined function is called immediately following its definition, with the
4333 result of that call being the result of the expression.
4334 The LC/SC version returns the populated container, while the GE version is
4335 flagged in symtable.c as a generator, so it returns the generator object
4336 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004337
4338 Possible cleanups:
4339 - iterate over the generator sequence instead of using recursion
4340*/
4341
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004342
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344compiler_comprehension_generator(struct compiler *c,
4345 asdl_seq *generators, int gen_index,
4346 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004348 comprehension_ty gen;
4349 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4350 if (gen->is_async) {
4351 return compiler_async_comprehension_generator(
4352 c, generators, gen_index, elt, val, type);
4353 } else {
4354 return compiler_sync_comprehension_generator(
4355 c, generators, gen_index, elt, val, type);
4356 }
4357}
4358
4359static int
4360compiler_sync_comprehension_generator(struct compiler *c,
4361 asdl_seq *generators, int gen_index,
4362 expr_ty elt, expr_ty val, int type)
4363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* generate code for the iterator, then each of the ifs,
4365 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 comprehension_ty gen;
4368 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004369 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 start = compiler_new_block(c);
4372 skip = compiler_new_block(c);
4373 if_cleanup = compiler_new_block(c);
4374 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4377 anchor == NULL)
4378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (gen_index == 0) {
4383 /* Receive outermost iter as an implicit argument */
4384 c->u->u_argcount = 1;
4385 ADDOP_I(c, LOAD_FAST, 0);
4386 }
4387 else {
4388 /* Sub-iter - calculate on the fly */
4389 VISIT(c, expr, gen->iter);
4390 ADDOP(c, GET_ITER);
4391 }
4392 compiler_use_next_block(c, start);
4393 ADDOP_JREL(c, FOR_ITER, anchor);
4394 NEXT_BLOCK(c);
4395 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 /* XXX this needs to be cleaned up...a lot! */
4398 n = asdl_seq_LEN(gen->ifs);
4399 for (i = 0; i < n; i++) {
4400 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004401 if (!compiler_jump_if(c, e, if_cleanup, 0))
4402 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 NEXT_BLOCK(c);
4404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 if (++gen_index < asdl_seq_LEN(generators))
4407 if (!compiler_comprehension_generator(c,
4408 generators, gen_index,
4409 elt, val, type))
4410 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 /* only append after the last for generator */
4413 if (gen_index >= asdl_seq_LEN(generators)) {
4414 /* comprehension specific code */
4415 switch (type) {
4416 case COMP_GENEXP:
4417 VISIT(c, expr, elt);
4418 ADDOP(c, YIELD_VALUE);
4419 ADDOP(c, POP_TOP);
4420 break;
4421 case COMP_LISTCOMP:
4422 VISIT(c, expr, elt);
4423 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4424 break;
4425 case COMP_SETCOMP:
4426 VISIT(c, expr, elt);
4427 ADDOP_I(c, SET_ADD, gen_index + 1);
4428 break;
4429 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004430 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004433 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 ADDOP_I(c, MAP_ADD, gen_index + 1);
4435 break;
4436 default:
4437 return 0;
4438 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 compiler_use_next_block(c, skip);
4441 }
4442 compiler_use_next_block(c, if_cleanup);
4443 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4444 compiler_use_next_block(c, anchor);
4445
4446 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447}
4448
4449static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004450compiler_async_comprehension_generator(struct compiler *c,
4451 asdl_seq *generators, int gen_index,
4452 expr_ty elt, expr_ty val, int type)
4453{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004454 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004455 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004456 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004457 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004458 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004459 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004460
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004461 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462 return 0;
4463 }
4464
4465 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4466
4467 if (gen_index == 0) {
4468 /* Receive outermost iter as an implicit argument */
4469 c->u->u_argcount = 1;
4470 ADDOP_I(c, LOAD_FAST, 0);
4471 }
4472 else {
4473 /* Sub-iter - calculate on the fly */
4474 VISIT(c, expr, gen->iter);
4475 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004476 }
4477
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004478 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004479
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004480 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004481 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004482 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004483 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004485 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486
4487 n = asdl_seq_LEN(gen->ifs);
4488 for (i = 0; i < n; i++) {
4489 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004490 if (!compiler_jump_if(c, e, if_cleanup, 0))
4491 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492 NEXT_BLOCK(c);
4493 }
4494
4495 if (++gen_index < asdl_seq_LEN(generators))
4496 if (!compiler_comprehension_generator(c,
4497 generators, gen_index,
4498 elt, val, type))
4499 return 0;
4500
4501 /* only append after the last for generator */
4502 if (gen_index >= asdl_seq_LEN(generators)) {
4503 /* comprehension specific code */
4504 switch (type) {
4505 case COMP_GENEXP:
4506 VISIT(c, expr, elt);
4507 ADDOP(c, YIELD_VALUE);
4508 ADDOP(c, POP_TOP);
4509 break;
4510 case COMP_LISTCOMP:
4511 VISIT(c, expr, elt);
4512 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4513 break;
4514 case COMP_SETCOMP:
4515 VISIT(c, expr, elt);
4516 ADDOP_I(c, SET_ADD, gen_index + 1);
4517 break;
4518 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004519 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004522 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523 ADDOP_I(c, MAP_ADD, gen_index + 1);
4524 break;
4525 default:
4526 return 0;
4527 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 }
4529 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004530 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4531
4532 compiler_use_next_block(c, except);
4533 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534
4535 return 1;
4536}
4537
4538static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004539compiler_comprehension(struct compiler *c, expr_ty e, int type,
4540 identifier name, asdl_seq *generators, expr_ty elt,
4541 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004544 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004545 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 int is_async_function = c->u->u_ste->ste_coroutine;
4547 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004548
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004550
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004551 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4552 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 }
4556
4557 is_async_generator = c->u->u_ste->ste_coroutine;
4558
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004559 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004560 compiler_error(c, "asynchronous comprehension outside of "
4561 "an asynchronous function");
4562 goto error_in_scope;
4563 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 if (type != COMP_GENEXP) {
4566 int op;
4567 switch (type) {
4568 case COMP_LISTCOMP:
4569 op = BUILD_LIST;
4570 break;
4571 case COMP_SETCOMP:
4572 op = BUILD_SET;
4573 break;
4574 case COMP_DICTCOMP:
4575 op = BUILD_MAP;
4576 break;
4577 default:
4578 PyErr_Format(PyExc_SystemError,
4579 "unknown comprehension type %d", type);
4580 goto error_in_scope;
4581 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 ADDOP_I(c, op, 0);
4584 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 if (!compiler_comprehension_generator(c, generators, 0, elt,
4587 val, type))
4588 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 if (type != COMP_GENEXP) {
4591 ADDOP(c, RETURN_VALUE);
4592 }
4593
4594 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004595 qualname = c->u->u_qualname;
4596 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004598 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 goto error;
4600
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004601 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004603 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 Py_DECREF(co);
4605
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004606 VISIT(c, expr, outermost->iter);
4607
4608 if (outermost->is_async) {
4609 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004610 } else {
4611 ADDOP(c, GET_ITER);
4612 }
4613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004615
4616 if (is_async_generator && type != COMP_GENEXP) {
4617 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004618 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004619 ADDOP(c, YIELD_FROM);
4620 }
4621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004623error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004625error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004626 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 Py_XDECREF(co);
4628 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004629}
4630
4631static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004632compiler_genexp(struct compiler *c, expr_ty e)
4633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 static identifier name;
4635 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004636 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 if (!name)
4638 return 0;
4639 }
4640 assert(e->kind == GeneratorExp_kind);
4641 return compiler_comprehension(c, e, COMP_GENEXP, name,
4642 e->v.GeneratorExp.generators,
4643 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004644}
4645
4646static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004647compiler_listcomp(struct compiler *c, expr_ty e)
4648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 static identifier name;
4650 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004651 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (!name)
4653 return 0;
4654 }
4655 assert(e->kind == ListComp_kind);
4656 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4657 e->v.ListComp.generators,
4658 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004659}
4660
4661static int
4662compiler_setcomp(struct compiler *c, expr_ty e)
4663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 static identifier name;
4665 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004666 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 if (!name)
4668 return 0;
4669 }
4670 assert(e->kind == SetComp_kind);
4671 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4672 e->v.SetComp.generators,
4673 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004674}
4675
4676
4677static int
4678compiler_dictcomp(struct compiler *c, expr_ty e)
4679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 static identifier name;
4681 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004682 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 if (!name)
4684 return 0;
4685 }
4686 assert(e->kind == DictComp_kind);
4687 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4688 e->v.DictComp.generators,
4689 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004690}
4691
4692
4693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004694compiler_visit_keyword(struct compiler *c, keyword_ty k)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 VISIT(c, expr, k->value);
4697 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698}
4699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004701 whether they are true or false.
4702
4703 Return values: 1 for true, 0 for false, -1 for non-constant.
4704 */
4705
4706static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004707expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004708{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004709 if (e->kind == Constant_kind) {
4710 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004711 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004712 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004713}
4714
Mark Shannonfee55262019-11-21 09:11:43 +00004715static int
4716compiler_with_except_finish(struct compiler *c) {
4717 basicblock *exit;
4718 exit = compiler_new_block(c);
4719 if (exit == NULL)
4720 return 0;
4721 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4722 ADDOP(c, RERAISE);
4723 compiler_use_next_block(c, exit);
4724 ADDOP(c, POP_TOP);
4725 ADDOP(c, POP_TOP);
4726 ADDOP(c, POP_TOP);
4727 ADDOP(c, POP_EXCEPT);
4728 ADDOP(c, POP_TOP);
4729 return 1;
4730}
Yury Selivanov75445082015-05-11 22:57:16 -04004731
4732/*
4733 Implements the async with statement.
4734
4735 The semantics outlined in that PEP are as follows:
4736
4737 async with EXPR as VAR:
4738 BLOCK
4739
4740 It is implemented roughly as:
4741
4742 context = EXPR
4743 exit = context.__aexit__ # not calling it
4744 value = await context.__aenter__()
4745 try:
4746 VAR = value # if VAR present in the syntax
4747 BLOCK
4748 finally:
4749 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004750 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004751 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004752 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004753 if not (await exit(*exc)):
4754 raise
4755 */
4756static int
4757compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4758{
Mark Shannonfee55262019-11-21 09:11:43 +00004759 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004760 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4761
4762 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004763 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4764 c->u->u_ste->ste_coroutine = 1;
4765 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004766 return compiler_error(c, "'async with' outside async function");
4767 }
Yury Selivanov75445082015-05-11 22:57:16 -04004768
4769 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004770 final = compiler_new_block(c);
4771 exit = compiler_new_block(c);
4772 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004773 return 0;
4774
4775 /* Evaluate EXPR */
4776 VISIT(c, expr, item->context_expr);
4777
4778 ADDOP(c, BEFORE_ASYNC_WITH);
4779 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004780 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004781 ADDOP(c, YIELD_FROM);
4782
Mark Shannonfee55262019-11-21 09:11:43 +00004783 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004784
4785 /* SETUP_ASYNC_WITH pushes a finally block. */
4786 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004787 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004788 return 0;
4789 }
4790
4791 if (item->optional_vars) {
4792 VISIT(c, expr, item->optional_vars);
4793 }
4794 else {
4795 /* Discard result from context.__aenter__() */
4796 ADDOP(c, POP_TOP);
4797 }
4798
4799 pos++;
4800 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4801 /* BLOCK code */
4802 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4803 else if (!compiler_async_with(c, s, pos))
4804 return 0;
4805
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004806 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004807 ADDOP(c, POP_BLOCK);
4808 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004809
Mark Shannonfee55262019-11-21 09:11:43 +00004810 /* For successful outcome:
4811 * call __exit__(None, None, None)
4812 */
4813 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004814 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004815 ADDOP(c, GET_AWAITABLE);
4816 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4817 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004818
Mark Shannonfee55262019-11-21 09:11:43 +00004819 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004820
Mark Shannonfee55262019-11-21 09:11:43 +00004821 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4822
4823 /* For exceptional outcome: */
4824 compiler_use_next_block(c, final);
4825
4826 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004827 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004828 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004829 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004830 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004831
Mark Shannonfee55262019-11-21 09:11:43 +00004832compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004833 return 1;
4834}
4835
4836
Guido van Rossumc2e20742006-02-27 22:32:47 +00004837/*
4838 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004839 with EXPR as VAR:
4840 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004841 is implemented as:
4842 <code for EXPR>
4843 SETUP_WITH E
4844 <code to store to VAR> or POP_TOP
4845 <code for BLOCK>
4846 LOAD_CONST (None, None, None)
4847 CALL_FUNCTION_EX 0
4848 JUMP_FORWARD EXIT
4849 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4850 POP_JUMP_IF_TRUE T:
4851 RERAISE
4852 T: POP_TOP * 3 (remove exception from stack)
4853 POP_EXCEPT
4854 POP_TOP
4855 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004856 */
Mark Shannonfee55262019-11-21 09:11:43 +00004857
Guido van Rossumc2e20742006-02-27 22:32:47 +00004858static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004859compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004860{
Mark Shannonfee55262019-11-21 09:11:43 +00004861 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004862 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004863
4864 assert(s->kind == With_kind);
4865
Guido van Rossumc2e20742006-02-27 22:32:47 +00004866 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004867 final = compiler_new_block(c);
4868 exit = compiler_new_block(c);
4869 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004870 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004871
Thomas Wouters477c8d52006-05-27 19:21:47 +00004872 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004873 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004874 /* Will push bound __exit__ */
4875 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004876
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004877 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004878 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004879 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004880 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004881 }
4882
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004883 if (item->optional_vars) {
4884 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004885 }
4886 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004888 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004889 }
4890
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004891 pos++;
4892 if (pos == asdl_seq_LEN(s->v.With.items))
4893 /* BLOCK code */
4894 VISIT_SEQ(c, stmt, s->v.With.body)
4895 else if (!compiler_with(c, s, pos))
4896 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004897
Guido van Rossumc2e20742006-02-27 22:32:47 +00004898 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004899 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004900
Mark Shannonfee55262019-11-21 09:11:43 +00004901 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004902
Mark Shannonfee55262019-11-21 09:11:43 +00004903 /* For successful outcome:
4904 * call __exit__(None, None, None)
4905 */
4906 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004907 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004908 ADDOP(c, POP_TOP);
4909 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910
Mark Shannonfee55262019-11-21 09:11:43 +00004911 /* For exceptional outcome: */
4912 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913
Mark Shannonfee55262019-11-21 09:11:43 +00004914 ADDOP(c, WITH_EXCEPT_START);
4915 compiler_with_except_finish(c);
4916
4917 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918 return 1;
4919}
4920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004921static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004922compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004925 case NamedExpr_kind:
4926 VISIT(c, expr, e->v.NamedExpr.value);
4927 ADDOP(c, DUP_TOP);
4928 VISIT(c, expr, e->v.NamedExpr.target);
4929 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 case BoolOp_kind:
4931 return compiler_boolop(c, e);
4932 case BinOp_kind:
4933 VISIT(c, expr, e->v.BinOp.left);
4934 VISIT(c, expr, e->v.BinOp.right);
4935 ADDOP(c, binop(c, e->v.BinOp.op));
4936 break;
4937 case UnaryOp_kind:
4938 VISIT(c, expr, e->v.UnaryOp.operand);
4939 ADDOP(c, unaryop(e->v.UnaryOp.op));
4940 break;
4941 case Lambda_kind:
4942 return compiler_lambda(c, e);
4943 case IfExp_kind:
4944 return compiler_ifexp(c, e);
4945 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004946 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004948 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 case GeneratorExp_kind:
4950 return compiler_genexp(c, e);
4951 case ListComp_kind:
4952 return compiler_listcomp(c, e);
4953 case SetComp_kind:
4954 return compiler_setcomp(c, e);
4955 case DictComp_kind:
4956 return compiler_dictcomp(c, e);
4957 case Yield_kind:
4958 if (c->u->u_ste->ste_type != FunctionBlock)
4959 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004960 if (e->v.Yield.value) {
4961 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 }
4963 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004964 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004966 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004968 case YieldFrom_kind:
4969 if (c->u->u_ste->ste_type != FunctionBlock)
4970 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004971
4972 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4973 return compiler_error(c, "'yield from' inside async function");
4974
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004975 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004976 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004977 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004978 ADDOP(c, YIELD_FROM);
4979 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004980 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004981 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4982 if (c->u->u_ste->ste_type != FunctionBlock){
4983 return compiler_error(c, "'await' outside function");
4984 }
Yury Selivanov75445082015-05-11 22:57:16 -04004985
Victor Stinner331a6a52019-05-27 16:39:22 +02004986 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004987 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4988 return compiler_error(c, "'await' outside async function");
4989 }
4990 }
Yury Selivanov75445082015-05-11 22:57:16 -04004991
4992 VISIT(c, expr, e->v.Await.value);
4993 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004994 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004995 ADDOP(c, YIELD_FROM);
4996 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 case Compare_kind:
4998 return compiler_compare(c, e);
4999 case Call_kind:
5000 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005001 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005002 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005003 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005004 case JoinedStr_kind:
5005 return compiler_joined_str(c, e);
5006 case FormattedValue_kind:
5007 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 /* The following exprs can be assignment targets. */
5009 case Attribute_kind:
5010 if (e->v.Attribute.ctx != AugStore)
5011 VISIT(c, expr, e->v.Attribute.value);
5012 switch (e->v.Attribute.ctx) {
5013 case AugLoad:
5014 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005015 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 case Load:
5017 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5018 break;
5019 case AugStore:
5020 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005021 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 case Store:
5023 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5024 break;
5025 case Del:
5026 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5027 break;
5028 case Param:
5029 default:
5030 PyErr_SetString(PyExc_SystemError,
5031 "param invalid in attribute expression");
5032 return 0;
5033 }
5034 break;
5035 case Subscript_kind:
5036 switch (e->v.Subscript.ctx) {
5037 case AugLoad:
5038 VISIT(c, expr, e->v.Subscript.value);
5039 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5040 break;
5041 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005042 if (!check_subscripter(c, e->v.Subscript.value)) {
5043 return 0;
5044 }
5045 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5046 return 0;
5047 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 VISIT(c, expr, e->v.Subscript.value);
5049 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5050 break;
5051 case AugStore:
5052 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5053 break;
5054 case Store:
5055 VISIT(c, expr, e->v.Subscript.value);
5056 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5057 break;
5058 case Del:
5059 VISIT(c, expr, e->v.Subscript.value);
5060 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5061 break;
5062 case Param:
5063 default:
5064 PyErr_SetString(PyExc_SystemError,
5065 "param invalid in subscript expression");
5066 return 0;
5067 }
5068 break;
5069 case Starred_kind:
5070 switch (e->v.Starred.ctx) {
5071 case Store:
5072 /* In all legitimate cases, the Starred node was already replaced
5073 * by compiler_list/compiler_tuple. XXX: is that okay? */
5074 return compiler_error(c,
5075 "starred assignment target must be in a list or tuple");
5076 default:
5077 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005078 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 case Name_kind:
5081 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5082 /* child nodes of List and Tuple will have expr_context set */
5083 case List_kind:
5084 return compiler_list(c, e);
5085 case Tuple_kind:
5086 return compiler_tuple(c, e);
5087 }
5088 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005089}
5090
5091static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005092compiler_visit_expr(struct compiler *c, expr_ty e)
5093{
5094 /* If expr e has a different line number than the last expr/stmt,
5095 set a new line number for the next instruction.
5096 */
5097 int old_lineno = c->u->u_lineno;
5098 int old_col_offset = c->u->u_col_offset;
5099 if (e->lineno != c->u->u_lineno) {
5100 c->u->u_lineno = e->lineno;
5101 c->u->u_lineno_set = 0;
5102 }
5103 /* Updating the column offset is always harmless. */
5104 c->u->u_col_offset = e->col_offset;
5105
5106 int res = compiler_visit_expr1(c, e);
5107
5108 if (old_lineno != c->u->u_lineno) {
5109 c->u->u_lineno = old_lineno;
5110 c->u->u_lineno_set = 0;
5111 }
5112 c->u->u_col_offset = old_col_offset;
5113 return res;
5114}
5115
5116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005117compiler_augassign(struct compiler *c, stmt_ty s)
5118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 expr_ty e = s->v.AugAssign.target;
5120 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 switch (e->kind) {
5125 case Attribute_kind:
5126 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005127 AugLoad, e->lineno, e->col_offset,
5128 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 if (auge == NULL)
5130 return 0;
5131 VISIT(c, expr, auge);
5132 VISIT(c, expr, s->v.AugAssign.value);
5133 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5134 auge->v.Attribute.ctx = AugStore;
5135 VISIT(c, expr, auge);
5136 break;
5137 case Subscript_kind:
5138 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005139 AugLoad, e->lineno, e->col_offset,
5140 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 if (auge == NULL)
5142 return 0;
5143 VISIT(c, expr, auge);
5144 VISIT(c, expr, s->v.AugAssign.value);
5145 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5146 auge->v.Subscript.ctx = AugStore;
5147 VISIT(c, expr, auge);
5148 break;
5149 case Name_kind:
5150 if (!compiler_nameop(c, e->v.Name.id, Load))
5151 return 0;
5152 VISIT(c, expr, s->v.AugAssign.value);
5153 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5154 return compiler_nameop(c, e->v.Name.id, Store);
5155 default:
5156 PyErr_Format(PyExc_SystemError,
5157 "invalid node type (%d) for augmented assignment",
5158 e->kind);
5159 return 0;
5160 }
5161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005162}
5163
5164static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005165check_ann_expr(struct compiler *c, expr_ty e)
5166{
5167 VISIT(c, expr, e);
5168 ADDOP(c, POP_TOP);
5169 return 1;
5170}
5171
5172static int
5173check_annotation(struct compiler *c, stmt_ty s)
5174{
5175 /* Annotations are only evaluated in a module or class. */
5176 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5177 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5178 return check_ann_expr(c, s->v.AnnAssign.annotation);
5179 }
5180 return 1;
5181}
5182
5183static int
5184check_ann_slice(struct compiler *c, slice_ty sl)
5185{
5186 switch(sl->kind) {
5187 case Index_kind:
5188 return check_ann_expr(c, sl->v.Index.value);
5189 case Slice_kind:
5190 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5191 return 0;
5192 }
5193 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5194 return 0;
5195 }
5196 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5197 return 0;
5198 }
5199 break;
5200 default:
5201 PyErr_SetString(PyExc_SystemError,
5202 "unexpected slice kind");
5203 return 0;
5204 }
5205 return 1;
5206}
5207
5208static int
5209check_ann_subscr(struct compiler *c, slice_ty sl)
5210{
5211 /* We check that everything in a subscript is defined at runtime. */
5212 Py_ssize_t i, n;
5213
5214 switch (sl->kind) {
5215 case Index_kind:
5216 case Slice_kind:
5217 if (!check_ann_slice(c, sl)) {
5218 return 0;
5219 }
5220 break;
5221 case ExtSlice_kind:
5222 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5223 for (i = 0; i < n; i++) {
5224 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5225 switch (subsl->kind) {
5226 case Index_kind:
5227 case Slice_kind:
5228 if (!check_ann_slice(c, subsl)) {
5229 return 0;
5230 }
5231 break;
5232 case ExtSlice_kind:
5233 default:
5234 PyErr_SetString(PyExc_SystemError,
5235 "extended slice invalid in nested slice");
5236 return 0;
5237 }
5238 }
5239 break;
5240 default:
5241 PyErr_Format(PyExc_SystemError,
5242 "invalid subscript kind %d", sl->kind);
5243 return 0;
5244 }
5245 return 1;
5246}
5247
5248static int
5249compiler_annassign(struct compiler *c, stmt_ty s)
5250{
5251 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005252 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005253
5254 assert(s->kind == AnnAssign_kind);
5255
5256 /* We perform the actual assignment first. */
5257 if (s->v.AnnAssign.value) {
5258 VISIT(c, expr, s->v.AnnAssign.value);
5259 VISIT(c, expr, targ);
5260 }
5261 switch (targ->kind) {
5262 case Name_kind:
5263 /* If we have a simple name in a module or class, store annotation. */
5264 if (s->v.AnnAssign.simple &&
5265 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5266 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005267 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5268 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5269 }
5270 else {
5271 VISIT(c, expr, s->v.AnnAssign.annotation);
5272 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005273 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005274 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005275 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005276 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005277 }
5278 break;
5279 case Attribute_kind:
5280 if (!s->v.AnnAssign.value &&
5281 !check_ann_expr(c, targ->v.Attribute.value)) {
5282 return 0;
5283 }
5284 break;
5285 case Subscript_kind:
5286 if (!s->v.AnnAssign.value &&
5287 (!check_ann_expr(c, targ->v.Subscript.value) ||
5288 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5289 return 0;
5290 }
5291 break;
5292 default:
5293 PyErr_Format(PyExc_SystemError,
5294 "invalid node type (%d) for annotated assignment",
5295 targ->kind);
5296 return 0;
5297 }
5298 /* Annotation is evaluated last. */
5299 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5300 return 0;
5301 }
5302 return 1;
5303}
5304
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005305/* Raises a SyntaxError and returns 0.
5306 If something goes wrong, a different exception may be raised.
5307*/
5308
5309static int
5310compiler_error(struct compiler *c, const char *errstr)
5311{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005312 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314
Victor Stinner14e461d2013-08-26 22:28:21 +02005315 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 if (!loc) {
5317 Py_INCREF(Py_None);
5318 loc = Py_None;
5319 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005320 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005321 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 if (!u)
5323 goto exit;
5324 v = Py_BuildValue("(zO)", errstr, u);
5325 if (!v)
5326 goto exit;
5327 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005328 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 Py_DECREF(loc);
5330 Py_XDECREF(u);
5331 Py_XDECREF(v);
5332 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005333}
5334
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005335/* Emits a SyntaxWarning and returns 1 on success.
5336 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5337 and returns 0.
5338*/
5339static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005340compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005341{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005342 va_list vargs;
5343#ifdef HAVE_STDARG_PROTOTYPES
5344 va_start(vargs, format);
5345#else
5346 va_start(vargs);
5347#endif
5348 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5349 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005350 if (msg == NULL) {
5351 return 0;
5352 }
5353 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5354 c->u->u_lineno, NULL, NULL) < 0)
5355 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005356 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005357 /* Replace the SyntaxWarning exception with a SyntaxError
5358 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005359 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005360 assert(PyUnicode_AsUTF8(msg) != NULL);
5361 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005362 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005363 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005364 return 0;
5365 }
5366 Py_DECREF(msg);
5367 return 1;
5368}
5369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371compiler_handle_subscr(struct compiler *c, const char *kind,
5372 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 /* XXX this code is duplicated */
5377 switch (ctx) {
5378 case AugLoad: /* fall through to Load */
5379 case Load: op = BINARY_SUBSCR; break;
5380 case AugStore:/* fall through to Store */
5381 case Store: op = STORE_SUBSCR; break;
5382 case Del: op = DELETE_SUBSCR; break;
5383 case Param:
5384 PyErr_Format(PyExc_SystemError,
5385 "invalid %s kind %d in subscript\n",
5386 kind, ctx);
5387 return 0;
5388 }
5389 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005390 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 }
5392 else if (ctx == AugStore) {
5393 ADDOP(c, ROT_THREE);
5394 }
5395 ADDOP(c, op);
5396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005397}
5398
5399static int
5400compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 int n = 2;
5403 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 /* only handles the cases where BUILD_SLICE is emitted */
5406 if (s->v.Slice.lower) {
5407 VISIT(c, expr, s->v.Slice.lower);
5408 }
5409 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005410 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 if (s->v.Slice.upper) {
5414 VISIT(c, expr, s->v.Slice.upper);
5415 }
5416 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005417 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 }
5419
5420 if (s->v.Slice.step) {
5421 n++;
5422 VISIT(c, expr, s->v.Slice.step);
5423 }
5424 ADDOP_I(c, BUILD_SLICE, n);
5425 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005426}
5427
5428static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5430 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 switch (s->kind) {
5433 case Slice_kind:
5434 return compiler_slice(c, s, ctx);
5435 case Index_kind:
5436 VISIT(c, expr, s->v.Index.value);
5437 break;
5438 case ExtSlice_kind:
5439 default:
5440 PyErr_SetString(PyExc_SystemError,
5441 "extended slice invalid in nested slice");
5442 return 0;
5443 }
5444 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005445}
5446
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447static int
5448compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5449{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005450 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 switch (s->kind) {
5452 case Index_kind:
5453 kindname = "index";
5454 if (ctx != AugStore) {
5455 VISIT(c, expr, s->v.Index.value);
5456 }
5457 break;
5458 case Slice_kind:
5459 kindname = "slice";
5460 if (ctx != AugStore) {
5461 if (!compiler_slice(c, s, ctx))
5462 return 0;
5463 }
5464 break;
5465 case ExtSlice_kind:
5466 kindname = "extended slice";
5467 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005468 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 for (i = 0; i < n; i++) {
5470 slice_ty sub = (slice_ty)asdl_seq_GET(
5471 s->v.ExtSlice.dims, i);
5472 if (!compiler_visit_nested_slice(c, sub, ctx))
5473 return 0;
5474 }
5475 ADDOP_I(c, BUILD_TUPLE, n);
5476 }
5477 break;
5478 default:
5479 PyErr_Format(PyExc_SystemError,
5480 "invalid subscript kind %d", s->kind);
5481 return 0;
5482 }
5483 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005484}
5485
Thomas Wouters89f507f2006-12-13 04:49:30 +00005486/* End of the compiler section, beginning of the assembler section */
5487
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005488/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005489 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005490
5491 XXX must handle implicit jumps from one block to next
5492*/
5493
Thomas Wouters89f507f2006-12-13 04:49:30 +00005494struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 PyObject *a_bytecode; /* string containing bytecode */
5496 int a_offset; /* offset into bytecode */
5497 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005498 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 PyObject *a_lnotab; /* string containing lnotab */
5500 int a_lnotab_off; /* offset into lnotab */
5501 int a_lineno; /* last lineno of emitted instruction */
5502 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005503};
5504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005505static void
T. Wouters99b54d62019-09-12 07:05:33 -07005506dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507{
T. Wouters99b54d62019-09-12 07:05:33 -07005508 int i, j;
5509
5510 /* Get rid of recursion for normal control flow.
5511 Since the number of blocks is limited, unused space in a_postorder
5512 (from a_nblocks to end) can be used as a stack for still not ordered
5513 blocks. */
5514 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005515 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005516 assert(a->a_nblocks < j);
5517 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 }
T. Wouters99b54d62019-09-12 07:05:33 -07005519 while (j < end) {
5520 b = a->a_postorder[j++];
5521 for (i = 0; i < b->b_iused; i++) {
5522 struct instr *instr = &b->b_instr[i];
5523 if (instr->i_jrel || instr->i_jabs)
5524 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005525 }
T. Wouters99b54d62019-09-12 07:05:33 -07005526 assert(a->a_nblocks < j);
5527 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005528 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005529}
5530
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005531Py_LOCAL_INLINE(void)
5532stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005533{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005534 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005535 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005536 assert(b->b_startdepth < 0);
5537 b->b_startdepth = depth;
5538 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005539 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005540}
5541
5542/* Find the flow path that needs the largest stack. We assume that
5543 * cycles in the flow graph have no net effect on the stack depth.
5544 */
5545static int
5546stackdepth(struct compiler *c)
5547{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005548 basicblock *b, *entryblock = NULL;
5549 basicblock **stack, **sp;
5550 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 b->b_startdepth = INT_MIN;
5553 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005554 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 }
5556 if (!entryblock)
5557 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005558 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5559 if (!stack) {
5560 PyErr_NoMemory();
5561 return -1;
5562 }
5563
5564 sp = stack;
5565 stackdepth_push(&sp, entryblock, 0);
5566 while (sp != stack) {
5567 b = *--sp;
5568 int depth = b->b_startdepth;
5569 assert(depth >= 0);
5570 basicblock *next = b->b_next;
5571 for (int i = 0; i < b->b_iused; i++) {
5572 struct instr *instr = &b->b_instr[i];
5573 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5574 if (effect == PY_INVALID_STACK_EFFECT) {
5575 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5576 Py_FatalError("PyCompile_OpcodeStackEffect()");
5577 }
5578 int new_depth = depth + effect;
5579 if (new_depth > maxdepth) {
5580 maxdepth = new_depth;
5581 }
5582 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5583 if (instr->i_jrel || instr->i_jabs) {
5584 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5585 assert(effect != PY_INVALID_STACK_EFFECT);
5586 int target_depth = depth + effect;
5587 if (target_depth > maxdepth) {
5588 maxdepth = target_depth;
5589 }
5590 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005591 stackdepth_push(&sp, instr->i_target, target_depth);
5592 }
5593 depth = new_depth;
5594 if (instr->i_opcode == JUMP_ABSOLUTE ||
5595 instr->i_opcode == JUMP_FORWARD ||
5596 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005597 instr->i_opcode == RAISE_VARARGS ||
5598 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005599 {
5600 /* remaining code is dead */
5601 next = NULL;
5602 break;
5603 }
5604 }
5605 if (next != NULL) {
5606 stackdepth_push(&sp, next, depth);
5607 }
5608 }
5609 PyObject_Free(stack);
5610 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005611}
5612
5613static int
5614assemble_init(struct assembler *a, int nblocks, int firstlineno)
5615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 memset(a, 0, sizeof(struct assembler));
5617 a->a_lineno = firstlineno;
5618 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5619 if (!a->a_bytecode)
5620 return 0;
5621 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5622 if (!a->a_lnotab)
5623 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005624 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 PyErr_NoMemory();
5626 return 0;
5627 }
T. Wouters99b54d62019-09-12 07:05:33 -07005628 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005629 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005630 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 PyErr_NoMemory();
5632 return 0;
5633 }
5634 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005635}
5636
5637static void
5638assemble_free(struct assembler *a)
5639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 Py_XDECREF(a->a_bytecode);
5641 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005642 if (a->a_postorder)
5643 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005644}
5645
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005646static int
5647blocksize(basicblock *b)
5648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 int i;
5650 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005653 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005655}
5656
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005657/* Appends a pair to the end of the line number table, a_lnotab, representing
5658 the instruction's bytecode offset and line number. See
5659 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005660
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005661static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005662assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005665 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005667
Serhiy Storchakaab874002016-09-11 13:48:15 +03005668 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 if(d_bytecode == 0 && d_lineno == 0)
5674 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 if (d_bytecode > 255) {
5677 int j, nbytes, ncodes = d_bytecode / 255;
5678 nbytes = a->a_lnotab_off + 2 * ncodes;
5679 len = PyBytes_GET_SIZE(a->a_lnotab);
5680 if (nbytes >= len) {
5681 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5682 len = nbytes;
5683 else if (len <= INT_MAX / 2)
5684 len *= 2;
5685 else {
5686 PyErr_NoMemory();
5687 return 0;
5688 }
5689 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5690 return 0;
5691 }
5692 lnotab = (unsigned char *)
5693 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5694 for (j = 0; j < ncodes; j++) {
5695 *lnotab++ = 255;
5696 *lnotab++ = 0;
5697 }
5698 d_bytecode -= ncodes * 255;
5699 a->a_lnotab_off += ncodes * 2;
5700 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005701 assert(0 <= d_bytecode && d_bytecode <= 255);
5702
5703 if (d_lineno < -128 || 127 < d_lineno) {
5704 int j, nbytes, ncodes, k;
5705 if (d_lineno < 0) {
5706 k = -128;
5707 /* use division on positive numbers */
5708 ncodes = (-d_lineno) / 128;
5709 }
5710 else {
5711 k = 127;
5712 ncodes = d_lineno / 127;
5713 }
5714 d_lineno -= ncodes * k;
5715 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 nbytes = a->a_lnotab_off + 2 * ncodes;
5717 len = PyBytes_GET_SIZE(a->a_lnotab);
5718 if (nbytes >= len) {
5719 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5720 len = nbytes;
5721 else if (len <= INT_MAX / 2)
5722 len *= 2;
5723 else {
5724 PyErr_NoMemory();
5725 return 0;
5726 }
5727 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5728 return 0;
5729 }
5730 lnotab = (unsigned char *)
5731 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5732 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005733 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 d_bytecode = 0;
5735 for (j = 1; j < ncodes; j++) {
5736 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005737 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 a->a_lnotab_off += ncodes * 2;
5740 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005741 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 len = PyBytes_GET_SIZE(a->a_lnotab);
5744 if (a->a_lnotab_off + 2 >= len) {
5745 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5746 return 0;
5747 }
5748 lnotab = (unsigned char *)
5749 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 a->a_lnotab_off += 2;
5752 if (d_bytecode) {
5753 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005754 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 }
5756 else { /* First line of a block; def stmt, etc. */
5757 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005758 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 }
5760 a->a_lineno = i->i_lineno;
5761 a->a_lineno_off = a->a_offset;
5762 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005763}
5764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005765/* assemble_emit()
5766 Extend the bytecode with a new instruction.
5767 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005768*/
5769
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005770static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005771assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005772{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005773 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005775 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005776
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005777 arg = i->i_oparg;
5778 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 if (i->i_lineno && !assemble_lnotab(a, i))
5780 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005781 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 if (len > PY_SSIZE_T_MAX / 2)
5783 return 0;
5784 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5785 return 0;
5786 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005787 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005789 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005791}
5792
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005793static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005794assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005797 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 /* Compute the size of each block and fixup jump args.
5801 Replace block pointer with position in bytecode. */
5802 do {
5803 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005804 for (i = a->a_nblocks - 1; i >= 0; i--) {
5805 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 bsize = blocksize(b);
5807 b->b_offset = totsize;
5808 totsize += bsize;
5809 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005810 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5812 bsize = b->b_offset;
5813 for (i = 0; i < b->b_iused; i++) {
5814 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005815 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 /* Relative jumps are computed relative to
5817 the instruction pointer after fetching
5818 the jump instruction.
5819 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005820 bsize += isize;
5821 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005823 if (instr->i_jrel) {
5824 instr->i_oparg -= bsize;
5825 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005826 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005827 if (instrsize(instr->i_oparg) != isize) {
5828 extended_arg_recompile = 1;
5829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 }
5832 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 /* XXX: This is an awful hack that could hurt performance, but
5835 on the bright side it should work until we come up
5836 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 The issue is that in the first loop blocksize() is called
5839 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005840 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 So we loop until we stop seeing new EXTENDED_ARGs.
5844 The only EXTENDED_ARGs that could be popping up are
5845 ones in jump instructions. So this should converge
5846 fairly quickly.
5847 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005848 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005849}
5850
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005851static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005852dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005855 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 tuple = PyTuple_New(size);
5858 if (tuple == NULL)
5859 return NULL;
5860 while (PyDict_Next(dict, &pos, &k, &v)) {
5861 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005862 Py_INCREF(k);
5863 assert((i - offset) < size);
5864 assert((i - offset) >= 0);
5865 PyTuple_SET_ITEM(tuple, i - offset, k);
5866 }
5867 return tuple;
5868}
5869
5870static PyObject *
5871consts_dict_keys_inorder(PyObject *dict)
5872{
5873 PyObject *consts, *k, *v;
5874 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5875
5876 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5877 if (consts == NULL)
5878 return NULL;
5879 while (PyDict_Next(dict, &pos, &k, &v)) {
5880 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005881 /* The keys of the dictionary can be tuples wrapping a contant.
5882 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5883 * the object we want is always second. */
5884 if (PyTuple_CheckExact(k)) {
5885 k = PyTuple_GET_ITEM(k, 1);
5886 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005888 assert(i < size);
5889 assert(i >= 0);
5890 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005892 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005893}
5894
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005895static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005896compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005899 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005901 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 if (ste->ste_nested)
5903 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005904 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005906 if (!ste->ste_generator && ste->ste_coroutine)
5907 flags |= CO_COROUTINE;
5908 if (ste->ste_generator && ste->ste_coroutine)
5909 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 if (ste->ste_varargs)
5911 flags |= CO_VARARGS;
5912 if (ste->ste_varkeywords)
5913 flags |= CO_VARKEYWORDS;
5914 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 /* (Only) inherit compilerflags in PyCF_MASK */
5917 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005918
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005919 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5920 ste->ste_coroutine &&
5921 !ste->ste_generator) {
5922 flags |= CO_COROUTINE;
5923 }
5924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005926}
5927
INADA Naokic2e16072018-11-26 21:23:22 +09005928// Merge *tuple* with constant cache.
5929// Unlike merge_consts_recursive(), this function doesn't work recursively.
5930static int
5931merge_const_tuple(struct compiler *c, PyObject **tuple)
5932{
5933 assert(PyTuple_CheckExact(*tuple));
5934
5935 PyObject *key = _PyCode_ConstantKey(*tuple);
5936 if (key == NULL) {
5937 return 0;
5938 }
5939
5940 // t is borrowed reference
5941 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5942 Py_DECREF(key);
5943 if (t == NULL) {
5944 return 0;
5945 }
5946 if (t == key) { // tuple is new constant.
5947 return 1;
5948 }
5949
5950 PyObject *u = PyTuple_GET_ITEM(t, 1);
5951 Py_INCREF(u);
5952 Py_DECREF(*tuple);
5953 *tuple = u;
5954 return 1;
5955}
5956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005957static PyCodeObject *
5958makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 PyObject *tmp;
5961 PyCodeObject *co = NULL;
5962 PyObject *consts = NULL;
5963 PyObject *names = NULL;
5964 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 PyObject *name = NULL;
5966 PyObject *freevars = NULL;
5967 PyObject *cellvars = NULL;
5968 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005969 Py_ssize_t nlocals;
5970 int nlocals_int;
5971 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005972 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005973
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005974 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 names = dict_keys_inorder(c->u->u_names, 0);
5976 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5977 if (!consts || !names || !varnames)
5978 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5981 if (!cellvars)
5982 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005983 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005984 if (!freevars)
5985 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005986
INADA Naokic2e16072018-11-26 21:23:22 +09005987 if (!merge_const_tuple(c, &names) ||
5988 !merge_const_tuple(c, &varnames) ||
5989 !merge_const_tuple(c, &cellvars) ||
5990 !merge_const_tuple(c, &freevars))
5991 {
5992 goto error;
5993 }
5994
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005995 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005996 assert(nlocals < INT_MAX);
5997 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 flags = compute_code_flags(c);
6000 if (flags < 0)
6001 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
6004 if (!bytecode)
6005 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6008 if (!tmp)
6009 goto error;
6010 Py_DECREF(consts);
6011 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09006012 if (!merge_const_tuple(c, &consts)) {
6013 goto error;
6014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006016 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006017 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006018 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006019 maxdepth = stackdepth(c);
6020 if (maxdepth < 0) {
6021 goto error;
6022 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006023 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006024 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006025 maxdepth, flags, bytecode, consts, names,
6026 varnames, freevars, cellvars, c->c_filename,
6027 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006028 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 Py_XDECREF(consts);
6030 Py_XDECREF(names);
6031 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006032 Py_XDECREF(name);
6033 Py_XDECREF(freevars);
6034 Py_XDECREF(cellvars);
6035 Py_XDECREF(bytecode);
6036 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006037}
6038
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006039
6040/* For debugging purposes only */
6041#if 0
6042static void
6043dump_instr(const struct instr *i)
6044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 const char *jrel = i->i_jrel ? "jrel " : "";
6046 const char *jabs = i->i_jabs ? "jabs " : "";
6047 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006050 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006051 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006052 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6054 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006055}
6056
6057static void
6058dump_basicblock(const basicblock *b)
6059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006060 const char *seen = b->b_seen ? "seen " : "";
6061 const char *b_return = b->b_return ? "return " : "";
6062 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6063 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6064 if (b->b_instr) {
6065 int i;
6066 for (i = 0; i < b->b_iused; i++) {
6067 fprintf(stderr, " [%02d] ", i);
6068 dump_instr(b->b_instr + i);
6069 }
6070 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006071}
6072#endif
6073
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006074static PyCodeObject *
6075assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006077 basicblock *b, *entryblock;
6078 struct assembler a;
6079 int i, j, nblocks;
6080 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006082 /* Make sure every block that falls off the end returns None.
6083 XXX NEXT_BLOCK() isn't quite right, because if the last
6084 block ends with a jump or return b_next shouldn't set.
6085 */
6086 if (!c->u->u_curblock->b_return) {
6087 NEXT_BLOCK(c);
6088 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006089 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006090 ADDOP(c, RETURN_VALUE);
6091 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006093 nblocks = 0;
6094 entryblock = NULL;
6095 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6096 nblocks++;
6097 entryblock = b;
6098 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006100 /* Set firstlineno if it wasn't explicitly set. */
6101 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006102 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006103 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6104 else
6105 c->u->u_firstlineno = 1;
6106 }
6107 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6108 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006109 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006111 /* Can't modify the bytecode after computing jump offsets. */
6112 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006113
T. Wouters99b54d62019-09-12 07:05:33 -07006114 /* Emit code in reverse postorder from dfs. */
6115 for (i = a.a_nblocks - 1; i >= 0; i--) {
6116 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006117 for (j = 0; j < b->b_iused; j++)
6118 if (!assemble_emit(&a, &b->b_instr[j]))
6119 goto error;
6120 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006122 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6123 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006124 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006125 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006128 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006129 assemble_free(&a);
6130 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006131}
Georg Brandl8334fd92010-12-04 10:26:46 +00006132
6133#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006134PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006135PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6136 PyArena *arena)
6137{
6138 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6139}