blob: 9ed29f4a1f9e54bf4b3b006523ee5527b1ede305 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800200static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200201static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500203static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400204static int compiler_async_with(struct compiler *, stmt_ty, int);
205static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100206static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400208 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500209static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400210static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700212static int compiler_sync_comprehension_generator(
213 struct compiler *c,
214 asdl_seq *generators, int gen_index,
215 expr_ty elt, expr_ty val, int type);
216
217static int compiler_async_comprehension_generator(
218 struct compiler *c,
219 asdl_seq *generators, int gen_index,
220 expr_ty elt, expr_ty val, int type);
221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000223static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400225#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* Name mangling: __private becomes _classname__private.
231 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 PyObject *result;
233 size_t nlen, plen, ipriv;
234 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 PyUnicode_READ_CHAR(ident, 0) != '_' ||
237 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident;
240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 nlen = PyUnicode_GET_LENGTH(ident);
242 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 The only time a name with a dot can occur is when
246 we are compiling an import statement that has a
247 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 TODO(jhylton): Decide whether we want to support
250 mangling of the module name, e.g. __M.X.
251 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
253 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
254 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_INCREF(ident);
256 return ident; /* Don't mangle __whatever__ */
257 }
258 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 ipriv = 0;
260 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
261 ipriv++;
262 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_INCREF(ident);
264 return ident; /* Don't mangle if class is just underscores */
265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000267
Antoine Pitrou55bff892013-04-06 21:21:04 +0200268 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
269 PyErr_SetString(PyExc_OverflowError,
270 "private identifier too large to be mangled");
271 return NULL;
272 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
275 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
276 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
277
278 result = PyUnicode_New(1 + nlen + plen, maxchar);
279 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
282 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200283 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
284 Py_DECREF(result);
285 return NULL;
286 }
287 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
288 Py_DECREF(result);
289 return NULL;
290 }
Victor Stinner8f825062012-04-27 13:55:39 +0200291 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000293}
294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295static int
296compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299
INADA Naokic2e16072018-11-26 21:23:22 +0900300 c->c_const_cache = PyDict_New();
301 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900303 }
304
305 c->c_stack = PyList_New(0);
306 if (!c->c_stack) {
307 Py_CLEAR(c->c_const_cache);
308 return 0;
309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312}
313
314PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200315PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
316 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 struct compiler c;
319 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200320 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200322 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!__doc__) {
325 __doc__ = PyUnicode_InternFromString("__doc__");
326 if (!__doc__)
327 return NULL;
328 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000329 if (!__annotations__) {
330 __annotations__ = PyUnicode_InternFromString("__annotations__");
331 if (!__annotations__)
332 return NULL;
333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!compiler_init(&c))
335 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 c.c_filename = filename;
338 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200339 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (c.c_future == NULL)
341 goto finally;
342 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 flags = &local_flags;
344 }
345 merged = c.c_future->ff_features | flags->cf_flags;
346 c.c_future->ff_features = merged;
347 flags->cf_flags = merged;
348 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200349 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100351 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200353 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900354 goto finally;
355 }
356
Victor Stinner14e461d2013-08-26 22:28:21 +0200357 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (c.c_st == NULL) {
359 if (!PyErr_Occurred())
360 PyErr_SetString(PyExc_SystemError, "no symtable");
361 goto finally;
362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Thomas Wouters1175c432006-02-27 22:49:54 +0000366 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 compiler_free(&c);
368 assert(co || PyErr_Occurred());
369 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370}
371
372PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200373PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
374 int optimize, PyArena *arena)
375{
376 PyObject *filename;
377 PyCodeObject *co;
378 filename = PyUnicode_DecodeFSDefault(filename_str);
379 if (filename == NULL)
380 return NULL;
381 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
382 Py_DECREF(filename);
383 return co;
384
385}
386
387PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388PyNode_Compile(struct _node *n, const char *filename)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyCodeObject *co = NULL;
391 mod_ty mod;
392 PyArena *arena = PyArena_New();
393 if (!arena)
394 return NULL;
395 mod = PyAST_FromNode(n, NULL, filename, arena);
396 if (mod)
397 co = PyAST_Compile(mod, filename, NULL, arena);
398 PyArena_Free(arena);
399 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000400}
401
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (c->c_st)
406 PySymtable_Free(c->c_st);
407 if (c->c_future)
408 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200409 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900410 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000412}
413
Guido van Rossum79f25d91997-04-29 20:08:16 +0000414static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_ssize_t i, n;
418 PyObject *v, *k;
419 PyObject *dict = PyDict_New();
420 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 n = PyList_Size(list);
423 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100424 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (!v) {
426 Py_DECREF(dict);
427 return NULL;
428 }
429 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300430 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(v);
432 Py_DECREF(dict);
433 return NULL;
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(v);
436 }
437 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438}
439
440/* Return new dict containing names from src that match scope(s).
441
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000442src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444values are integers, starting at offset and increasing by one for
445each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446*/
447
448static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100449dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700451 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500453 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 assert(offset >= 0);
456 if (dest == NULL)
457 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Meador Inge2ca63152012-07-18 14:20:11 -0500459 /* Sort the keys so that we have a deterministic order on the indexes
460 saved in the returned dictionary. These indexes are used as indexes
461 into the free and cell var storage. Therefore if they aren't
462 deterministic, then the generated bytecode is not deterministic.
463 */
464 sorted_keys = PyDict_Keys(src);
465 if (sorted_keys == NULL)
466 return NULL;
467 if (PyList_Sort(sorted_keys) != 0) {
468 Py_DECREF(sorted_keys);
469 return NULL;
470 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500471 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500472
473 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* XXX this should probably be a macro in symtable.h */
475 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500476 k = PyList_GET_ITEM(sorted_keys, key_i);
477 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 assert(PyLong_Check(v));
479 vi = PyLong_AS_LONG(v);
480 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300483 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_DECREF(dest);
487 return NULL;
488 }
489 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300490 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(item);
493 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
496 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
498 }
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000501}
502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503static void
504compiler_unit_check(struct compiler_unit *u)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 basicblock *block;
507 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700508 assert((uintptr_t)block != 0xcbcbcbcbU);
509 assert((uintptr_t)block != 0xfbfbfbfbU);
510 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (block->b_instr != NULL) {
512 assert(block->b_ialloc > 0);
513 assert(block->b_iused > 0);
514 assert(block->b_ialloc >= block->b_iused);
515 }
516 else {
517 assert (block->b_iused == 0);
518 assert (block->b_ialloc == 0);
519 }
520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521}
522
523static void
524compiler_unit_free(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 compiler_unit_check(u);
529 b = u->u_blocks;
530 while (b != NULL) {
531 if (b->b_instr)
532 PyObject_Free((void *)b->b_instr);
533 next = b->b_list;
534 PyObject_Free((void *)b);
535 b = next;
536 }
537 Py_CLEAR(u->u_ste);
538 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400539 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_CLEAR(u->u_consts);
541 Py_CLEAR(u->u_names);
542 Py_CLEAR(u->u_varnames);
543 Py_CLEAR(u->u_freevars);
544 Py_CLEAR(u->u_cellvars);
545 Py_CLEAR(u->u_private);
546 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547}
548
549static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100550compiler_enter_scope(struct compiler *c, identifier name,
551 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100554 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
557 struct compiler_unit));
558 if (!u) {
559 PyErr_NoMemory();
560 return 0;
561 }
562 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100563 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100565 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 u->u_kwonlyargcount = 0;
567 u->u_ste = PySymtable_Lookup(c->c_st, key);
568 if (!u->u_ste) {
569 compiler_unit_free(u);
570 return 0;
571 }
572 Py_INCREF(name);
573 u->u_name = name;
574 u->u_varnames = list2dict(u->u_ste->ste_varnames);
575 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
576 if (!u->u_varnames || !u->u_cellvars) {
577 compiler_unit_free(u);
578 return 0;
579 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000581 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300583 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 int res;
585 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200586 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 name = _PyUnicode_FromId(&PyId___class__);
588 if (!name) {
589 compiler_unit_free(u);
590 return 0;
591 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300592 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (res < 0) {
594 compiler_unit_free(u);
595 return 0;
596 }
597 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200600 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (!u->u_freevars) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_blocks = NULL;
607 u->u_nfblocks = 0;
608 u->u_firstlineno = lineno;
609 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000610 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_lineno_set = 0;
612 u->u_consts = PyDict_New();
613 if (!u->u_consts) {
614 compiler_unit_free(u);
615 return 0;
616 }
617 u->u_names = PyDict_New();
618 if (!u->u_names) {
619 compiler_unit_free(u);
620 return 0;
621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Push the old compiler_unit on the stack. */
626 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400627 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
629 Py_XDECREF(capsule);
630 compiler_unit_free(u);
631 return 0;
632 }
633 Py_DECREF(capsule);
634 u->u_private = c->u->u_private;
635 Py_XINCREF(u->u_private);
636 }
637 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100640
641 block = compiler_new_block(c);
642 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100644 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400646 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
647 if (!compiler_set_qualname(c))
648 return 0;
649 }
650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652}
653
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000654static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655compiler_exit_scope(struct compiler *c)
656{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100657 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 c->c_nestlevel--;
661 compiler_unit_free(c->u);
662 /* Restore c->u to the parent unit. */
663 n = PyList_GET_SIZE(c->c_stack) - 1;
664 if (n >= 0) {
665 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400666 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(c->u);
668 /* we are deleting from a list so this really shouldn't fail */
669 if (PySequence_DelItem(c->c_stack, n) < 0)
670 Py_FatalError("compiler_exit_scope()");
671 compiler_unit_check(c->u);
672 }
673 else
674 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678static int
679compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 _Py_static_string(dot_locals, ".<locals>");
683 Py_ssize_t stack_size;
684 struct compiler_unit *u = c->u;
685 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100686
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400689 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 if (stack_size > 1) {
691 int scope, force_global = 0;
692 struct compiler_unit *parent;
693 PyObject *mangled, *capsule;
694
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400695 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400696 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 assert(parent);
698
Yury Selivanov75445082015-05-11 22:57:16 -0400699 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
700 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
701 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 assert(u->u_name);
703 mangled = _Py_Mangle(parent->u_private, u->u_name);
704 if (!mangled)
705 return 0;
706 scope = PyST_GetScope(parent->u_ste, mangled);
707 Py_DECREF(mangled);
708 assert(scope != GLOBAL_IMPLICIT);
709 if (scope == GLOBAL_EXPLICIT)
710 force_global = 1;
711 }
712
713 if (!force_global) {
714 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400715 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400716 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
717 dot_locals_str = _PyUnicode_FromId(&dot_locals);
718 if (dot_locals_str == NULL)
719 return 0;
720 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
721 if (base == NULL)
722 return 0;
723 }
724 else {
725 Py_INCREF(parent->u_qualname);
726 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728 }
729 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 if (base != NULL) {
732 dot_str = _PyUnicode_FromId(&dot);
733 if (dot_str == NULL) {
734 Py_DECREF(base);
735 return 0;
736 }
737 name = PyUnicode_Concat(base, dot_str);
738 Py_DECREF(base);
739 if (name == NULL)
740 return 0;
741 PyUnicode_Append(&name, u->u_name);
742 if (name == NULL)
743 return 0;
744 }
745 else {
746 Py_INCREF(u->u_name);
747 name = u->u_name;
748 }
749 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100750
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400751 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100752}
753
Eric V. Smith235a6f02015-09-19 14:51:32 -0400754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755/* Allocate a new block and return a pointer to it.
756 Returns NULL on error.
757*/
758
759static basicblock *
760compiler_new_block(struct compiler *c)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 basicblock *b;
763 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 u = c->u;
766 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
767 if (b == NULL) {
768 PyErr_NoMemory();
769 return NULL;
770 }
771 memset((void *)b, 0, sizeof(basicblock));
772 /* Extend the singly linked list of blocks with new block. */
773 b->b_list = u->u_blocks;
774 u->u_blocks = b;
775 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779compiler_next_block(struct compiler *c)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 basicblock *block = compiler_new_block(c);
782 if (block == NULL)
783 return NULL;
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789static basicblock *
790compiler_use_next_block(struct compiler *c, basicblock *block)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(block != NULL);
793 c->u->u_curblock->b_next = block;
794 c->u->u_curblock = block;
795 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796}
797
798/* Returns the offset of the next instruction in the current block's
799 b_instr array. Resizes the b_instr as necessary.
800 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802
803static int
804compiler_next_instr(struct compiler *c, basicblock *b)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(b != NULL);
807 if (b->b_instr == NULL) {
808 b->b_instr = (struct instr *)PyObject_Malloc(
809 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
810 if (b->b_instr == NULL) {
811 PyErr_NoMemory();
812 return -1;
813 }
814 b->b_ialloc = DEFAULT_BLOCK_SIZE;
815 memset((char *)b->b_instr, 0,
816 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
817 }
818 else if (b->b_iused == b->b_ialloc) {
819 struct instr *tmp;
820 size_t oldsize, newsize;
821 oldsize = b->b_ialloc * sizeof(struct instr);
822 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000823
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700824 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_NoMemory();
826 return -1;
827 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (newsize == 0) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 b->b_ialloc <<= 1;
834 tmp = (struct instr *)PyObject_Realloc(
835 (void *)b->b_instr, newsize);
836 if (tmp == NULL) {
837 PyErr_NoMemory();
838 return -1;
839 }
840 b->b_instr = tmp;
841 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
842 }
843 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844}
845
Christian Heimes2202f872008-02-06 14:31:34 +0000846/* Set the i_lineno member of the instruction at offset off if the
847 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 already been set. If it has been set, the call has no effect.
849
Christian Heimes2202f872008-02-06 14:31:34 +0000850 The line number is reset in the following cases:
851 - when entering a new scope
852 - on each statement
853 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200854 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000855 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858static void
859compiler_set_lineno(struct compiler *c, int off)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 basicblock *b;
862 if (c->u->u_lineno_set)
863 return;
864 c->u->u_lineno_set = 1;
865 b = c->u->u_curblock;
866 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867}
868
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200869/* Return the stack effect of opcode with argument oparg.
870
871 Some opcodes have different stack effect when jump to the target and
872 when not jump. The 'jump' parameter specifies the case:
873
874 * 0 -- when not jump
875 * 1 -- when jump
876 * -1 -- maximal
877 */
878/* XXX Make the stack effect of WITH_CLEANUP_START and
879 WITH_CLEANUP_FINISH deterministic. */
880static int
881stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300884 case NOP:
885 case EXTENDED_ARG:
886 return 0;
887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case POP_TOP:
890 return -1;
891 case ROT_TWO:
892 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200893 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return 0;
895 case DUP_TOP:
896 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000897 case DUP_TOP_TWO:
898 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case UNARY_POSITIVE:
902 case UNARY_NEGATIVE:
903 case UNARY_NOT:
904 case UNARY_INVERT:
905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case SET_ADD:
908 case LIST_APPEND:
909 return -1;
910 case MAP_ADD:
911 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000912
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200913 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_POWER:
915 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400916 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_MODULO:
918 case BINARY_ADD:
919 case BINARY_SUBTRACT:
920 case BINARY_SUBSCR:
921 case BINARY_FLOOR_DIVIDE:
922 case BINARY_TRUE_DIVIDE:
923 return -1;
924 case INPLACE_FLOOR_DIVIDE:
925 case INPLACE_TRUE_DIVIDE:
926 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case INPLACE_ADD:
929 case INPLACE_SUBTRACT:
930 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400931 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case INPLACE_MODULO:
933 return -1;
934 case STORE_SUBSCR:
935 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case DELETE_SUBSCR:
937 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case BINARY_LSHIFT:
940 case BINARY_RSHIFT:
941 case BINARY_AND:
942 case BINARY_XOR:
943 case BINARY_OR:
944 return -1;
945 case INPLACE_POWER:
946 return -1;
947 case GET_ITER:
948 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case PRINT_EXPR:
951 return -1;
952 case LOAD_BUILD_CLASS:
953 return 1;
954 case INPLACE_LSHIFT:
955 case INPLACE_RSHIFT:
956 case INPLACE_AND:
957 case INPLACE_XOR:
958 case INPLACE_OR:
959 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* 1 in the normal flow.
963 * Restore the stack position and push 6 values before jumping to
964 * the handler if an exception be raised. */
965 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case RETURN_VALUE:
967 return -1;
968 case IMPORT_STAR:
969 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700970 case SETUP_ANNOTATIONS:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case YIELD_VALUE:
973 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500974 case YIELD_FROM:
975 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case POP_BLOCK:
977 return 0;
978 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_NAME:
982 return -1;
983 case DELETE_NAME:
984 return 0;
985 case UNPACK_SEQUENCE:
986 return oparg-1;
987 case UNPACK_EX:
988 return (oparg&0xFF) + (oparg>>8);
989 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200990 /* -1 at end of iterator, 1 if continue iterating. */
991 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case STORE_ATTR:
994 return -2;
995 case DELETE_ATTR:
996 return -1;
997 case STORE_GLOBAL:
998 return -1;
999 case DELETE_GLOBAL:
1000 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CONST:
1002 return 1;
1003 case LOAD_NAME:
1004 return 1;
1005 case BUILD_TUPLE:
1006 case BUILD_LIST:
1007 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001008 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001012 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001014 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001015 case BUILD_CONST_KEY_MAP:
1016 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case LOAD_ATTR:
1018 return 0;
1019 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001020 case IS_OP:
1021 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001023 case JUMP_IF_NOT_EXC_MATCH:
1024 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 case IMPORT_NAME:
1026 return -1;
1027 case IMPORT_FROM:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001030 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case JUMP_ABSOLUTE:
1033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001035 case JUMP_IF_TRUE_OR_POP:
1036 case JUMP_IF_FALSE_OR_POP:
1037 return jump ? 0 : -1;
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case POP_JUMP_IF_FALSE:
1040 case POP_JUMP_IF_TRUE:
1041 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_GLOBAL:
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001046 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* 0 in the normal flow.
1049 * Restore the stack position and push 6 values before jumping to
1050 * the handler if an exception be raised. */
1051 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001052 case RERAISE:
1053 return -3;
1054
1055 case WITH_EXCEPT_START:
1056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_FAST:
1059 return 1;
1060 case STORE_FAST:
1061 return -1;
1062 case DELETE_FAST:
1063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case RAISE_VARARGS:
1066 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001070 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001071 case CALL_METHOD:
1072 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg-1;
1075 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001076 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001077 case MAKE_FUNCTION:
1078 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1079 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case BUILD_SLICE:
1081 if (oparg == 3)
1082 return -2;
1083 else
1084 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case LOAD_CLOSURE:
1088 return 1;
1089 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001090 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return 1;
1092 case STORE_DEREF:
1093 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001094 case DELETE_DEREF:
1095 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096
1097 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case GET_AWAITABLE:
1099 return 0;
1100 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001101 /* 0 in the normal flow.
1102 * Restore the stack position to the position before the result
1103 * of __aenter__ and push 6 values before jumping to the handler
1104 * if an exception be raised. */
1105 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001106 case BEFORE_ASYNC_WITH:
1107 return 1;
1108 case GET_AITER:
1109 return 0;
1110 case GET_ANEXT:
1111 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001112 case GET_YIELD_FROM_ITER:
1113 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001114 case END_ASYNC_FOR:
1115 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001116 case FORMAT_VALUE:
1117 /* If there's a fmt_spec on the stack, we go from 2->1,
1118 else 1->1. */
1119 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001120 case LOAD_METHOD:
1121 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001122 case LOAD_ASSERTION_ERROR:
1123 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001124 case LIST_TO_TUPLE:
1125 return 0;
1126 case LIST_EXTEND:
1127 case SET_UPDATE:
1128 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001130 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Larry Hastings3a907972013-11-23 14:49:22 -08001132 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133}
1134
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001135int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001136PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1137{
1138 return stack_effect(opcode, oparg, jump);
1139}
1140
1141int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001142PyCompile_OpcodeStackEffect(int opcode, int oparg)
1143{
1144 return stack_effect(opcode, oparg, -1);
1145}
1146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147/* Add an opcode with no argument.
1148 Returns 0 on failure, 1 on success.
1149*/
1150
1151static int
1152compiler_addop(struct compiler *c, int opcode)
1153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 basicblock *b;
1155 struct instr *i;
1156 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001157 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001158 if (c->c_do_not_emit_bytecode) {
1159 return 1;
1160 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 off = compiler_next_instr(c, c->u->u_curblock);
1162 if (off < 0)
1163 return 0;
1164 b = c->u->u_curblock;
1165 i = &b->b_instr[off];
1166 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001167 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (opcode == RETURN_VALUE)
1169 b->b_return = 1;
1170 compiler_set_lineno(c, off);
1171 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172}
1173
Victor Stinnerf8e32212013-11-19 23:56:34 +01001174static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1176{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001177 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001180 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001182 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001184 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001185 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001186 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return -1;
1189 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001190 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 Py_DECREF(v);
1192 return -1;
1193 }
1194 Py_DECREF(v);
1195 }
1196 else
1197 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001198 return arg;
1199}
1200
INADA Naokic2e16072018-11-26 21:23:22 +09001201// Merge const *o* recursively and return constant key object.
1202static PyObject*
1203merge_consts_recursive(struct compiler *c, PyObject *o)
1204{
1205 // None and Ellipsis are singleton, and key is the singleton.
1206 // No need to merge object and key.
1207 if (o == Py_None || o == Py_Ellipsis) {
1208 Py_INCREF(o);
1209 return o;
1210 }
1211
1212 PyObject *key = _PyCode_ConstantKey(o);
1213 if (key == NULL) {
1214 return NULL;
1215 }
1216
1217 // t is borrowed reference
1218 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1219 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001221 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001222 Py_DECREF(key);
1223 return t;
1224 }
1225
INADA Naokif7e4d362018-11-29 00:58:46 +09001226 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001227 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001228 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001229 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001230 Py_ssize_t len = PyTuple_GET_SIZE(o);
1231 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001232 PyObject *item = PyTuple_GET_ITEM(o, i);
1233 PyObject *u = merge_consts_recursive(c, item);
1234 if (u == NULL) {
1235 Py_DECREF(key);
1236 return NULL;
1237 }
1238
1239 // See _PyCode_ConstantKey()
1240 PyObject *v; // borrowed
1241 if (PyTuple_CheckExact(u)) {
1242 v = PyTuple_GET_ITEM(u, 1);
1243 }
1244 else {
1245 v = u;
1246 }
1247 if (v != item) {
1248 Py_INCREF(v);
1249 PyTuple_SET_ITEM(o, i, v);
1250 Py_DECREF(item);
1251 }
1252
1253 Py_DECREF(u);
1254 }
1255 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001256 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001257 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001258 // constant keys.
1259 // See _PyCode_ConstantKey() for detail.
1260 assert(PyTuple_CheckExact(key));
1261 assert(PyTuple_GET_SIZE(key) == 2);
1262
1263 Py_ssize_t len = PySet_GET_SIZE(o);
1264 if (len == 0) { // empty frozenset should not be re-created.
1265 return key;
1266 }
1267 PyObject *tuple = PyTuple_New(len);
1268 if (tuple == NULL) {
1269 Py_DECREF(key);
1270 return NULL;
1271 }
1272 Py_ssize_t i = 0, pos = 0;
1273 PyObject *item;
1274 Py_hash_t hash;
1275 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1276 PyObject *k = merge_consts_recursive(c, item);
1277 if (k == NULL) {
1278 Py_DECREF(tuple);
1279 Py_DECREF(key);
1280 return NULL;
1281 }
1282 PyObject *u;
1283 if (PyTuple_CheckExact(k)) {
1284 u = PyTuple_GET_ITEM(k, 1);
1285 Py_INCREF(u);
1286 Py_DECREF(k);
1287 }
1288 else {
1289 u = k;
1290 }
1291 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1292 i++;
1293 }
1294
1295 // Instead of rewriting o, we create new frozenset and embed in the
1296 // key tuple. Caller should get merged frozenset from the key tuple.
1297 PyObject *new = PyFrozenSet_New(tuple);
1298 Py_DECREF(tuple);
1299 if (new == NULL) {
1300 Py_DECREF(key);
1301 return NULL;
1302 }
1303 assert(PyTuple_GET_ITEM(key, 1) == o);
1304 Py_DECREF(o);
1305 PyTuple_SET_ITEM(key, 1, new);
1306 }
INADA Naokic2e16072018-11-26 21:23:22 +09001307
1308 return key;
1309}
1310
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001311static Py_ssize_t
1312compiler_add_const(struct compiler *c, PyObject *o)
1313{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001314 if (c->c_do_not_emit_bytecode) {
1315 return 0;
1316 }
1317
INADA Naokic2e16072018-11-26 21:23:22 +09001318 PyObject *key = merge_consts_recursive(c, o);
1319 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001320 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001321 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001322
INADA Naokic2e16072018-11-26 21:23:22 +09001323 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1324 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326}
1327
1328static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001329compiler_addop_load_const(struct compiler *c, PyObject *o)
1330{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001331 if (c->c_do_not_emit_bytecode) {
1332 return 1;
1333 }
1334
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001335 Py_ssize_t arg = compiler_add_const(c, o);
1336 if (arg < 0)
1337 return 0;
1338 return compiler_addop_i(c, LOAD_CONST, arg);
1339}
1340
1341static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001345 if (c->c_do_not_emit_bytecode) {
1346 return 1;
1347 }
1348
Victor Stinnerad9a0662013-11-19 22:23:20 +01001349 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001351 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352 return compiler_addop_i(c, opcode, arg);
1353}
1354
1355static int
1356compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001359 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001360
1361 if (c->c_do_not_emit_bytecode) {
1362 return 1;
1363 }
1364
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1366 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001367 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 arg = compiler_add_o(c, dict, mangled);
1369 Py_DECREF(mangled);
1370 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001371 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001372 return compiler_addop_i(c, opcode, arg);
1373}
1374
1375/* Add an opcode with an integer argument.
1376 Returns 0 on failure, 1 on success.
1377*/
1378
1379static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001380compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 struct instr *i;
1383 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001384
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001385 if (c->c_do_not_emit_bytecode) {
1386 return 1;
1387 }
1388
Victor Stinner2ad474b2016-03-01 23:34:47 +01001389 /* oparg value is unsigned, but a signed C int is usually used to store
1390 it in the C code (like Python/ceval.c).
1391
1392 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1393
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001394 The argument of a concrete bytecode instruction is limited to 8-bit.
1395 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1396 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001397 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 off = compiler_next_instr(c, c->u->u_curblock);
1400 if (off < 0)
1401 return 0;
1402 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001403 i->i_opcode = opcode;
1404 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 compiler_set_lineno(c, off);
1406 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407}
1408
1409static int
1410compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 struct instr *i;
1413 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001415 if (c->c_do_not_emit_bytecode) {
1416 return 1;
1417 }
1418
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001419 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 assert(b != NULL);
1421 off = compiler_next_instr(c, c->u->u_curblock);
1422 if (off < 0)
1423 return 0;
1424 i = &c->u->u_curblock->b_instr[off];
1425 i->i_opcode = opcode;
1426 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (absolute)
1428 i->i_jabs = 1;
1429 else
1430 i->i_jrel = 1;
1431 compiler_set_lineno(c, off);
1432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433}
1434
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001435/* NEXT_BLOCK() creates an implicit jump from the current block
1436 to the new block.
1437
1438 The returns inside this macro make it impossible to decref objects
1439 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (compiler_next_block((C)) == NULL) \
1443 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
1446#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_addop((C), (OP))) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001451#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) { \
1453 compiler_exit_scope(c); \
1454 return 0; \
1455 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456}
1457
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001458#define ADDOP_LOAD_CONST(C, O) { \
1459 if (!compiler_addop_load_const((C), (O))) \
1460 return 0; \
1461}
1462
1463/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1464#define ADDOP_LOAD_CONST_NEW(C, O) { \
1465 PyObject *__new_const = (O); \
1466 if (__new_const == NULL) { \
1467 return 0; \
1468 } \
1469 if (!compiler_addop_load_const((C), __new_const)) { \
1470 Py_DECREF(__new_const); \
1471 return 0; \
1472 } \
1473 Py_DECREF(__new_const); \
1474}
1475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1478 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479}
1480
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001481/* Same as ADDOP_O, but steals a reference. */
1482#define ADDOP_N(C, OP, O, TYPE) { \
1483 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1484 Py_DECREF((O)); \
1485 return 0; \
1486 } \
1487 Py_DECREF((O)); \
1488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_i((C), (OP), (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_j((C), (OP), (O), 1)) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_addop_j((C), (OP), (O), 0)) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
Mark Shannon9af0e472020-01-14 10:12:45 +00001510
1511#define ADDOP_COMPARE(C, CMP) { \
1512 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1513 return 0; \
1514}
1515
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1517 the ASDL name to synthesize the name of the C type and the visit function.
1518*/
1519
1520#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!compiler_visit_ ## TYPE((C), (V))) \
1522 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523}
1524
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001525#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!compiler_visit_ ## TYPE((C), (V))) { \
1527 compiler_exit_scope(c); \
1528 return 0; \
1529 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001530}
1531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (!compiler_visit_slice((C), (V), (CTX))) \
1534 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535}
1536
1537#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 int _i; \
1539 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1540 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1541 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1542 if (!compiler_visit_ ## TYPE((C), elt)) \
1543 return 0; \
1544 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545}
1546
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001547#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 int _i; \
1549 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1550 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1551 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1552 if (!compiler_visit_ ## TYPE((C), elt)) { \
1553 compiler_exit_scope(c); \
1554 return 0; \
1555 } \
1556 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001557}
1558
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001559/* These macros allows to check only for errors and not emmit bytecode
1560 * while visiting nodes.
1561*/
1562
1563#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1564 c->c_do_not_emit_bytecode++;
1565
1566#define END_DO_NOT_EMIT_BYTECODE \
1567 c->c_do_not_emit_bytecode--; \
1568}
1569
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001570/* Search if variable annotations are present statically in a block. */
1571
1572static int
1573find_ann(asdl_seq *stmts)
1574{
1575 int i, j, res = 0;
1576 stmt_ty st;
1577
1578 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1579 st = (stmt_ty)asdl_seq_GET(stmts, i);
1580 switch (st->kind) {
1581 case AnnAssign_kind:
1582 return 1;
1583 case For_kind:
1584 res = find_ann(st->v.For.body) ||
1585 find_ann(st->v.For.orelse);
1586 break;
1587 case AsyncFor_kind:
1588 res = find_ann(st->v.AsyncFor.body) ||
1589 find_ann(st->v.AsyncFor.orelse);
1590 break;
1591 case While_kind:
1592 res = find_ann(st->v.While.body) ||
1593 find_ann(st->v.While.orelse);
1594 break;
1595 case If_kind:
1596 res = find_ann(st->v.If.body) ||
1597 find_ann(st->v.If.orelse);
1598 break;
1599 case With_kind:
1600 res = find_ann(st->v.With.body);
1601 break;
1602 case AsyncWith_kind:
1603 res = find_ann(st->v.AsyncWith.body);
1604 break;
1605 case Try_kind:
1606 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1607 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1608 st->v.Try.handlers, j);
1609 if (find_ann(handler->v.ExceptHandler.body)) {
1610 return 1;
1611 }
1612 }
1613 res = find_ann(st->v.Try.body) ||
1614 find_ann(st->v.Try.finalbody) ||
1615 find_ann(st->v.Try.orelse);
1616 break;
1617 default:
1618 res = 0;
1619 }
1620 if (res) {
1621 break;
1622 }
1623 }
1624 return res;
1625}
1626
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001627/*
1628 * Frame block handling functions
1629 */
1630
1631static int
1632compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001633 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001634{
1635 struct fblockinfo *f;
1636 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1637 PyErr_SetString(PyExc_SyntaxError,
1638 "too many statically nested blocks");
1639 return 0;
1640 }
1641 f = &c->u->u_fblock[c->u->u_nfblocks++];
1642 f->fb_type = t;
1643 f->fb_block = b;
1644 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001645 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001646 return 1;
1647}
1648
1649static void
1650compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1651{
1652 struct compiler_unit *u = c->u;
1653 assert(u->u_nfblocks > 0);
1654 u->u_nfblocks--;
1655 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1656 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1657}
1658
Mark Shannonfee55262019-11-21 09:11:43 +00001659static int
1660compiler_call_exit_with_nones(struct compiler *c) {
1661 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1662 ADDOP(c, DUP_TOP);
1663 ADDOP(c, DUP_TOP);
1664 ADDOP_I(c, CALL_FUNCTION, 3);
1665 return 1;
1666}
1667
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001668/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001669 * popping the blocks will be restored afterwards, unless another
1670 * return, break or continue is found. In which case, the TOS will
1671 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001672 */
1673static int
1674compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1675 int preserve_tos)
1676{
1677 switch (info->fb_type) {
1678 case WHILE_LOOP:
1679 return 1;
1680
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001681 case FOR_LOOP:
1682 /* Pop the iterator */
1683 if (preserve_tos) {
1684 ADDOP(c, ROT_TWO);
1685 }
1686 ADDOP(c, POP_TOP);
1687 return 1;
1688
1689 case EXCEPT:
1690 ADDOP(c, POP_BLOCK);
1691 return 1;
1692
1693 case FINALLY_TRY:
1694 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001695 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001696 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1697 return 0;
1698 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001699 }
Mark Shannon88dce262019-12-30 09:53:36 +00001700 /* Emit the finally block, restoring the line number when done */
1701 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001702 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001703 c->u->u_lineno = saved_lineno;
1704 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001705 if (preserve_tos) {
1706 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001707 }
1708 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001709
Mark Shannonfee55262019-11-21 09:11:43 +00001710 case FINALLY_END:
1711 if (preserve_tos) {
1712 ADDOP(c, ROT_FOUR);
1713 }
1714 ADDOP(c, POP_TOP);
1715 ADDOP(c, POP_TOP);
1716 ADDOP(c, POP_TOP);
1717 if (preserve_tos) {
1718 ADDOP(c, ROT_FOUR);
1719 }
1720 ADDOP(c, POP_EXCEPT);
1721 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001722
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001723 case WITH:
1724 case ASYNC_WITH:
1725 ADDOP(c, POP_BLOCK);
1726 if (preserve_tos) {
1727 ADDOP(c, ROT_TWO);
1728 }
Mark Shannonfee55262019-11-21 09:11:43 +00001729 if(!compiler_call_exit_with_nones(c)) {
1730 return 0;
1731 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001732 if (info->fb_type == ASYNC_WITH) {
1733 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001734 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001735 ADDOP(c, YIELD_FROM);
1736 }
Mark Shannonfee55262019-11-21 09:11:43 +00001737 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001738 return 1;
1739
1740 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001741 if (info->fb_datum) {
1742 ADDOP(c, POP_BLOCK);
1743 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 if (preserve_tos) {
1745 ADDOP(c, ROT_FOUR);
1746 }
Mark Shannonfee55262019-11-21 09:11:43 +00001747 ADDOP(c, POP_EXCEPT);
1748 if (info->fb_datum) {
1749 ADDOP_LOAD_CONST(c, Py_None);
1750 compiler_nameop(c, info->fb_datum, Store);
1751 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 }
Mark Shannonfee55262019-11-21 09:11:43 +00001753 return 1;
1754
1755 case POP_VALUE:
1756 if (preserve_tos) {
1757 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001758 }
Mark Shannonfee55262019-11-21 09:11:43 +00001759 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001760 return 1;
1761 }
1762 Py_UNREACHABLE();
1763}
1764
Mark Shannonfee55262019-11-21 09:11:43 +00001765/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1766static int
1767compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1768 if (c->u->u_nfblocks == 0) {
1769 return 1;
1770 }
1771 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1772 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1773 *loop = top;
1774 return 1;
1775 }
1776 struct fblockinfo copy = *top;
1777 c->u->u_nfblocks--;
1778 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1779 return 0;
1780 }
1781 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1782 return 0;
1783 }
1784 c->u->u_fblock[c->u->u_nfblocks] = copy;
1785 c->u->u_nfblocks++;
1786 return 1;
1787}
1788
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001789/* Compile a sequence of statements, checking for a docstring
1790 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
1792static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001793compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001795 int i = 0;
1796 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001797 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001798
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001799 /* Set current line number to the line number of first statement.
1800 This way line number for SETUP_ANNOTATIONS will always
1801 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301802 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001803 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1804 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001805 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001806 c->u->u_lineno = st->lineno;
1807 }
1808 /* Every annotated class and module should have __annotations__. */
1809 if (find_ann(stmts)) {
1810 ADDOP(c, SETUP_ANNOTATIONS);
1811 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001812 if (!asdl_seq_LEN(stmts))
1813 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001814 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001815 if (c->c_optimize < 2) {
1816 docstring = _PyAST_GetDocString(stmts);
1817 if (docstring) {
1818 i = 1;
1819 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1820 assert(st->kind == Expr_kind);
1821 VISIT(c, expr, st->v.Expr.value);
1822 if (!compiler_nameop(c, __doc__, Store))
1823 return 0;
1824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001826 for (; i < asdl_seq_LEN(stmts); i++)
1827 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829}
1830
1831static PyCodeObject *
1832compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyCodeObject *co;
1835 int addNone = 1;
1836 static PyObject *module;
1837 if (!module) {
1838 module = PyUnicode_InternFromString("<module>");
1839 if (!module)
1840 return NULL;
1841 }
1842 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001843 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 return NULL;
1845 switch (mod->kind) {
1846 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001847 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 compiler_exit_scope(c);
1849 return 0;
1850 }
1851 break;
1852 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001853 if (find_ann(mod->v.Interactive.body)) {
1854 ADDOP(c, SETUP_ANNOTATIONS);
1855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 c->c_interactive = 1;
1857 VISIT_SEQ_IN_SCOPE(c, stmt,
1858 mod->v.Interactive.body);
1859 break;
1860 case Expression_kind:
1861 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1862 addNone = 0;
1863 break;
1864 case Suite_kind:
1865 PyErr_SetString(PyExc_SystemError,
1866 "suite should not be possible");
1867 return 0;
1868 default:
1869 PyErr_Format(PyExc_SystemError,
1870 "module kind %d should not be possible",
1871 mod->kind);
1872 return 0;
1873 }
1874 co = assemble(c, addNone);
1875 compiler_exit_scope(c);
1876 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001877}
1878
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879/* The test for LOCAL must come before the test for FREE in order to
1880 handle classes where name is both local and free. The local var is
1881 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001882*/
1883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884static int
1885get_ref_type(struct compiler *c, PyObject *name)
1886{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001887 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001888 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001889 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001890 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001891 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (scope == 0) {
1893 char buf[350];
1894 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001895 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001897 PyUnicode_AsUTF8(name),
1898 PyUnicode_AsUTF8(c->u->u_name),
1899 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1902 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 );
1904 Py_FatalError(buf);
1905 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908}
1909
1910static int
1911compiler_lookup_arg(PyObject *dict, PyObject *name)
1912{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001913 PyObject *v;
1914 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001916 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001917 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918}
1919
1920static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001923 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001924 if (qualname == NULL)
1925 qualname = co->co_name;
1926
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001927 if (free) {
1928 for (i = 0; i < free; ++i) {
1929 /* Bypass com_addop_varname because it will generate
1930 LOAD_DEREF but LOAD_CLOSURE is needed.
1931 */
1932 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1933 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001935 /* Special case: If a class contains a method with a
1936 free variable that has the same name as a method,
1937 the name will be considered free *and* local in the
1938 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001939 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001940 */
1941 reftype = get_ref_type(c, name);
1942 if (reftype == CELL)
1943 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1944 else /* (reftype == FREE) */
1945 arg = compiler_lookup_arg(c->u->u_freevars, name);
1946 if (arg == -1) {
1947 fprintf(stderr,
1948 "lookup %s in %s %d %d\n"
1949 "freevars of %s: %s\n",
1950 PyUnicode_AsUTF8(PyObject_Repr(name)),
1951 PyUnicode_AsUTF8(c->u->u_name),
1952 reftype, arg,
1953 PyUnicode_AsUTF8(co->co_name),
1954 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1955 Py_FatalError("compiler_make_closure()");
1956 }
1957 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001959 flags |= 0x08;
1960 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001962 ADDOP_LOAD_CONST(c, (PyObject*)co);
1963 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
1969compiler_decorators(struct compiler *c, asdl_seq* decos)
1970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (!decos)
1974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1977 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1978 }
1979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980}
1981
1982static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001983compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001985{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001986 /* Push a dict of keyword-only default values.
1987
1988 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1989 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 int i;
1991 PyObject *keys = NULL;
1992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1994 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1995 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1996 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001997 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 if (!mangled) {
1999 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002001 if (keys == NULL) {
2002 keys = PyList_New(1);
2003 if (keys == NULL) {
2004 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002005 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 }
2007 PyList_SET_ITEM(keys, 0, mangled);
2008 }
2009 else {
2010 int res = PyList_Append(keys, mangled);
2011 Py_DECREF(mangled);
2012 if (res == -1) {
2013 goto error;
2014 }
2015 }
2016 if (!compiler_visit_expr(c, default_)) {
2017 goto error;
2018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
2020 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 if (keys != NULL) {
2022 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2023 PyObject *keys_tuple = PyList_AsTuple(keys);
2024 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002025 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002026 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002027 assert(default_count > 0);
2028 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002029 }
2030 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002032 }
2033
2034error:
2035 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002036 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002037}
2038
2039static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002040compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2041{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002042 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002043 return 1;
2044}
2045
2046static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002047compiler_visit_argannotation(struct compiler *c, identifier id,
2048 expr_ty annotation, PyObject *names)
2049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002051 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002052 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2053 VISIT(c, annexpr, annotation)
2054 }
2055 else {
2056 VISIT(c, expr, annotation);
2057 }
Victor Stinner065efc32014-02-18 22:07:56 +01002058 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002059 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002061 if (PyList_Append(names, mangled) < 0) {
2062 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002064 }
2065 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002068}
2069
2070static int
2071compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2072 PyObject *names)
2073{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 for (i = 0; i < asdl_seq_LEN(args); i++) {
2076 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002077 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 c,
2079 arg->arg,
2080 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002081 names))
2082 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002084 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002085}
2086
2087static int
2088compiler_visit_annotations(struct compiler *c, arguments_ty args,
2089 expr_ty returns)
2090{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002091 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002092 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002093
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002094 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 */
2096 static identifier return_str;
2097 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002098 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 names = PyList_New(0);
2100 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002101 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002103 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002105 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2106 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002107 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002108 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002109 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002111 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002113 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002114 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002115 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 if (!return_str) {
2119 return_str = PyUnicode_InternFromString("return");
2120 if (!return_str)
2121 goto error;
2122 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002123 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 goto error;
2125 }
2126
2127 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002129 PyObject *keytuple = PyList_AsTuple(names);
2130 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002131 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002132 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002133 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002135 else {
2136 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002137 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002138 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002139
2140error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002142 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002143}
2144
2145static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002146compiler_visit_defaults(struct compiler *c, arguments_ty args)
2147{
2148 VISIT_SEQ(c, expr, args->defaults);
2149 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2150 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151}
2152
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002153static Py_ssize_t
2154compiler_default_arguments(struct compiler *c, arguments_ty args)
2155{
2156 Py_ssize_t funcflags = 0;
2157 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002158 if (!compiler_visit_defaults(c, args))
2159 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002160 funcflags |= 0x01;
2161 }
2162 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002163 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002164 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002165 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002166 return -1;
2167 }
2168 else if (res > 0) {
2169 funcflags |= 0x02;
2170 }
2171 }
2172 return funcflags;
2173}
2174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175static int
Yury Selivanov75445082015-05-11 22:57:16 -04002176compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002179 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002180 arguments_ty args;
2181 expr_ty returns;
2182 identifier name;
2183 asdl_seq* decos;
2184 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002185 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002186 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002187 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002188 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189
Yury Selivanov75445082015-05-11 22:57:16 -04002190 if (is_async) {
2191 assert(s->kind == AsyncFunctionDef_kind);
2192
2193 args = s->v.AsyncFunctionDef.args;
2194 returns = s->v.AsyncFunctionDef.returns;
2195 decos = s->v.AsyncFunctionDef.decorator_list;
2196 name = s->v.AsyncFunctionDef.name;
2197 body = s->v.AsyncFunctionDef.body;
2198
2199 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2200 } else {
2201 assert(s->kind == FunctionDef_kind);
2202
2203 args = s->v.FunctionDef.args;
2204 returns = s->v.FunctionDef.returns;
2205 decos = s->v.FunctionDef.decorator_list;
2206 name = s->v.FunctionDef.name;
2207 body = s->v.FunctionDef.body;
2208
2209 scope_type = COMPILER_SCOPE_FUNCTION;
2210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (!compiler_decorators(c, decos))
2213 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002214
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002215 firstlineno = s->lineno;
2216 if (asdl_seq_LEN(decos)) {
2217 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2218 }
2219
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002220 funcflags = compiler_default_arguments(c, args);
2221 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002223 }
2224
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002225 annotations = compiler_visit_annotations(c, args, returns);
2226 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002227 return 0;
2228 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002229 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002230 funcflags |= 0x04;
2231 }
2232
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002233 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002234 return 0;
2235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236
INADA Naokicb41b272017-02-23 00:31:59 +09002237 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002238 if (c->c_optimize < 2) {
2239 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002240 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002241 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 compiler_exit_scope(c);
2243 return 0;
2244 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002247 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002249 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002251 qualname = c->u->u_qualname;
2252 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002254 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002255 Py_XDECREF(qualname);
2256 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002258 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002260 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002261 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 /* decorators */
2265 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2266 ADDOP_I(c, CALL_FUNCTION, 1);
2267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268
Yury Selivanov75445082015-05-11 22:57:16 -04002269 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270}
2271
2272static int
2273compiler_class(struct compiler *c, stmt_ty s)
2274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyCodeObject *co;
2276 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002277 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 if (!compiler_decorators(c, decos))
2281 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002282
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002283 firstlineno = s->lineno;
2284 if (asdl_seq_LEN(decos)) {
2285 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2286 }
2287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* ultimately generate code for:
2289 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2290 where:
2291 <func> is a function/closure created from the class body;
2292 it has a single argument (__locals__) where the dict
2293 (or MutableSequence) representing the locals is passed
2294 <name> is the class name
2295 <bases> is the positional arguments and *varargs argument
2296 <keywords> is the keyword arguments and **kwds argument
2297 This borrows from compiler_call.
2298 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002301 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002302 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 return 0;
2304 /* this block represents what we do in the new scope */
2305 {
2306 /* use the class name for name mangling */
2307 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002308 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* load (global) __name__ ... */
2310 str = PyUnicode_InternFromString("__name__");
2311 if (!str || !compiler_nameop(c, str, Load)) {
2312 Py_XDECREF(str);
2313 compiler_exit_scope(c);
2314 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002315 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 Py_DECREF(str);
2317 /* ... and store it as __module__ */
2318 str = PyUnicode_InternFromString("__module__");
2319 if (!str || !compiler_nameop(c, str, Store)) {
2320 Py_XDECREF(str);
2321 compiler_exit_scope(c);
2322 return 0;
2323 }
2324 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002325 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002326 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002327 str = PyUnicode_InternFromString("__qualname__");
2328 if (!str || !compiler_nameop(c, str, Store)) {
2329 Py_XDECREF(str);
2330 compiler_exit_scope(c);
2331 return 0;
2332 }
2333 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002335 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 compiler_exit_scope(c);
2337 return 0;
2338 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002339 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002340 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002341 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002342 str = PyUnicode_InternFromString("__class__");
2343 if (str == NULL) {
2344 compiler_exit_scope(c);
2345 return 0;
2346 }
2347 i = compiler_lookup_arg(c->u->u_cellvars, str);
2348 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002349 if (i < 0) {
2350 compiler_exit_scope(c);
2351 return 0;
2352 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002353 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002357 str = PyUnicode_InternFromString("__classcell__");
2358 if (!str || !compiler_nameop(c, str, Store)) {
2359 Py_XDECREF(str);
2360 compiler_exit_scope(c);
2361 return 0;
2362 }
2363 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002365 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002366 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002367 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002368 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002369 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002370 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* create the code object */
2372 co = assemble(c, 1);
2373 }
2374 /* leave the new scope */
2375 compiler_exit_scope(c);
2376 if (co == NULL)
2377 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* 2. load the 'build_class' function */
2380 ADDOP(c, LOAD_BUILD_CLASS);
2381
2382 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002383 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 Py_DECREF(co);
2385
2386 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002387 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388
2389 /* 5. generate the rest of the code for the call */
2390 if (!compiler_call_helper(c, 2,
2391 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002392 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return 0;
2394
2395 /* 6. apply decorators */
2396 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2397 ADDOP_I(c, CALL_FUNCTION, 1);
2398 }
2399
2400 /* 7. store into <name> */
2401 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2402 return 0;
2403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404}
2405
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002406/* Return 0 if the expression is a constant value except named singletons.
2407 Return 1 otherwise. */
2408static int
2409check_is_arg(expr_ty e)
2410{
2411 if (e->kind != Constant_kind) {
2412 return 1;
2413 }
2414 PyObject *value = e->v.Constant.value;
2415 return (value == Py_None
2416 || value == Py_False
2417 || value == Py_True
2418 || value == Py_Ellipsis);
2419}
2420
2421/* Check operands of identity chacks ("is" and "is not").
2422 Emit a warning if any operand is a constant except named singletons.
2423 Return 0 on error.
2424 */
2425static int
2426check_compare(struct compiler *c, expr_ty e)
2427{
2428 Py_ssize_t i, n;
2429 int left = check_is_arg(e->v.Compare.left);
2430 n = asdl_seq_LEN(e->v.Compare.ops);
2431 for (i = 0; i < n; i++) {
2432 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2433 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2434 if (op == Is || op == IsNot) {
2435 if (!right || !left) {
2436 const char *msg = (op == Is)
2437 ? "\"is\" with a literal. Did you mean \"==\"?"
2438 : "\"is not\" with a literal. Did you mean \"!=\"?";
2439 return compiler_warn(c, msg);
2440 }
2441 }
2442 left = right;
2443 }
2444 return 1;
2445}
2446
Mark Shannon9af0e472020-01-14 10:12:45 +00002447static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002448{
Mark Shannon9af0e472020-01-14 10:12:45 +00002449 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002450 switch (op) {
2451 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002452 cmp = Py_EQ;
2453 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002454 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002455 cmp = Py_NE;
2456 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002457 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002458 cmp = Py_LT;
2459 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002460 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002461 cmp = Py_LE;
2462 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002464 cmp = Py_GT;
2465 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002466 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002467 cmp = Py_GE;
2468 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002470 ADDOP_I(c, IS_OP, 0);
2471 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002472 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002473 ADDOP_I(c, IS_OP, 1);
2474 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002475 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002476 ADDOP_I(c, CONTAINS_OP, 0);
2477 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002478 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002479 ADDOP_I(c, CONTAINS_OP, 1);
2480 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002482 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002484 ADDOP_I(c, COMPARE_OP, cmp);
2485 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002486}
2487
Mark Shannon9af0e472020-01-14 10:12:45 +00002488
2489
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002490static int
2491compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2492{
2493 switch (e->kind) {
2494 case UnaryOp_kind:
2495 if (e->v.UnaryOp.op == Not)
2496 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2497 /* fallback to general implementation */
2498 break;
2499 case BoolOp_kind: {
2500 asdl_seq *s = e->v.BoolOp.values;
2501 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2502 assert(n >= 0);
2503 int cond2 = e->v.BoolOp.op == Or;
2504 basicblock *next2 = next;
2505 if (!cond2 != !cond) {
2506 next2 = compiler_new_block(c);
2507 if (next2 == NULL)
2508 return 0;
2509 }
2510 for (i = 0; i < n; ++i) {
2511 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2512 return 0;
2513 }
2514 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2515 return 0;
2516 if (next2 != next)
2517 compiler_use_next_block(c, next2);
2518 return 1;
2519 }
2520 case IfExp_kind: {
2521 basicblock *end, *next2;
2522 end = compiler_new_block(c);
2523 if (end == NULL)
2524 return 0;
2525 next2 = compiler_new_block(c);
2526 if (next2 == NULL)
2527 return 0;
2528 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2529 return 0;
2530 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2531 return 0;
2532 ADDOP_JREL(c, JUMP_FORWARD, end);
2533 compiler_use_next_block(c, next2);
2534 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2535 return 0;
2536 compiler_use_next_block(c, end);
2537 return 1;
2538 }
2539 case Compare_kind: {
2540 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2541 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002542 if (!check_compare(c, e)) {
2543 return 0;
2544 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002545 basicblock *cleanup = compiler_new_block(c);
2546 if (cleanup == NULL)
2547 return 0;
2548 VISIT(c, expr, e->v.Compare.left);
2549 for (i = 0; i < n; i++) {
2550 VISIT(c, expr,
2551 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2552 ADDOP(c, DUP_TOP);
2553 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002554 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002555 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2556 NEXT_BLOCK(c);
2557 }
2558 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002559 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002560 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2561 basicblock *end = compiler_new_block(c);
2562 if (end == NULL)
2563 return 0;
2564 ADDOP_JREL(c, JUMP_FORWARD, end);
2565 compiler_use_next_block(c, cleanup);
2566 ADDOP(c, POP_TOP);
2567 if (!cond) {
2568 ADDOP_JREL(c, JUMP_FORWARD, next);
2569 }
2570 compiler_use_next_block(c, end);
2571 return 1;
2572 }
2573 /* fallback to general implementation */
2574 break;
2575 }
2576 default:
2577 /* fallback to general implementation */
2578 break;
2579 }
2580
2581 /* general implementation */
2582 VISIT(c, expr, e);
2583 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2584 return 1;
2585}
2586
2587static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002588compiler_ifexp(struct compiler *c, expr_ty e)
2589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 basicblock *end, *next;
2591
2592 assert(e->kind == IfExp_kind);
2593 end = compiler_new_block(c);
2594 if (end == NULL)
2595 return 0;
2596 next = compiler_new_block(c);
2597 if (next == NULL)
2598 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2600 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 VISIT(c, expr, e->v.IfExp.body);
2602 ADDOP_JREL(c, JUMP_FORWARD, end);
2603 compiler_use_next_block(c, next);
2604 VISIT(c, expr, e->v.IfExp.orelse);
2605 compiler_use_next_block(c, end);
2606 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002607}
2608
2609static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610compiler_lambda(struct compiler *c, expr_ty e)
2611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002613 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002615 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 arguments_ty args = e->v.Lambda.args;
2617 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (!name) {
2620 name = PyUnicode_InternFromString("<lambda>");
2621 if (!name)
2622 return 0;
2623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002625 funcflags = compiler_default_arguments(c, args);
2626 if (funcflags == -1) {
2627 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002629
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002630 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002631 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 /* Make None the first constant, so the lambda can't have a
2635 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002636 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002640 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2642 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2643 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002644 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 }
2646 else {
2647 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002648 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002650 qualname = c->u->u_qualname;
2651 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002653 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002656 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002657 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 Py_DECREF(co);
2659
2660 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661}
2662
2663static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664compiler_if(struct compiler *c, stmt_ty s)
2665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 basicblock *end, *next;
2667 int constant;
2668 assert(s->kind == If_kind);
2669 end = compiler_new_block(c);
2670 if (end == NULL)
2671 return 0;
2672
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002673 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002674 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 * constant = 1: "if 1", "if 2", ...
2676 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002677 if (constant == 0) {
2678 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002680 END_DO_NOT_EMIT_BYTECODE
2681 if (s->v.If.orelse) {
2682 VISIT_SEQ(c, stmt, s->v.If.orelse);
2683 }
2684 } else if (constant == 1) {
2685 VISIT_SEQ(c, stmt, s->v.If.body);
2686 if (s->v.If.orelse) {
2687 BEGIN_DO_NOT_EMIT_BYTECODE
2688 VISIT_SEQ(c, stmt, s->v.If.orelse);
2689 END_DO_NOT_EMIT_BYTECODE
2690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002692 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 next = compiler_new_block(c);
2694 if (next == NULL)
2695 return 0;
2696 }
Mark Shannonfee55262019-11-21 09:11:43 +00002697 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002699 }
2700 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002701 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002702 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002704 if (asdl_seq_LEN(s->v.If.orelse)) {
2705 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 compiler_use_next_block(c, next);
2707 VISIT_SEQ(c, stmt, s->v.If.orelse);
2708 }
2709 }
2710 compiler_use_next_block(c, end);
2711 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712}
2713
2714static int
2715compiler_for(struct compiler *c, stmt_ty s)
2716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 start = compiler_new_block(c);
2720 cleanup = compiler_new_block(c);
2721 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002722 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002724 }
2725 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 VISIT(c, expr, s->v.For.iter);
2729 ADDOP(c, GET_ITER);
2730 compiler_use_next_block(c, start);
2731 ADDOP_JREL(c, FOR_ITER, cleanup);
2732 VISIT(c, expr, s->v.For.target);
2733 VISIT_SEQ(c, stmt, s->v.For.body);
2734 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2735 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002736
2737 compiler_pop_fblock(c, FOR_LOOP, start);
2738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 VISIT_SEQ(c, stmt, s->v.For.orelse);
2740 compiler_use_next_block(c, end);
2741 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742}
2743
Yury Selivanov75445082015-05-11 22:57:16 -04002744
2745static int
2746compiler_async_for(struct compiler *c, stmt_ty s)
2747{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002748 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002749 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2750 c->u->u_ste->ste_coroutine = 1;
2751 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002752 return compiler_error(c, "'async for' outside async function");
2753 }
2754
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002755 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002756 except = compiler_new_block(c);
2757 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002758
Mark Shannonfee55262019-11-21 09:11:43 +00002759 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002760 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002761 }
Yury Selivanov75445082015-05-11 22:57:16 -04002762 VISIT(c, expr, s->v.AsyncFor.iter);
2763 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002764
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002765 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002766 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002767 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002768 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002769 /* SETUP_FINALLY to guard the __anext__ call */
2770 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002771 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002772 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002773 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002774 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002775
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002776 /* Success block for __anext__ */
2777 VISIT(c, expr, s->v.AsyncFor.target);
2778 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2779 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2780
2781 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002782
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002783 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002784 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002785 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002786
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002787 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002788 VISIT_SEQ(c, stmt, s->v.For.orelse);
2789
2790 compiler_use_next_block(c, end);
2791
2792 return 1;
2793}
2794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795static int
2796compiler_while(struct compiler *c, stmt_ty s)
2797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002799 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002802 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002803 // Push a dummy block so the VISIT_SEQ knows that we are
2804 // inside a while loop so it can correctly evaluate syntax
2805 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002806 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002807 return 0;
2808 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002809 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002810 // Remove the dummy block now that is not needed.
2811 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002812 END_DO_NOT_EMIT_BYTECODE
2813 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 return 1;
2817 }
2818 loop = compiler_new_block(c);
2819 end = compiler_new_block(c);
2820 if (constant == -1) {
2821 anchor = compiler_new_block(c);
2822 if (anchor == NULL)
2823 return 0;
2824 }
2825 if (loop == NULL || end == NULL)
2826 return 0;
2827 if (s->v.While.orelse) {
2828 orelse = compiler_new_block(c);
2829 if (orelse == NULL)
2830 return 0;
2831 }
2832 else
2833 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002836 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 return 0;
2838 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002839 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2840 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 }
2842 VISIT_SEQ(c, stmt, s->v.While.body);
2843 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* XXX should the two POP instructions be in a separate block
2846 if there is no else clause ?
2847 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002849 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002851 compiler_pop_fblock(c, WHILE_LOOP, loop);
2852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 if (orelse != NULL) /* what if orelse is just pass? */
2854 VISIT_SEQ(c, stmt, s->v.While.orelse);
2855 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858}
2859
2860static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002861compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002863 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002864 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002865 if (c->u->u_ste->ste_type != FunctionBlock)
2866 return compiler_error(c, "'return' outside function");
2867 if (s->v.Return.value != NULL &&
2868 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2869 {
2870 return compiler_error(
2871 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873 if (preserve_tos) {
2874 VISIT(c, expr, s->v.Return.value);
2875 }
Mark Shannonfee55262019-11-21 09:11:43 +00002876 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2877 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002878 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002879 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002880 }
2881 else if (!preserve_tos) {
2882 VISIT(c, expr, s->v.Return.value);
2883 }
2884 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887}
2888
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002889static int
2890compiler_break(struct compiler *c)
2891{
Mark Shannonfee55262019-11-21 09:11:43 +00002892 struct fblockinfo *loop = NULL;
2893 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2894 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895 }
Mark Shannonfee55262019-11-21 09:11:43 +00002896 if (loop == NULL) {
2897 return compiler_error(c, "'break' outside loop");
2898 }
2899 if (!compiler_unwind_fblock(c, loop, 0)) {
2900 return 0;
2901 }
2902 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2903 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002904}
2905
2906static int
2907compiler_continue(struct compiler *c)
2908{
Mark Shannonfee55262019-11-21 09:11:43 +00002909 struct fblockinfo *loop = NULL;
2910 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2911 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002912 }
Mark Shannonfee55262019-11-21 09:11:43 +00002913 if (loop == NULL) {
2914 return compiler_error(c, "'continue' not properly in loop");
2915 }
2916 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2917 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002918}
2919
2920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922
2923 SETUP_FINALLY L
2924 <code for body>
2925 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002926 <code for finalbody>
2927 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002928 L:
2929 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002930 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932 The special instructions use the block stack. Each block
2933 stack entry contains the instruction that created it (here
2934 SETUP_FINALLY), the level of the value stack at the time the
2935 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 Pushes the current value stack level and the label
2939 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002944 when a SETUP_FINALLY entry is found, the raised and the caught
2945 exceptions are pushed onto the value stack (and the exception
2946 condition is cleared), and the interpreter jumps to the label
2947 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948*/
2949
2950static int
2951compiler_try_finally(struct compiler *c, stmt_ty s)
2952{
Mark Shannonfee55262019-11-21 09:11:43 +00002953 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 body = compiler_new_block(c);
2956 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002957 exit = compiler_new_block(c);
2958 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002961 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 ADDOP_JREL(c, SETUP_FINALLY, end);
2963 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002964 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002966 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2967 if (!compiler_try_except(c, s))
2968 return 0;
2969 }
2970 else {
2971 VISIT_SEQ(c, stmt, s->v.Try.body);
2972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002974 compiler_pop_fblock(c, FINALLY_TRY, body);
2975 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2976 ADDOP_JREL(c, JUMP_FORWARD, exit);
2977 /* `finally` block */
2978 compiler_use_next_block(c, end);
2979 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2980 return 0;
2981 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2982 compiler_pop_fblock(c, FINALLY_END, end);
2983 ADDOP(c, RERAISE);
2984 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986}
2987
2988/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002989 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 (The contents of the value stack is shown in [], with the top
2991 at the right; 'tb' is trace-back info, 'val' the exception's
2992 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993
2994 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002995 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 [] <code for S>
2997 [] POP_BLOCK
2998 [] JUMP_FORWARD L0
2999
3000 [tb, val, exc] L1: DUP )
3001 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003002 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 [tb, val, exc] POP
3004 [tb, val] <assign to V1> (or POP if no V1)
3005 [tb] POP
3006 [] <code for S1>
3007 JUMP_FORWARD L0
3008
3009 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 .............................etc.......................
3011
Mark Shannonfee55262019-11-21 09:11:43 +00003012 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013
3014 [] L0: <next statement>
3015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 Of course, parts are not generated if Vi or Ei is not present.
3017*/
3018static int
3019compiler_try_except(struct compiler *c, stmt_ty s)
3020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003022 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 body = compiler_new_block(c);
3025 except = compiler_new_block(c);
3026 orelse = compiler_new_block(c);
3027 end = compiler_new_block(c);
3028 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3029 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003030 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003032 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003034 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 ADDOP(c, POP_BLOCK);
3036 compiler_pop_fblock(c, EXCEPT, body);
3037 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003038 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 compiler_use_next_block(c, except);
3040 for (i = 0; i < n; i++) {
3041 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003042 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 if (!handler->v.ExceptHandler.type && i < n-1)
3044 return compiler_error(c, "default 'except:' must be last");
3045 c->u->u_lineno_set = 0;
3046 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003047 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 except = compiler_new_block(c);
3049 if (except == NULL)
3050 return 0;
3051 if (handler->v.ExceptHandler.type) {
3052 ADDOP(c, DUP_TOP);
3053 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003054 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 }
3056 ADDOP(c, POP_TOP);
3057 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003059
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003060 cleanup_end = compiler_new_block(c);
3061 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003062 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003063 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003064 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003065
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003066 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3067 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 /*
3070 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003071 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003073 try:
3074 # body
3075 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003076 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003077 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003078 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 /* second try: */
3081 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3082 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003083 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 /* second # body */
3087 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003088 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003089 ADDOP(c, POP_BLOCK);
3090 ADDOP(c, POP_EXCEPT);
3091 /* name = None; del name */
3092 ADDOP_LOAD_CONST(c, Py_None);
3093 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3094 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3095 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096
Mark Shannonfee55262019-11-21 09:11:43 +00003097 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003098 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003100 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003101 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104
Mark Shannonfee55262019-11-21 09:11:43 +00003105 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 }
3107 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003108 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003110 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003111 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003112 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113
Guido van Rossumb940e112007-01-10 16:19:56 +00003114 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 ADDOP(c, POP_TOP);
3116 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003117 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003118 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003120 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003121 ADDOP(c, POP_EXCEPT);
3122 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 compiler_use_next_block(c, except);
3125 }
Mark Shannonfee55262019-11-21 09:11:43 +00003126 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003128 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 compiler_use_next_block(c, end);
3130 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131}
3132
3133static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003134compiler_try(struct compiler *c, stmt_ty s) {
3135 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3136 return compiler_try_finally(c, s);
3137 else
3138 return compiler_try_except(c, s);
3139}
3140
3141
3142static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143compiler_import_as(struct compiler *c, identifier name, identifier asname)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 /* The IMPORT_NAME opcode was already generated. This function
3146 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003149 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003151 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3152 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003153 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003154 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003155 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003157 while (1) {
3158 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003160 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003161 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003162 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003163 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003165 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003166 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003167 if (dot == -1) {
3168 break;
3169 }
3170 ADDOP(c, ROT_TWO);
3171 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003173 if (!compiler_nameop(c, asname, Store)) {
3174 return 0;
3175 }
3176 ADDOP(c, POP_TOP);
3177 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 }
3179 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180}
3181
3182static int
3183compiler_import(struct compiler *c, stmt_ty s)
3184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 /* The Import node stores a module name like a.b.c as a single
3186 string. This is convenient for all cases except
3187 import a.b.c as d
3188 where we need to parse that string to extract the individual
3189 module names.
3190 XXX Perhaps change the representation to make this case simpler?
3191 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003192 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 for (i = 0; i < n; i++) {
3195 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3196 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003198 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3199 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 if (alias->asname) {
3203 r = compiler_import_as(c, alias->name, alias->asname);
3204 if (!r)
3205 return r;
3206 }
3207 else {
3208 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003209 Py_ssize_t dot = PyUnicode_FindChar(
3210 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003211 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003212 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003213 if (tmp == NULL)
3214 return 0;
3215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003217 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 Py_DECREF(tmp);
3219 }
3220 if (!r)
3221 return r;
3222 }
3223 }
3224 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225}
3226
3227static int
3228compiler_from_import(struct compiler *c, stmt_ty s)
3229{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003230 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003231 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (!empty_string) {
3235 empty_string = PyUnicode_FromString("");
3236 if (!empty_string)
3237 return 0;
3238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003240 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003241
3242 names = PyTuple_New(n);
3243 if (!names)
3244 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 /* build up the names */
3247 for (i = 0; i < n; i++) {
3248 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3249 Py_INCREF(alias->name);
3250 PyTuple_SET_ITEM(names, i, alias->name);
3251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003254 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 Py_DECREF(names);
3256 return compiler_error(c, "from __future__ imports must occur "
3257 "at the beginning of the file");
3258 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003259 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 if (s->v.ImportFrom.module) {
3262 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3263 }
3264 else {
3265 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3266 }
3267 for (i = 0; i < n; i++) {
3268 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3269 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003271 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 assert(n == 1);
3273 ADDOP(c, IMPORT_STAR);
3274 return 1;
3275 }
3276
3277 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3278 store_name = alias->name;
3279 if (alias->asname)
3280 store_name = alias->asname;
3281
3282 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 return 0;
3284 }
3285 }
3286 /* remove imported module */
3287 ADDOP(c, POP_TOP);
3288 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289}
3290
3291static int
3292compiler_assert(struct compiler *c, stmt_ty s)
3293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295
Georg Brandl8334fd92010-12-04 10:26:46 +00003296 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003299 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3300 {
3301 if (!compiler_warn(c, "assertion is always true, "
3302 "perhaps remove parentheses?"))
3303 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003304 return 0;
3305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 end = compiler_new_block(c);
3308 if (end == NULL)
3309 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003310 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3311 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003312 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 if (s->v.Assert.msg) {
3314 VISIT(c, expr, s->v.Assert.msg);
3315 ADDOP_I(c, CALL_FUNCTION, 1);
3316 }
3317 ADDOP_I(c, RAISE_VARARGS, 1);
3318 compiler_use_next_block(c, end);
3319 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320}
3321
3322static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003323compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3324{
3325 if (c->c_interactive && c->c_nestlevel <= 1) {
3326 VISIT(c, expr, value);
3327 ADDOP(c, PRINT_EXPR);
3328 return 1;
3329 }
3330
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003331 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003332 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003333 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003334 }
3335
3336 VISIT(c, expr, value);
3337 ADDOP(c, POP_TOP);
3338 return 1;
3339}
3340
3341static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342compiler_visit_stmt(struct compiler *c, stmt_ty s)
3343{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003344 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 /* Always assign a lineno to the next instruction for a stmt. */
3347 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003348 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 switch (s->kind) {
3352 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003353 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 case ClassDef_kind:
3355 return compiler_class(c, s);
3356 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003357 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 case Delete_kind:
3359 VISIT_SEQ(c, expr, s->v.Delete.targets)
3360 break;
3361 case Assign_kind:
3362 n = asdl_seq_LEN(s->v.Assign.targets);
3363 VISIT(c, expr, s->v.Assign.value);
3364 for (i = 0; i < n; i++) {
3365 if (i < n - 1)
3366 ADDOP(c, DUP_TOP);
3367 VISIT(c, expr,
3368 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3369 }
3370 break;
3371 case AugAssign_kind:
3372 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003373 case AnnAssign_kind:
3374 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 case For_kind:
3376 return compiler_for(c, s);
3377 case While_kind:
3378 return compiler_while(c, s);
3379 case If_kind:
3380 return compiler_if(c, s);
3381 case Raise_kind:
3382 n = 0;
3383 if (s->v.Raise.exc) {
3384 VISIT(c, expr, s->v.Raise.exc);
3385 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003386 if (s->v.Raise.cause) {
3387 VISIT(c, expr, s->v.Raise.cause);
3388 n++;
3389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003391 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003393 case Try_kind:
3394 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 case Assert_kind:
3396 return compiler_assert(c, s);
3397 case Import_kind:
3398 return compiler_import(c, s);
3399 case ImportFrom_kind:
3400 return compiler_from_import(c, s);
3401 case Global_kind:
3402 case Nonlocal_kind:
3403 break;
3404 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003405 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 case Pass_kind:
3407 break;
3408 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003409 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 case Continue_kind:
3411 return compiler_continue(c);
3412 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003413 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003414 case AsyncFunctionDef_kind:
3415 return compiler_function(c, s, 1);
3416 case AsyncWith_kind:
3417 return compiler_async_with(c, s, 0);
3418 case AsyncFor_kind:
3419 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 }
Yury Selivanov75445082015-05-11 22:57:16 -04003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423}
3424
3425static int
3426unaryop(unaryop_ty op)
3427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 switch (op) {
3429 case Invert:
3430 return UNARY_INVERT;
3431 case Not:
3432 return UNARY_NOT;
3433 case UAdd:
3434 return UNARY_POSITIVE;
3435 case USub:
3436 return UNARY_NEGATIVE;
3437 default:
3438 PyErr_Format(PyExc_SystemError,
3439 "unary op %d should not be possible", op);
3440 return 0;
3441 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003442}
3443
3444static int
3445binop(struct compiler *c, operator_ty op)
3446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 switch (op) {
3448 case Add:
3449 return BINARY_ADD;
3450 case Sub:
3451 return BINARY_SUBTRACT;
3452 case Mult:
3453 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003454 case MatMult:
3455 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 case Div:
3457 return BINARY_TRUE_DIVIDE;
3458 case Mod:
3459 return BINARY_MODULO;
3460 case Pow:
3461 return BINARY_POWER;
3462 case LShift:
3463 return BINARY_LSHIFT;
3464 case RShift:
3465 return BINARY_RSHIFT;
3466 case BitOr:
3467 return BINARY_OR;
3468 case BitXor:
3469 return BINARY_XOR;
3470 case BitAnd:
3471 return BINARY_AND;
3472 case FloorDiv:
3473 return BINARY_FLOOR_DIVIDE;
3474 default:
3475 PyErr_Format(PyExc_SystemError,
3476 "binary op %d should not be possible", op);
3477 return 0;
3478 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479}
3480
3481static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482inplace_binop(struct compiler *c, operator_ty op)
3483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 switch (op) {
3485 case Add:
3486 return INPLACE_ADD;
3487 case Sub:
3488 return INPLACE_SUBTRACT;
3489 case Mult:
3490 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003491 case MatMult:
3492 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 case Div:
3494 return INPLACE_TRUE_DIVIDE;
3495 case Mod:
3496 return INPLACE_MODULO;
3497 case Pow:
3498 return INPLACE_POWER;
3499 case LShift:
3500 return INPLACE_LSHIFT;
3501 case RShift:
3502 return INPLACE_RSHIFT;
3503 case BitOr:
3504 return INPLACE_OR;
3505 case BitXor:
3506 return INPLACE_XOR;
3507 case BitAnd:
3508 return INPLACE_AND;
3509 case FloorDiv:
3510 return INPLACE_FLOOR_DIVIDE;
3511 default:
3512 PyErr_Format(PyExc_SystemError,
3513 "inplace binary op %d should not be possible", op);
3514 return 0;
3515 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516}
3517
3518static int
3519compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3520{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003521 int op, scope;
3522 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 PyObject *dict = c->u->u_names;
3526 PyObject *mangled;
3527 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003529 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3530 !_PyUnicode_EqualToASCIIString(name, "True") &&
3531 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003532
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003533 mangled = _Py_Mangle(c->u->u_private, name);
3534 if (!mangled)
3535 return 0;
3536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 op = 0;
3538 optype = OP_NAME;
3539 scope = PyST_GetScope(c->u->u_ste, mangled);
3540 switch (scope) {
3541 case FREE:
3542 dict = c->u->u_freevars;
3543 optype = OP_DEREF;
3544 break;
3545 case CELL:
3546 dict = c->u->u_cellvars;
3547 optype = OP_DEREF;
3548 break;
3549 case LOCAL:
3550 if (c->u->u_ste->ste_type == FunctionBlock)
3551 optype = OP_FAST;
3552 break;
3553 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003554 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 optype = OP_GLOBAL;
3556 break;
3557 case GLOBAL_EXPLICIT:
3558 optype = OP_GLOBAL;
3559 break;
3560 default:
3561 /* scope can be 0 */
3562 break;
3563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003566 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 switch (optype) {
3569 case OP_DEREF:
3570 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003571 case Load:
3572 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3573 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003574 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003575 op = STORE_DEREF;
3576 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 case AugLoad:
3578 case AugStore:
3579 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003580 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 case Param:
3582 default:
3583 PyErr_SetString(PyExc_SystemError,
3584 "param invalid for deref variable");
3585 return 0;
3586 }
3587 break;
3588 case OP_FAST:
3589 switch (ctx) {
3590 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003591 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003592 op = STORE_FAST;
3593 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 case Del: op = DELETE_FAST; break;
3595 case AugLoad:
3596 case AugStore:
3597 break;
3598 case Param:
3599 default:
3600 PyErr_SetString(PyExc_SystemError,
3601 "param invalid for local variable");
3602 return 0;
3603 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003604 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 return 1;
3606 case OP_GLOBAL:
3607 switch (ctx) {
3608 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003609 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003610 op = STORE_GLOBAL;
3611 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 case Del: op = DELETE_GLOBAL; break;
3613 case AugLoad:
3614 case AugStore:
3615 break;
3616 case Param:
3617 default:
3618 PyErr_SetString(PyExc_SystemError,
3619 "param invalid for global variable");
3620 return 0;
3621 }
3622 break;
3623 case OP_NAME:
3624 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003625 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003626 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003627 op = STORE_NAME;
3628 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 case Del: op = DELETE_NAME; break;
3630 case AugLoad:
3631 case AugStore:
3632 break;
3633 case Param:
3634 default:
3635 PyErr_SetString(PyExc_SystemError,
3636 "param invalid for name variable");
3637 return 0;
3638 }
3639 break;
3640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 assert(op);
3643 arg = compiler_add_o(c, dict, mangled);
3644 Py_DECREF(mangled);
3645 if (arg < 0)
3646 return 0;
3647 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648}
3649
3650static int
3651compiler_boolop(struct compiler *c, expr_ty e)
3652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003654 int jumpi;
3655 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 assert(e->kind == BoolOp_kind);
3659 if (e->v.BoolOp.op == And)
3660 jumpi = JUMP_IF_FALSE_OR_POP;
3661 else
3662 jumpi = JUMP_IF_TRUE_OR_POP;
3663 end = compiler_new_block(c);
3664 if (end == NULL)
3665 return 0;
3666 s = e->v.BoolOp.values;
3667 n = asdl_seq_LEN(s) - 1;
3668 assert(n >= 0);
3669 for (i = 0; i < n; ++i) {
3670 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3671 ADDOP_JABS(c, jumpi, end);
3672 }
3673 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3674 compiler_use_next_block(c, end);
3675 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676}
3677
3678static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003679starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3680 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003681{
3682 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003683 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003684 if (n > 2 && are_all_items_const(elts, 0, n)) {
3685 PyObject *folded = PyTuple_New(n);
3686 if (folded == NULL) {
3687 return 0;
3688 }
3689 PyObject *val;
3690 for (i = 0; i < n; i++) {
3691 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3692 Py_INCREF(val);
3693 PyTuple_SET_ITEM(folded, i, val);
3694 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003695 if (tuple) {
3696 ADDOP_LOAD_CONST_NEW(c, folded);
3697 } else {
3698 if (add == SET_ADD) {
3699 Py_SETREF(folded, PyFrozenSet_New(folded));
3700 if (folded == NULL) {
3701 return 0;
3702 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003703 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003704 ADDOP_I(c, build, pushed);
3705 ADDOP_LOAD_CONST_NEW(c, folded);
3706 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003707 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003708 return 1;
3709 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003710
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003711 for (i = 0; i < n; i++) {
3712 expr_ty elt = asdl_seq_GET(elts, i);
3713 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003714 seen_star = 1;
3715 }
3716 }
3717 if (seen_star) {
3718 seen_star = 0;
3719 for (i = 0; i < n; i++) {
3720 expr_ty elt = asdl_seq_GET(elts, i);
3721 if (elt->kind == Starred_kind) {
3722 if (seen_star == 0) {
3723 ADDOP_I(c, build, i+pushed);
3724 seen_star = 1;
3725 }
3726 VISIT(c, expr, elt->v.Starred.value);
3727 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003728 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003729 else {
3730 VISIT(c, expr, elt);
3731 if (seen_star) {
3732 ADDOP_I(c, add, 1);
3733 }
3734 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003736 assert(seen_star);
3737 if (tuple) {
3738 ADDOP(c, LIST_TO_TUPLE);
3739 }
3740 }
3741 else {
3742 for (i = 0; i < n; i++) {
3743 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003744 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003745 }
3746 if (tuple) {
3747 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3748 } else {
3749 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003750 }
3751 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003752 return 1;
3753}
3754
3755static int
3756assignment_helper(struct compiler *c, asdl_seq *elts)
3757{
3758 Py_ssize_t n = asdl_seq_LEN(elts);
3759 Py_ssize_t i;
3760 int seen_star = 0;
3761 for (i = 0; i < n; i++) {
3762 expr_ty elt = asdl_seq_GET(elts, i);
3763 if (elt->kind == Starred_kind && !seen_star) {
3764 if ((i >= (1 << 8)) ||
3765 (n-i-1 >= (INT_MAX >> 8)))
3766 return compiler_error(c,
3767 "too many expressions in "
3768 "star-unpacking assignment");
3769 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3770 seen_star = 1;
3771 asdl_seq_SET(elts, i, elt->v.Starred.value);
3772 }
3773 else if (elt->kind == Starred_kind) {
3774 return compiler_error(c,
3775 "two starred expressions in assignment");
3776 }
3777 }
3778 if (!seen_star) {
3779 ADDOP_I(c, UNPACK_SEQUENCE, n);
3780 }
3781 VISIT_SEQ(c, expr, elts);
3782 return 1;
3783}
3784
3785static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786compiler_list(struct compiler *c, expr_ty e)
3787{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003788 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003789 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003792 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003793 return starunpack_helper(c, elts, 0, BUILD_LIST,
3794 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 else
3797 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799}
3800
3801static int
3802compiler_tuple(struct compiler *c, expr_ty e)
3803{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003804 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003805 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003806 return assignment_helper(c, elts);
3807 }
3808 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003809 return starunpack_helper(c, elts, 0, BUILD_LIST,
3810 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811 }
3812 else
3813 VISIT_SEQ(c, expr, elts);
3814 return 1;
3815}
3816
3817static int
3818compiler_set(struct compiler *c, expr_ty e)
3819{
Mark Shannon13bc1392020-01-23 09:25:17 +00003820 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3821 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003822}
3823
3824static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003825are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3826{
3827 Py_ssize_t i;
3828 for (i = begin; i < end; i++) {
3829 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003830 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003831 return 0;
3832 }
3833 return 1;
3834}
3835
3836static int
3837compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3838{
3839 Py_ssize_t i, n = end - begin;
3840 PyObject *keys, *key;
3841 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3842 for (i = begin; i < end; i++) {
3843 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3844 }
3845 keys = PyTuple_New(n);
3846 if (keys == NULL) {
3847 return 0;
3848 }
3849 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003850 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003851 Py_INCREF(key);
3852 PyTuple_SET_ITEM(keys, i - begin, key);
3853 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003854 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003855 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3856 }
3857 else {
3858 for (i = begin; i < end; i++) {
3859 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3860 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3861 }
3862 ADDOP_I(c, BUILD_MAP, n);
3863 }
3864 return 1;
3865}
3866
3867static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003868compiler_dict(struct compiler *c, expr_ty e)
3869{
Victor Stinner976bb402016-03-23 11:36:19 +01003870 Py_ssize_t i, n, elements;
3871 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003872 int is_unpacking = 0;
3873 n = asdl_seq_LEN(e->v.Dict.values);
3874 containers = 0;
3875 elements = 0;
3876 for (i = 0; i < n; i++) {
3877 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3878 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003879 if (!compiler_subdict(c, e, i - elements, i))
3880 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003881 containers++;
3882 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003884 if (is_unpacking) {
3885 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3886 containers++;
3887 }
3888 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003889 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 }
3891 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003892 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003893 if (!compiler_subdict(c, e, n - elements, n))
3894 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003895 containers++;
3896 }
3897 /* If there is more than one dict, they need to be merged into a new
3898 * dict. If there is one dict and it's an unpacking, then it needs
3899 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003900 if (containers > 1 || is_unpacking) {
3901 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 }
3903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904}
3905
3906static int
3907compiler_compare(struct compiler *c, expr_ty e)
3908{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003909 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003911 if (!check_compare(c, e)) {
3912 return 0;
3913 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003915 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3916 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3917 if (n == 0) {
3918 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003919 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003920 }
3921 else {
3922 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 if (cleanup == NULL)
3924 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 VISIT(c, expr,
3927 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003928 ADDOP(c, DUP_TOP);
3929 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003930 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003931 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3932 NEXT_BLOCK(c);
3933 }
3934 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003935 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 basicblock *end = compiler_new_block(c);
3937 if (end == NULL)
3938 return 0;
3939 ADDOP_JREL(c, JUMP_FORWARD, end);
3940 compiler_use_next_block(c, cleanup);
3941 ADDOP(c, ROT_TWO);
3942 ADDOP(c, POP_TOP);
3943 compiler_use_next_block(c, end);
3944 }
3945 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946}
3947
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003948static PyTypeObject *
3949infer_type(expr_ty e)
3950{
3951 switch (e->kind) {
3952 case Tuple_kind:
3953 return &PyTuple_Type;
3954 case List_kind:
3955 case ListComp_kind:
3956 return &PyList_Type;
3957 case Dict_kind:
3958 case DictComp_kind:
3959 return &PyDict_Type;
3960 case Set_kind:
3961 case SetComp_kind:
3962 return &PySet_Type;
3963 case GeneratorExp_kind:
3964 return &PyGen_Type;
3965 case Lambda_kind:
3966 return &PyFunction_Type;
3967 case JoinedStr_kind:
3968 case FormattedValue_kind:
3969 return &PyUnicode_Type;
3970 case Constant_kind:
3971 return e->v.Constant.value->ob_type;
3972 default:
3973 return NULL;
3974 }
3975}
3976
3977static int
3978check_caller(struct compiler *c, expr_ty e)
3979{
3980 switch (e->kind) {
3981 case Constant_kind:
3982 case Tuple_kind:
3983 case List_kind:
3984 case ListComp_kind:
3985 case Dict_kind:
3986 case DictComp_kind:
3987 case Set_kind:
3988 case SetComp_kind:
3989 case GeneratorExp_kind:
3990 case JoinedStr_kind:
3991 case FormattedValue_kind:
3992 return compiler_warn(c, "'%.200s' object is not callable; "
3993 "perhaps you missed a comma?",
3994 infer_type(e)->tp_name);
3995 default:
3996 return 1;
3997 }
3998}
3999
4000static int
4001check_subscripter(struct compiler *c, expr_ty e)
4002{
4003 PyObject *v;
4004
4005 switch (e->kind) {
4006 case Constant_kind:
4007 v = e->v.Constant.value;
4008 if (!(v == Py_None || v == Py_Ellipsis ||
4009 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4010 PyAnySet_Check(v)))
4011 {
4012 return 1;
4013 }
4014 /* fall through */
4015 case Set_kind:
4016 case SetComp_kind:
4017 case GeneratorExp_kind:
4018 case Lambda_kind:
4019 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4020 "perhaps you missed a comma?",
4021 infer_type(e)->tp_name);
4022 default:
4023 return 1;
4024 }
4025}
4026
4027static int
4028check_index(struct compiler *c, expr_ty e, slice_ty s)
4029{
4030 PyObject *v;
4031
4032 if (s->kind != Index_kind) {
4033 return 1;
4034 }
4035 PyTypeObject *index_type = infer_type(s->v.Index.value);
4036 if (index_type == NULL
4037 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4038 || index_type == &PySlice_Type) {
4039 return 1;
4040 }
4041
4042 switch (e->kind) {
4043 case Constant_kind:
4044 v = e->v.Constant.value;
4045 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4046 return 1;
4047 }
4048 /* fall through */
4049 case Tuple_kind:
4050 case List_kind:
4051 case ListComp_kind:
4052 case JoinedStr_kind:
4053 case FormattedValue_kind:
4054 return compiler_warn(c, "%.200s indices must be integers or slices, "
4055 "not %.200s; "
4056 "perhaps you missed a comma?",
4057 infer_type(e)->tp_name,
4058 index_type->tp_name);
4059 default:
4060 return 1;
4061 }
4062}
4063
Zackery Spytz97f5de02019-03-22 01:30:32 -06004064// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004066maybe_optimize_method_call(struct compiler *c, expr_ty e)
4067{
4068 Py_ssize_t argsl, i;
4069 expr_ty meth = e->v.Call.func;
4070 asdl_seq *args = e->v.Call.args;
4071
4072 /* Check that the call node is an attribute access, and that
4073 the call doesn't have keyword parameters. */
4074 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4075 asdl_seq_LEN(e->v.Call.keywords))
4076 return -1;
4077
4078 /* Check that there are no *varargs types of arguments. */
4079 argsl = asdl_seq_LEN(args);
4080 for (i = 0; i < argsl; i++) {
4081 expr_ty elt = asdl_seq_GET(args, i);
4082 if (elt->kind == Starred_kind) {
4083 return -1;
4084 }
4085 }
4086
4087 /* Alright, we can optimize the code. */
4088 VISIT(c, expr, meth->v.Attribute.value);
4089 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4090 VISIT_SEQ(c, expr, e->v.Call.args);
4091 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4092 return 1;
4093}
4094
4095static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096compiler_call(struct compiler *c, expr_ty e)
4097{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004098 int ret = maybe_optimize_method_call(c, e);
4099 if (ret >= 0) {
4100 return ret;
4101 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004102 if (!check_caller(c, e->v.Call.func)) {
4103 return 0;
4104 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 VISIT(c, expr, e->v.Call.func);
4106 return compiler_call_helper(c, 0,
4107 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004108 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004109}
4110
Eric V. Smith235a6f02015-09-19 14:51:32 -04004111static int
4112compiler_joined_str(struct compiler *c, expr_ty e)
4113{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004114 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004115 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4116 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004117 return 1;
4118}
4119
Eric V. Smitha78c7952015-11-03 12:45:05 -05004120/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004121static int
4122compiler_formatted_value(struct compiler *c, expr_ty e)
4123{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004124 /* Our oparg encodes 2 pieces of information: the conversion
4125 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004126
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004127 Convert the conversion char to 3 bits:
4128 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004129 !s : 001 0x1 FVC_STR
4130 !r : 010 0x2 FVC_REPR
4131 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004132
Eric V. Smitha78c7952015-11-03 12:45:05 -05004133 next bit is whether or not we have a format spec:
4134 yes : 100 0x4
4135 no : 000 0x0
4136 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004137
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004138 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004139 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004140
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004141 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004142 VISIT(c, expr, e->v.FormattedValue.value);
4143
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004144 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004145 case 's': oparg = FVC_STR; break;
4146 case 'r': oparg = FVC_REPR; break;
4147 case 'a': oparg = FVC_ASCII; break;
4148 case -1: oparg = FVC_NONE; break;
4149 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004150 PyErr_Format(PyExc_SystemError,
4151 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004152 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004154 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004155 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004156 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004157 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158 }
4159
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 /* And push our opcode and oparg */
4161 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004162
Eric V. Smith235a6f02015-09-19 14:51:32 -04004163 return 1;
4164}
4165
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004166static int
4167compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4168{
4169 Py_ssize_t i, n = end - begin;
4170 keyword_ty kw;
4171 PyObject *keys, *key;
4172 assert(n > 0);
4173 if (n > 1) {
4174 for (i = begin; i < end; i++) {
4175 kw = asdl_seq_GET(keywords, i);
4176 VISIT(c, expr, kw->value);
4177 }
4178 keys = PyTuple_New(n);
4179 if (keys == NULL) {
4180 return 0;
4181 }
4182 for (i = begin; i < end; i++) {
4183 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4184 Py_INCREF(key);
4185 PyTuple_SET_ITEM(keys, i - begin, key);
4186 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004187 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004188 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4189 }
4190 else {
4191 /* a for loop only executes once */
4192 for (i = begin; i < end; i++) {
4193 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004194 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004195 VISIT(c, expr, kw->value);
4196 }
4197 ADDOP_I(c, BUILD_MAP, n);
4198 }
4199 return 1;
4200}
4201
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004202/* shared code between compiler_call and compiler_class */
4203static int
4204compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004205 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004206 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004207 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004208{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004209 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004210
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004211 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004212 nkwelts = asdl_seq_LEN(keywords);
4213
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004214 for (i = 0; i < nelts; i++) {
4215 expr_ty elt = asdl_seq_GET(args, i);
4216 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004217 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004218 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004219 }
4220 for (i = 0; i < nkwelts; i++) {
4221 keyword_ty kw = asdl_seq_GET(keywords, i);
4222 if (kw->arg == NULL) {
4223 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004226
Mark Shannon13bc1392020-01-23 09:25:17 +00004227 /* No * or ** args, so can use faster calling sequence */
4228 for (i = 0; i < nelts; i++) {
4229 expr_ty elt = asdl_seq_GET(args, i);
4230 assert(elt->kind != Starred_kind);
4231 VISIT(c, expr, elt);
4232 }
4233 if (nkwelts) {
4234 PyObject *names;
4235 VISIT_SEQ(c, keyword, keywords);
4236 names = PyTuple_New(nkwelts);
4237 if (names == NULL) {
4238 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004239 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004240 for (i = 0; i < nkwelts; i++) {
4241 keyword_ty kw = asdl_seq_GET(keywords, i);
4242 Py_INCREF(kw->arg);
4243 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004244 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004245 ADDOP_LOAD_CONST_NEW(c, names);
4246 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4247 return 1;
4248 }
4249 else {
4250 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4251 return 1;
4252 }
4253
4254ex_call:
4255
4256 /* Do positional arguments. */
4257 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4258 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4259 }
4260 else if (starunpack_helper(c, args, n, BUILD_LIST,
4261 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4262 return 0;
4263 }
4264 /* Then keyword arguments */
4265 if (nkwelts) {
4266 /* the number of dictionaries on the stack */
4267 Py_ssize_t nsubkwargs = 0;
4268
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004269 nseen = 0; /* the number of keyword arguments on the stack following */
4270 for (i = 0; i < nkwelts; i++) {
4271 keyword_ty kw = asdl_seq_GET(keywords, i);
4272 if (kw->arg == NULL) {
4273 /* A keyword argument unpacking. */
4274 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004275 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4276 return 0;
4277 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004278 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004279 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004280 VISIT(c, expr, kw->value);
4281 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004282 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004283 else {
4284 nseen++;
4285 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004286 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004287 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004288 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004289 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004290 return 0;
4291 nsubkwargs++;
4292 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004293 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004294 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004295 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004296 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004298 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4299 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004300}
4301
Nick Coghlan650f0d02007-04-15 12:05:43 +00004302
4303/* List and set comprehensions and generator expressions work by creating a
4304 nested function to perform the actual iteration. This means that the
4305 iteration variables don't leak into the current scope.
4306 The defined function is called immediately following its definition, with the
4307 result of that call being the result of the expression.
4308 The LC/SC version returns the populated container, while the GE version is
4309 flagged in symtable.c as a generator, so it returns the generator object
4310 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004311
4312 Possible cleanups:
4313 - iterate over the generator sequence instead of using recursion
4314*/
4315
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004316
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318compiler_comprehension_generator(struct compiler *c,
4319 asdl_seq *generators, int gen_index,
4320 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004322 comprehension_ty gen;
4323 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4324 if (gen->is_async) {
4325 return compiler_async_comprehension_generator(
4326 c, generators, gen_index, elt, val, type);
4327 } else {
4328 return compiler_sync_comprehension_generator(
4329 c, generators, gen_index, elt, val, type);
4330 }
4331}
4332
4333static int
4334compiler_sync_comprehension_generator(struct compiler *c,
4335 asdl_seq *generators, int gen_index,
4336 expr_ty elt, expr_ty val, int type)
4337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 /* generate code for the iterator, then each of the ifs,
4339 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 comprehension_ty gen;
4342 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004343 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 start = compiler_new_block(c);
4346 skip = compiler_new_block(c);
4347 if_cleanup = compiler_new_block(c);
4348 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4351 anchor == NULL)
4352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (gen_index == 0) {
4357 /* Receive outermost iter as an implicit argument */
4358 c->u->u_argcount = 1;
4359 ADDOP_I(c, LOAD_FAST, 0);
4360 }
4361 else {
4362 /* Sub-iter - calculate on the fly */
4363 VISIT(c, expr, gen->iter);
4364 ADDOP(c, GET_ITER);
4365 }
4366 compiler_use_next_block(c, start);
4367 ADDOP_JREL(c, FOR_ITER, anchor);
4368 NEXT_BLOCK(c);
4369 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 /* XXX this needs to be cleaned up...a lot! */
4372 n = asdl_seq_LEN(gen->ifs);
4373 for (i = 0; i < n; i++) {
4374 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004375 if (!compiler_jump_if(c, e, if_cleanup, 0))
4376 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 NEXT_BLOCK(c);
4378 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 if (++gen_index < asdl_seq_LEN(generators))
4381 if (!compiler_comprehension_generator(c,
4382 generators, gen_index,
4383 elt, val, type))
4384 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 /* only append after the last for generator */
4387 if (gen_index >= asdl_seq_LEN(generators)) {
4388 /* comprehension specific code */
4389 switch (type) {
4390 case COMP_GENEXP:
4391 VISIT(c, expr, elt);
4392 ADDOP(c, YIELD_VALUE);
4393 ADDOP(c, POP_TOP);
4394 break;
4395 case COMP_LISTCOMP:
4396 VISIT(c, expr, elt);
4397 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4398 break;
4399 case COMP_SETCOMP:
4400 VISIT(c, expr, elt);
4401 ADDOP_I(c, SET_ADD, gen_index + 1);
4402 break;
4403 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004404 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004407 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 ADDOP_I(c, MAP_ADD, gen_index + 1);
4409 break;
4410 default:
4411 return 0;
4412 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 compiler_use_next_block(c, skip);
4415 }
4416 compiler_use_next_block(c, if_cleanup);
4417 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4418 compiler_use_next_block(c, anchor);
4419
4420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421}
4422
4423static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004424compiler_async_comprehension_generator(struct compiler *c,
4425 asdl_seq *generators, int gen_index,
4426 expr_ty elt, expr_ty val, int type)
4427{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004428 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004429 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004431 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004432 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004433 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004434
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004435 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004436 return 0;
4437 }
4438
4439 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4440
4441 if (gen_index == 0) {
4442 /* Receive outermost iter as an implicit argument */
4443 c->u->u_argcount = 1;
4444 ADDOP_I(c, LOAD_FAST, 0);
4445 }
4446 else {
4447 /* Sub-iter - calculate on the fly */
4448 VISIT(c, expr, gen->iter);
4449 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004450 }
4451
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004452 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004453
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004454 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004455 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004456 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004457 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004458 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004459 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004460
4461 n = asdl_seq_LEN(gen->ifs);
4462 for (i = 0; i < n; i++) {
4463 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004464 if (!compiler_jump_if(c, e, if_cleanup, 0))
4465 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004466 NEXT_BLOCK(c);
4467 }
4468
4469 if (++gen_index < asdl_seq_LEN(generators))
4470 if (!compiler_comprehension_generator(c,
4471 generators, gen_index,
4472 elt, val, type))
4473 return 0;
4474
4475 /* only append after the last for generator */
4476 if (gen_index >= asdl_seq_LEN(generators)) {
4477 /* comprehension specific code */
4478 switch (type) {
4479 case COMP_GENEXP:
4480 VISIT(c, expr, elt);
4481 ADDOP(c, YIELD_VALUE);
4482 ADDOP(c, POP_TOP);
4483 break;
4484 case COMP_LISTCOMP:
4485 VISIT(c, expr, elt);
4486 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4487 break;
4488 case COMP_SETCOMP:
4489 VISIT(c, expr, elt);
4490 ADDOP_I(c, SET_ADD, gen_index + 1);
4491 break;
4492 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004493 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004496 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 ADDOP_I(c, MAP_ADD, gen_index + 1);
4498 break;
4499 default:
4500 return 0;
4501 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 }
4503 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004504 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4505
4506 compiler_use_next_block(c, except);
4507 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508
4509 return 1;
4510}
4511
4512static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004513compiler_comprehension(struct compiler *c, expr_ty e, int type,
4514 identifier name, asdl_seq *generators, expr_ty elt,
4515 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004518 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004519 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 int is_async_function = c->u->u_ste->ste_coroutine;
4521 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004522
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004524
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004525 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4526 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 }
4530
4531 is_async_generator = c->u->u_ste->ste_coroutine;
4532
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004533 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534 compiler_error(c, "asynchronous comprehension outside of "
4535 "an asynchronous function");
4536 goto error_in_scope;
4537 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 if (type != COMP_GENEXP) {
4540 int op;
4541 switch (type) {
4542 case COMP_LISTCOMP:
4543 op = BUILD_LIST;
4544 break;
4545 case COMP_SETCOMP:
4546 op = BUILD_SET;
4547 break;
4548 case COMP_DICTCOMP:
4549 op = BUILD_MAP;
4550 break;
4551 default:
4552 PyErr_Format(PyExc_SystemError,
4553 "unknown comprehension type %d", type);
4554 goto error_in_scope;
4555 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 ADDOP_I(c, op, 0);
4558 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 if (!compiler_comprehension_generator(c, generators, 0, elt,
4561 val, type))
4562 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 if (type != COMP_GENEXP) {
4565 ADDOP(c, RETURN_VALUE);
4566 }
4567
4568 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004569 qualname = c->u->u_qualname;
4570 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004572 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 goto error;
4574
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004575 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004577 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 Py_DECREF(co);
4579
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004580 VISIT(c, expr, outermost->iter);
4581
4582 if (outermost->is_async) {
4583 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004584 } else {
4585 ADDOP(c, GET_ITER);
4586 }
4587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589
4590 if (is_async_generator && type != COMP_GENEXP) {
4591 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004592 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004593 ADDOP(c, YIELD_FROM);
4594 }
4595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004597error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004599error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004600 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 Py_XDECREF(co);
4602 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004603}
4604
4605static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004606compiler_genexp(struct compiler *c, expr_ty e)
4607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 static identifier name;
4609 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004610 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 if (!name)
4612 return 0;
4613 }
4614 assert(e->kind == GeneratorExp_kind);
4615 return compiler_comprehension(c, e, COMP_GENEXP, name,
4616 e->v.GeneratorExp.generators,
4617 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004618}
4619
4620static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621compiler_listcomp(struct compiler *c, expr_ty e)
4622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 static identifier name;
4624 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004625 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 if (!name)
4627 return 0;
4628 }
4629 assert(e->kind == ListComp_kind);
4630 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4631 e->v.ListComp.generators,
4632 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004633}
4634
4635static int
4636compiler_setcomp(struct compiler *c, expr_ty e)
4637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 static identifier name;
4639 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004640 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (!name)
4642 return 0;
4643 }
4644 assert(e->kind == SetComp_kind);
4645 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4646 e->v.SetComp.generators,
4647 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004648}
4649
4650
4651static int
4652compiler_dictcomp(struct compiler *c, expr_ty e)
4653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 static identifier name;
4655 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004656 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 if (!name)
4658 return 0;
4659 }
4660 assert(e->kind == DictComp_kind);
4661 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4662 e->v.DictComp.generators,
4663 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004664}
4665
4666
4667static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004668compiler_visit_keyword(struct compiler *c, keyword_ty k)
4669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 VISIT(c, expr, k->value);
4671 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004672}
4673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004675 whether they are true or false.
4676
4677 Return values: 1 for true, 0 for false, -1 for non-constant.
4678 */
4679
4680static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004681expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004682{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004683 if (e->kind == Constant_kind) {
4684 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004685 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004686 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004687}
4688
Mark Shannonfee55262019-11-21 09:11:43 +00004689static int
4690compiler_with_except_finish(struct compiler *c) {
4691 basicblock *exit;
4692 exit = compiler_new_block(c);
4693 if (exit == NULL)
4694 return 0;
4695 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4696 ADDOP(c, RERAISE);
4697 compiler_use_next_block(c, exit);
4698 ADDOP(c, POP_TOP);
4699 ADDOP(c, POP_TOP);
4700 ADDOP(c, POP_TOP);
4701 ADDOP(c, POP_EXCEPT);
4702 ADDOP(c, POP_TOP);
4703 return 1;
4704}
Yury Selivanov75445082015-05-11 22:57:16 -04004705
4706/*
4707 Implements the async with statement.
4708
4709 The semantics outlined in that PEP are as follows:
4710
4711 async with EXPR as VAR:
4712 BLOCK
4713
4714 It is implemented roughly as:
4715
4716 context = EXPR
4717 exit = context.__aexit__ # not calling it
4718 value = await context.__aenter__()
4719 try:
4720 VAR = value # if VAR present in the syntax
4721 BLOCK
4722 finally:
4723 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004724 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004725 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004726 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004727 if not (await exit(*exc)):
4728 raise
4729 */
4730static int
4731compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4732{
Mark Shannonfee55262019-11-21 09:11:43 +00004733 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004734 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4735
4736 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004737 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4738 c->u->u_ste->ste_coroutine = 1;
4739 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004740 return compiler_error(c, "'async with' outside async function");
4741 }
Yury Selivanov75445082015-05-11 22:57:16 -04004742
4743 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004744 final = compiler_new_block(c);
4745 exit = compiler_new_block(c);
4746 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004747 return 0;
4748
4749 /* Evaluate EXPR */
4750 VISIT(c, expr, item->context_expr);
4751
4752 ADDOP(c, BEFORE_ASYNC_WITH);
4753 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004754 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004755 ADDOP(c, YIELD_FROM);
4756
Mark Shannonfee55262019-11-21 09:11:43 +00004757 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004758
4759 /* SETUP_ASYNC_WITH pushes a finally block. */
4760 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004761 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004762 return 0;
4763 }
4764
4765 if (item->optional_vars) {
4766 VISIT(c, expr, item->optional_vars);
4767 }
4768 else {
4769 /* Discard result from context.__aenter__() */
4770 ADDOP(c, POP_TOP);
4771 }
4772
4773 pos++;
4774 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4775 /* BLOCK code */
4776 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4777 else if (!compiler_async_with(c, s, pos))
4778 return 0;
4779
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004780 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004781 ADDOP(c, POP_BLOCK);
4782 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004783
Mark Shannonfee55262019-11-21 09:11:43 +00004784 /* For successful outcome:
4785 * call __exit__(None, None, None)
4786 */
4787 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004788 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004789 ADDOP(c, GET_AWAITABLE);
4790 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4791 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004792
Mark Shannonfee55262019-11-21 09:11:43 +00004793 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004794
Mark Shannonfee55262019-11-21 09:11:43 +00004795 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4796
4797 /* For exceptional outcome: */
4798 compiler_use_next_block(c, final);
4799
4800 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004801 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004802 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004803 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004804 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004805
Mark Shannonfee55262019-11-21 09:11:43 +00004806compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004807 return 1;
4808}
4809
4810
Guido van Rossumc2e20742006-02-27 22:32:47 +00004811/*
4812 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004813 with EXPR as VAR:
4814 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004815 is implemented as:
4816 <code for EXPR>
4817 SETUP_WITH E
4818 <code to store to VAR> or POP_TOP
4819 <code for BLOCK>
4820 LOAD_CONST (None, None, None)
4821 CALL_FUNCTION_EX 0
4822 JUMP_FORWARD EXIT
4823 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4824 POP_JUMP_IF_TRUE T:
4825 RERAISE
4826 T: POP_TOP * 3 (remove exception from stack)
4827 POP_EXCEPT
4828 POP_TOP
4829 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004830 */
Mark Shannonfee55262019-11-21 09:11:43 +00004831
Guido van Rossumc2e20742006-02-27 22:32:47 +00004832static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004833compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004834{
Mark Shannonfee55262019-11-21 09:11:43 +00004835 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004836 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004837
4838 assert(s->kind == With_kind);
4839
Guido van Rossumc2e20742006-02-27 22:32:47 +00004840 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004841 final = compiler_new_block(c);
4842 exit = compiler_new_block(c);
4843 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004844 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004845
Thomas Wouters477c8d52006-05-27 19:21:47 +00004846 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004847 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004848 /* Will push bound __exit__ */
4849 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004850
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004851 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004852 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004853 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004854 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004855 }
4856
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004857 if (item->optional_vars) {
4858 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004859 }
4860 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004862 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004863 }
4864
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004865 pos++;
4866 if (pos == asdl_seq_LEN(s->v.With.items))
4867 /* BLOCK code */
4868 VISIT_SEQ(c, stmt, s->v.With.body)
4869 else if (!compiler_with(c, s, pos))
4870 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004871
Guido van Rossumc2e20742006-02-27 22:32:47 +00004872 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004873 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004874
Mark Shannonfee55262019-11-21 09:11:43 +00004875 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004876
Mark Shannonfee55262019-11-21 09:11:43 +00004877 /* For successful outcome:
4878 * call __exit__(None, None, None)
4879 */
4880 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004881 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004882 ADDOP(c, POP_TOP);
4883 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004884
Mark Shannonfee55262019-11-21 09:11:43 +00004885 /* For exceptional outcome: */
4886 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004887
Mark Shannonfee55262019-11-21 09:11:43 +00004888 ADDOP(c, WITH_EXCEPT_START);
4889 compiler_with_except_finish(c);
4890
4891 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892 return 1;
4893}
4894
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004895static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004896compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004899 case NamedExpr_kind:
4900 VISIT(c, expr, e->v.NamedExpr.value);
4901 ADDOP(c, DUP_TOP);
4902 VISIT(c, expr, e->v.NamedExpr.target);
4903 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 case BoolOp_kind:
4905 return compiler_boolop(c, e);
4906 case BinOp_kind:
4907 VISIT(c, expr, e->v.BinOp.left);
4908 VISIT(c, expr, e->v.BinOp.right);
4909 ADDOP(c, binop(c, e->v.BinOp.op));
4910 break;
4911 case UnaryOp_kind:
4912 VISIT(c, expr, e->v.UnaryOp.operand);
4913 ADDOP(c, unaryop(e->v.UnaryOp.op));
4914 break;
4915 case Lambda_kind:
4916 return compiler_lambda(c, e);
4917 case IfExp_kind:
4918 return compiler_ifexp(c, e);
4919 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004920 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004922 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004923 case GeneratorExp_kind:
4924 return compiler_genexp(c, e);
4925 case ListComp_kind:
4926 return compiler_listcomp(c, e);
4927 case SetComp_kind:
4928 return compiler_setcomp(c, e);
4929 case DictComp_kind:
4930 return compiler_dictcomp(c, e);
4931 case Yield_kind:
4932 if (c->u->u_ste->ste_type != FunctionBlock)
4933 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004934 if (e->v.Yield.value) {
4935 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 }
4937 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004938 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004940 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004942 case YieldFrom_kind:
4943 if (c->u->u_ste->ste_type != FunctionBlock)
4944 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004945
4946 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4947 return compiler_error(c, "'yield from' inside async function");
4948
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004949 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004950 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004951 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004952 ADDOP(c, YIELD_FROM);
4953 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004954 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004955 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4956 if (c->u->u_ste->ste_type != FunctionBlock){
4957 return compiler_error(c, "'await' outside function");
4958 }
Yury Selivanov75445082015-05-11 22:57:16 -04004959
Victor Stinner331a6a52019-05-27 16:39:22 +02004960 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004961 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4962 return compiler_error(c, "'await' outside async function");
4963 }
4964 }
Yury Selivanov75445082015-05-11 22:57:16 -04004965
4966 VISIT(c, expr, e->v.Await.value);
4967 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004968 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004969 ADDOP(c, YIELD_FROM);
4970 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 case Compare_kind:
4972 return compiler_compare(c, e);
4973 case Call_kind:
4974 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004975 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004976 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004977 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004978 case JoinedStr_kind:
4979 return compiler_joined_str(c, e);
4980 case FormattedValue_kind:
4981 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 /* The following exprs can be assignment targets. */
4983 case Attribute_kind:
4984 if (e->v.Attribute.ctx != AugStore)
4985 VISIT(c, expr, e->v.Attribute.value);
4986 switch (e->v.Attribute.ctx) {
4987 case AugLoad:
4988 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004989 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 case Load:
4991 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4992 break;
4993 case AugStore:
4994 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004995 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 case Store:
4997 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4998 break;
4999 case Del:
5000 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5001 break;
5002 case Param:
5003 default:
5004 PyErr_SetString(PyExc_SystemError,
5005 "param invalid in attribute expression");
5006 return 0;
5007 }
5008 break;
5009 case Subscript_kind:
5010 switch (e->v.Subscript.ctx) {
5011 case AugLoad:
5012 VISIT(c, expr, e->v.Subscript.value);
5013 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5014 break;
5015 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005016 if (!check_subscripter(c, e->v.Subscript.value)) {
5017 return 0;
5018 }
5019 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5020 return 0;
5021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 VISIT(c, expr, e->v.Subscript.value);
5023 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5024 break;
5025 case AugStore:
5026 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5027 break;
5028 case Store:
5029 VISIT(c, expr, e->v.Subscript.value);
5030 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5031 break;
5032 case Del:
5033 VISIT(c, expr, e->v.Subscript.value);
5034 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5035 break;
5036 case Param:
5037 default:
5038 PyErr_SetString(PyExc_SystemError,
5039 "param invalid in subscript expression");
5040 return 0;
5041 }
5042 break;
5043 case Starred_kind:
5044 switch (e->v.Starred.ctx) {
5045 case Store:
5046 /* In all legitimate cases, the Starred node was already replaced
5047 * by compiler_list/compiler_tuple. XXX: is that okay? */
5048 return compiler_error(c,
5049 "starred assignment target must be in a list or tuple");
5050 default:
5051 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005052 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 case Name_kind:
5055 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5056 /* child nodes of List and Tuple will have expr_context set */
5057 case List_kind:
5058 return compiler_list(c, e);
5059 case Tuple_kind:
5060 return compiler_tuple(c, e);
5061 }
5062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005063}
5064
5065static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005066compiler_visit_expr(struct compiler *c, expr_ty e)
5067{
5068 /* If expr e has a different line number than the last expr/stmt,
5069 set a new line number for the next instruction.
5070 */
5071 int old_lineno = c->u->u_lineno;
5072 int old_col_offset = c->u->u_col_offset;
5073 if (e->lineno != c->u->u_lineno) {
5074 c->u->u_lineno = e->lineno;
5075 c->u->u_lineno_set = 0;
5076 }
5077 /* Updating the column offset is always harmless. */
5078 c->u->u_col_offset = e->col_offset;
5079
5080 int res = compiler_visit_expr1(c, e);
5081
5082 if (old_lineno != c->u->u_lineno) {
5083 c->u->u_lineno = old_lineno;
5084 c->u->u_lineno_set = 0;
5085 }
5086 c->u->u_col_offset = old_col_offset;
5087 return res;
5088}
5089
5090static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005091compiler_augassign(struct compiler *c, stmt_ty s)
5092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 expr_ty e = s->v.AugAssign.target;
5094 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 switch (e->kind) {
5099 case Attribute_kind:
5100 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005101 AugLoad, e->lineno, e->col_offset,
5102 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 if (auge == NULL)
5104 return 0;
5105 VISIT(c, expr, auge);
5106 VISIT(c, expr, s->v.AugAssign.value);
5107 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5108 auge->v.Attribute.ctx = AugStore;
5109 VISIT(c, expr, auge);
5110 break;
5111 case Subscript_kind:
5112 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005113 AugLoad, e->lineno, e->col_offset,
5114 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 if (auge == NULL)
5116 return 0;
5117 VISIT(c, expr, auge);
5118 VISIT(c, expr, s->v.AugAssign.value);
5119 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5120 auge->v.Subscript.ctx = AugStore;
5121 VISIT(c, expr, auge);
5122 break;
5123 case Name_kind:
5124 if (!compiler_nameop(c, e->v.Name.id, Load))
5125 return 0;
5126 VISIT(c, expr, s->v.AugAssign.value);
5127 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5128 return compiler_nameop(c, e->v.Name.id, Store);
5129 default:
5130 PyErr_Format(PyExc_SystemError,
5131 "invalid node type (%d) for augmented assignment",
5132 e->kind);
5133 return 0;
5134 }
5135 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005136}
5137
5138static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005139check_ann_expr(struct compiler *c, expr_ty e)
5140{
5141 VISIT(c, expr, e);
5142 ADDOP(c, POP_TOP);
5143 return 1;
5144}
5145
5146static int
5147check_annotation(struct compiler *c, stmt_ty s)
5148{
5149 /* Annotations are only evaluated in a module or class. */
5150 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5151 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5152 return check_ann_expr(c, s->v.AnnAssign.annotation);
5153 }
5154 return 1;
5155}
5156
5157static int
5158check_ann_slice(struct compiler *c, slice_ty sl)
5159{
5160 switch(sl->kind) {
5161 case Index_kind:
5162 return check_ann_expr(c, sl->v.Index.value);
5163 case Slice_kind:
5164 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5165 return 0;
5166 }
5167 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5168 return 0;
5169 }
5170 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5171 return 0;
5172 }
5173 break;
5174 default:
5175 PyErr_SetString(PyExc_SystemError,
5176 "unexpected slice kind");
5177 return 0;
5178 }
5179 return 1;
5180}
5181
5182static int
5183check_ann_subscr(struct compiler *c, slice_ty sl)
5184{
5185 /* We check that everything in a subscript is defined at runtime. */
5186 Py_ssize_t i, n;
5187
5188 switch (sl->kind) {
5189 case Index_kind:
5190 case Slice_kind:
5191 if (!check_ann_slice(c, sl)) {
5192 return 0;
5193 }
5194 break;
5195 case ExtSlice_kind:
5196 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5197 for (i = 0; i < n; i++) {
5198 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5199 switch (subsl->kind) {
5200 case Index_kind:
5201 case Slice_kind:
5202 if (!check_ann_slice(c, subsl)) {
5203 return 0;
5204 }
5205 break;
5206 case ExtSlice_kind:
5207 default:
5208 PyErr_SetString(PyExc_SystemError,
5209 "extended slice invalid in nested slice");
5210 return 0;
5211 }
5212 }
5213 break;
5214 default:
5215 PyErr_Format(PyExc_SystemError,
5216 "invalid subscript kind %d", sl->kind);
5217 return 0;
5218 }
5219 return 1;
5220}
5221
5222static int
5223compiler_annassign(struct compiler *c, stmt_ty s)
5224{
5225 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005226 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005227
5228 assert(s->kind == AnnAssign_kind);
5229
5230 /* We perform the actual assignment first. */
5231 if (s->v.AnnAssign.value) {
5232 VISIT(c, expr, s->v.AnnAssign.value);
5233 VISIT(c, expr, targ);
5234 }
5235 switch (targ->kind) {
5236 case Name_kind:
5237 /* If we have a simple name in a module or class, store annotation. */
5238 if (s->v.AnnAssign.simple &&
5239 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5240 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005241 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5242 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5243 }
5244 else {
5245 VISIT(c, expr, s->v.AnnAssign.annotation);
5246 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005247 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005248 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005249 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005250 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005251 }
5252 break;
5253 case Attribute_kind:
5254 if (!s->v.AnnAssign.value &&
5255 !check_ann_expr(c, targ->v.Attribute.value)) {
5256 return 0;
5257 }
5258 break;
5259 case Subscript_kind:
5260 if (!s->v.AnnAssign.value &&
5261 (!check_ann_expr(c, targ->v.Subscript.value) ||
5262 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5263 return 0;
5264 }
5265 break;
5266 default:
5267 PyErr_Format(PyExc_SystemError,
5268 "invalid node type (%d) for annotated assignment",
5269 targ->kind);
5270 return 0;
5271 }
5272 /* Annotation is evaluated last. */
5273 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5274 return 0;
5275 }
5276 return 1;
5277}
5278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279/* Raises a SyntaxError and returns 0.
5280 If something goes wrong, a different exception may be raised.
5281*/
5282
5283static int
5284compiler_error(struct compiler *c, const char *errstr)
5285{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005286 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005288
Victor Stinner14e461d2013-08-26 22:28:21 +02005289 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 if (!loc) {
5291 Py_INCREF(Py_None);
5292 loc = Py_None;
5293 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005294 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005295 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 if (!u)
5297 goto exit;
5298 v = Py_BuildValue("(zO)", errstr, u);
5299 if (!v)
5300 goto exit;
5301 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005302 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 Py_DECREF(loc);
5304 Py_XDECREF(u);
5305 Py_XDECREF(v);
5306 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005307}
5308
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005309/* Emits a SyntaxWarning and returns 1 on success.
5310 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5311 and returns 0.
5312*/
5313static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005314compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005315{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005316 va_list vargs;
5317#ifdef HAVE_STDARG_PROTOTYPES
5318 va_start(vargs, format);
5319#else
5320 va_start(vargs);
5321#endif
5322 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5323 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005324 if (msg == NULL) {
5325 return 0;
5326 }
5327 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5328 c->u->u_lineno, NULL, NULL) < 0)
5329 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005330 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005331 /* Replace the SyntaxWarning exception with a SyntaxError
5332 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005333 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005334 assert(PyUnicode_AsUTF8(msg) != NULL);
5335 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005336 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005337 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005338 return 0;
5339 }
5340 Py_DECREF(msg);
5341 return 1;
5342}
5343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005344static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345compiler_handle_subscr(struct compiler *c, const char *kind,
5346 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 /* XXX this code is duplicated */
5351 switch (ctx) {
5352 case AugLoad: /* fall through to Load */
5353 case Load: op = BINARY_SUBSCR; break;
5354 case AugStore:/* fall through to Store */
5355 case Store: op = STORE_SUBSCR; break;
5356 case Del: op = DELETE_SUBSCR; break;
5357 case Param:
5358 PyErr_Format(PyExc_SystemError,
5359 "invalid %s kind %d in subscript\n",
5360 kind, ctx);
5361 return 0;
5362 }
5363 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005364 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 }
5366 else if (ctx == AugStore) {
5367 ADDOP(c, ROT_THREE);
5368 }
5369 ADDOP(c, op);
5370 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005371}
5372
5373static int
5374compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 int n = 2;
5377 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 /* only handles the cases where BUILD_SLICE is emitted */
5380 if (s->v.Slice.lower) {
5381 VISIT(c, expr, s->v.Slice.lower);
5382 }
5383 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005384 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 if (s->v.Slice.upper) {
5388 VISIT(c, expr, s->v.Slice.upper);
5389 }
5390 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005391 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 }
5393
5394 if (s->v.Slice.step) {
5395 n++;
5396 VISIT(c, expr, s->v.Slice.step);
5397 }
5398 ADDOP_I(c, BUILD_SLICE, n);
5399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400}
5401
5402static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5404 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 switch (s->kind) {
5407 case Slice_kind:
5408 return compiler_slice(c, s, ctx);
5409 case Index_kind:
5410 VISIT(c, expr, s->v.Index.value);
5411 break;
5412 case ExtSlice_kind:
5413 default:
5414 PyErr_SetString(PyExc_SystemError,
5415 "extended slice invalid in nested slice");
5416 return 0;
5417 }
5418 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005419}
5420
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005421static int
5422compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5423{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005424 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 switch (s->kind) {
5426 case Index_kind:
5427 kindname = "index";
5428 if (ctx != AugStore) {
5429 VISIT(c, expr, s->v.Index.value);
5430 }
5431 break;
5432 case Slice_kind:
5433 kindname = "slice";
5434 if (ctx != AugStore) {
5435 if (!compiler_slice(c, s, ctx))
5436 return 0;
5437 }
5438 break;
5439 case ExtSlice_kind:
5440 kindname = "extended slice";
5441 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005442 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 for (i = 0; i < n; i++) {
5444 slice_ty sub = (slice_ty)asdl_seq_GET(
5445 s->v.ExtSlice.dims, i);
5446 if (!compiler_visit_nested_slice(c, sub, ctx))
5447 return 0;
5448 }
5449 ADDOP_I(c, BUILD_TUPLE, n);
5450 }
5451 break;
5452 default:
5453 PyErr_Format(PyExc_SystemError,
5454 "invalid subscript kind %d", s->kind);
5455 return 0;
5456 }
5457 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458}
5459
Thomas Wouters89f507f2006-12-13 04:49:30 +00005460/* End of the compiler section, beginning of the assembler section */
5461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005462/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005463 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005464
5465 XXX must handle implicit jumps from one block to next
5466*/
5467
Thomas Wouters89f507f2006-12-13 04:49:30 +00005468struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 PyObject *a_bytecode; /* string containing bytecode */
5470 int a_offset; /* offset into bytecode */
5471 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005472 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 PyObject *a_lnotab; /* string containing lnotab */
5474 int a_lnotab_off; /* offset into lnotab */
5475 int a_lineno; /* last lineno of emitted instruction */
5476 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005477};
5478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479static void
T. Wouters99b54d62019-09-12 07:05:33 -07005480dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005481{
T. Wouters99b54d62019-09-12 07:05:33 -07005482 int i, j;
5483
5484 /* Get rid of recursion for normal control flow.
5485 Since the number of blocks is limited, unused space in a_postorder
5486 (from a_nblocks to end) can be used as a stack for still not ordered
5487 blocks. */
5488 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005489 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005490 assert(a->a_nblocks < j);
5491 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 }
T. Wouters99b54d62019-09-12 07:05:33 -07005493 while (j < end) {
5494 b = a->a_postorder[j++];
5495 for (i = 0; i < b->b_iused; i++) {
5496 struct instr *instr = &b->b_instr[i];
5497 if (instr->i_jrel || instr->i_jabs)
5498 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 }
T. Wouters99b54d62019-09-12 07:05:33 -07005500 assert(a->a_nblocks < j);
5501 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005503}
5504
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005505Py_LOCAL_INLINE(void)
5506stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005508 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005509 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005510 assert(b->b_startdepth < 0);
5511 b->b_startdepth = depth;
5512 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005514}
5515
5516/* Find the flow path that needs the largest stack. We assume that
5517 * cycles in the flow graph have no net effect on the stack depth.
5518 */
5519static int
5520stackdepth(struct compiler *c)
5521{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005522 basicblock *b, *entryblock = NULL;
5523 basicblock **stack, **sp;
5524 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 b->b_startdepth = INT_MIN;
5527 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005528 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 }
5530 if (!entryblock)
5531 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005532 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5533 if (!stack) {
5534 PyErr_NoMemory();
5535 return -1;
5536 }
5537
5538 sp = stack;
5539 stackdepth_push(&sp, entryblock, 0);
5540 while (sp != stack) {
5541 b = *--sp;
5542 int depth = b->b_startdepth;
5543 assert(depth >= 0);
5544 basicblock *next = b->b_next;
5545 for (int i = 0; i < b->b_iused; i++) {
5546 struct instr *instr = &b->b_instr[i];
5547 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5548 if (effect == PY_INVALID_STACK_EFFECT) {
5549 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5550 Py_FatalError("PyCompile_OpcodeStackEffect()");
5551 }
5552 int new_depth = depth + effect;
5553 if (new_depth > maxdepth) {
5554 maxdepth = new_depth;
5555 }
5556 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5557 if (instr->i_jrel || instr->i_jabs) {
5558 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5559 assert(effect != PY_INVALID_STACK_EFFECT);
5560 int target_depth = depth + effect;
5561 if (target_depth > maxdepth) {
5562 maxdepth = target_depth;
5563 }
5564 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005565 stackdepth_push(&sp, instr->i_target, target_depth);
5566 }
5567 depth = new_depth;
5568 if (instr->i_opcode == JUMP_ABSOLUTE ||
5569 instr->i_opcode == JUMP_FORWARD ||
5570 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005571 instr->i_opcode == RAISE_VARARGS ||
5572 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005573 {
5574 /* remaining code is dead */
5575 next = NULL;
5576 break;
5577 }
5578 }
5579 if (next != NULL) {
5580 stackdepth_push(&sp, next, depth);
5581 }
5582 }
5583 PyObject_Free(stack);
5584 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005585}
5586
5587static int
5588assemble_init(struct assembler *a, int nblocks, int firstlineno)
5589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 memset(a, 0, sizeof(struct assembler));
5591 a->a_lineno = firstlineno;
5592 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5593 if (!a->a_bytecode)
5594 return 0;
5595 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5596 if (!a->a_lnotab)
5597 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005598 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005599 PyErr_NoMemory();
5600 return 0;
5601 }
T. Wouters99b54d62019-09-12 07:05:33 -07005602 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005603 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005604 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 PyErr_NoMemory();
5606 return 0;
5607 }
5608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005609}
5610
5611static void
5612assemble_free(struct assembler *a)
5613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 Py_XDECREF(a->a_bytecode);
5615 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005616 if (a->a_postorder)
5617 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005618}
5619
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005620static int
5621blocksize(basicblock *b)
5622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 int i;
5624 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005627 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005629}
5630
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005631/* Appends a pair to the end of the line number table, a_lnotab, representing
5632 the instruction's bytecode offset and line number. See
5633 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005634
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005635static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005636assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005639 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005641
Serhiy Storchakaab874002016-09-11 13:48:15 +03005642 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 if(d_bytecode == 0 && d_lineno == 0)
5648 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 if (d_bytecode > 255) {
5651 int j, nbytes, ncodes = d_bytecode / 255;
5652 nbytes = a->a_lnotab_off + 2 * ncodes;
5653 len = PyBytes_GET_SIZE(a->a_lnotab);
5654 if (nbytes >= len) {
5655 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5656 len = nbytes;
5657 else if (len <= INT_MAX / 2)
5658 len *= 2;
5659 else {
5660 PyErr_NoMemory();
5661 return 0;
5662 }
5663 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5664 return 0;
5665 }
5666 lnotab = (unsigned char *)
5667 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5668 for (j = 0; j < ncodes; j++) {
5669 *lnotab++ = 255;
5670 *lnotab++ = 0;
5671 }
5672 d_bytecode -= ncodes * 255;
5673 a->a_lnotab_off += ncodes * 2;
5674 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005675 assert(0 <= d_bytecode && d_bytecode <= 255);
5676
5677 if (d_lineno < -128 || 127 < d_lineno) {
5678 int j, nbytes, ncodes, k;
5679 if (d_lineno < 0) {
5680 k = -128;
5681 /* use division on positive numbers */
5682 ncodes = (-d_lineno) / 128;
5683 }
5684 else {
5685 k = 127;
5686 ncodes = d_lineno / 127;
5687 }
5688 d_lineno -= ncodes * k;
5689 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 nbytes = a->a_lnotab_off + 2 * ncodes;
5691 len = PyBytes_GET_SIZE(a->a_lnotab);
5692 if (nbytes >= len) {
5693 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5694 len = nbytes;
5695 else if (len <= INT_MAX / 2)
5696 len *= 2;
5697 else {
5698 PyErr_NoMemory();
5699 return 0;
5700 }
5701 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5702 return 0;
5703 }
5704 lnotab = (unsigned char *)
5705 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5706 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005707 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 d_bytecode = 0;
5709 for (j = 1; j < ncodes; j++) {
5710 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005711 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 a->a_lnotab_off += ncodes * 2;
5714 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005715 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 len = PyBytes_GET_SIZE(a->a_lnotab);
5718 if (a->a_lnotab_off + 2 >= len) {
5719 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5720 return 0;
5721 }
5722 lnotab = (unsigned char *)
5723 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 a->a_lnotab_off += 2;
5726 if (d_bytecode) {
5727 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005728 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005729 }
5730 else { /* First line of a block; def stmt, etc. */
5731 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005732 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 }
5734 a->a_lineno = i->i_lineno;
5735 a->a_lineno_off = a->a_offset;
5736 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005737}
5738
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005739/* assemble_emit()
5740 Extend the bytecode with a new instruction.
5741 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005742*/
5743
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005744static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005745assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005746{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005747 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005749 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005750
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005751 arg = i->i_oparg;
5752 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 if (i->i_lineno && !assemble_lnotab(a, i))
5754 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005755 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 if (len > PY_SSIZE_T_MAX / 2)
5757 return 0;
5758 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5759 return 0;
5760 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005761 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005763 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005765}
5766
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005767static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005768assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005771 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 /* Compute the size of each block and fixup jump args.
5775 Replace block pointer with position in bytecode. */
5776 do {
5777 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005778 for (i = a->a_nblocks - 1; i >= 0; i--) {
5779 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 bsize = blocksize(b);
5781 b->b_offset = totsize;
5782 totsize += bsize;
5783 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005784 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5786 bsize = b->b_offset;
5787 for (i = 0; i < b->b_iused; i++) {
5788 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005789 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 /* Relative jumps are computed relative to
5791 the instruction pointer after fetching
5792 the jump instruction.
5793 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005794 bsize += isize;
5795 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005797 if (instr->i_jrel) {
5798 instr->i_oparg -= bsize;
5799 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005800 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005801 if (instrsize(instr->i_oparg) != isize) {
5802 extended_arg_recompile = 1;
5803 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 }
5806 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 /* XXX: This is an awful hack that could hurt performance, but
5809 on the bright side it should work until we come up
5810 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 The issue is that in the first loop blocksize() is called
5813 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005814 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 So we loop until we stop seeing new EXTENDED_ARGs.
5818 The only EXTENDED_ARGs that could be popping up are
5819 ones in jump instructions. So this should converge
5820 fairly quickly.
5821 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005822 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005823}
5824
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005825static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005826dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005829 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 tuple = PyTuple_New(size);
5832 if (tuple == NULL)
5833 return NULL;
5834 while (PyDict_Next(dict, &pos, &k, &v)) {
5835 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005836 Py_INCREF(k);
5837 assert((i - offset) < size);
5838 assert((i - offset) >= 0);
5839 PyTuple_SET_ITEM(tuple, i - offset, k);
5840 }
5841 return tuple;
5842}
5843
5844static PyObject *
5845consts_dict_keys_inorder(PyObject *dict)
5846{
5847 PyObject *consts, *k, *v;
5848 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5849
5850 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5851 if (consts == NULL)
5852 return NULL;
5853 while (PyDict_Next(dict, &pos, &k, &v)) {
5854 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005855 /* The keys of the dictionary can be tuples wrapping a contant.
5856 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5857 * the object we want is always second. */
5858 if (PyTuple_CheckExact(k)) {
5859 k = PyTuple_GET_ITEM(k, 1);
5860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005862 assert(i < size);
5863 assert(i >= 0);
5864 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005866 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005867}
5868
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005869static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005870compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005873 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005875 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 if (ste->ste_nested)
5877 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005878 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005880 if (!ste->ste_generator && ste->ste_coroutine)
5881 flags |= CO_COROUTINE;
5882 if (ste->ste_generator && ste->ste_coroutine)
5883 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 if (ste->ste_varargs)
5885 flags |= CO_VARARGS;
5886 if (ste->ste_varkeywords)
5887 flags |= CO_VARKEYWORDS;
5888 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 /* (Only) inherit compilerflags in PyCF_MASK */
5891 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005892
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005893 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5894 ste->ste_coroutine &&
5895 !ste->ste_generator) {
5896 flags |= CO_COROUTINE;
5897 }
5898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005900}
5901
INADA Naokic2e16072018-11-26 21:23:22 +09005902// Merge *tuple* with constant cache.
5903// Unlike merge_consts_recursive(), this function doesn't work recursively.
5904static int
5905merge_const_tuple(struct compiler *c, PyObject **tuple)
5906{
5907 assert(PyTuple_CheckExact(*tuple));
5908
5909 PyObject *key = _PyCode_ConstantKey(*tuple);
5910 if (key == NULL) {
5911 return 0;
5912 }
5913
5914 // t is borrowed reference
5915 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5916 Py_DECREF(key);
5917 if (t == NULL) {
5918 return 0;
5919 }
5920 if (t == key) { // tuple is new constant.
5921 return 1;
5922 }
5923
5924 PyObject *u = PyTuple_GET_ITEM(t, 1);
5925 Py_INCREF(u);
5926 Py_DECREF(*tuple);
5927 *tuple = u;
5928 return 1;
5929}
5930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005931static PyCodeObject *
5932makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 PyObject *tmp;
5935 PyCodeObject *co = NULL;
5936 PyObject *consts = NULL;
5937 PyObject *names = NULL;
5938 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 PyObject *name = NULL;
5940 PyObject *freevars = NULL;
5941 PyObject *cellvars = NULL;
5942 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005943 Py_ssize_t nlocals;
5944 int nlocals_int;
5945 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005946 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005947
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005948 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 names = dict_keys_inorder(c->u->u_names, 0);
5950 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5951 if (!consts || !names || !varnames)
5952 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005954 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5955 if (!cellvars)
5956 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005957 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005958 if (!freevars)
5959 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005960
INADA Naokic2e16072018-11-26 21:23:22 +09005961 if (!merge_const_tuple(c, &names) ||
5962 !merge_const_tuple(c, &varnames) ||
5963 !merge_const_tuple(c, &cellvars) ||
5964 !merge_const_tuple(c, &freevars))
5965 {
5966 goto error;
5967 }
5968
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005969 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005970 assert(nlocals < INT_MAX);
5971 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 flags = compute_code_flags(c);
5974 if (flags < 0)
5975 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5978 if (!bytecode)
5979 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5982 if (!tmp)
5983 goto error;
5984 Py_DECREF(consts);
5985 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005986 if (!merge_const_tuple(c, &consts)) {
5987 goto error;
5988 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005990 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005991 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005992 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005993 maxdepth = stackdepth(c);
5994 if (maxdepth < 0) {
5995 goto error;
5996 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005997 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005998 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005999 maxdepth, flags, bytecode, consts, names,
6000 varnames, freevars, cellvars, c->c_filename,
6001 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006002 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 Py_XDECREF(consts);
6004 Py_XDECREF(names);
6005 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 Py_XDECREF(name);
6007 Py_XDECREF(freevars);
6008 Py_XDECREF(cellvars);
6009 Py_XDECREF(bytecode);
6010 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006011}
6012
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006013
6014/* For debugging purposes only */
6015#if 0
6016static void
6017dump_instr(const struct instr *i)
6018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 const char *jrel = i->i_jrel ? "jrel " : "";
6020 const char *jabs = i->i_jabs ? "jabs " : "";
6021 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006024 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006026 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006027 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6028 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006029}
6030
6031static void
6032dump_basicblock(const basicblock *b)
6033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006034 const char *seen = b->b_seen ? "seen " : "";
6035 const char *b_return = b->b_return ? "return " : "";
6036 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6037 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6038 if (b->b_instr) {
6039 int i;
6040 for (i = 0; i < b->b_iused; i++) {
6041 fprintf(stderr, " [%02d] ", i);
6042 dump_instr(b->b_instr + i);
6043 }
6044 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006045}
6046#endif
6047
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006048static PyCodeObject *
6049assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006051 basicblock *b, *entryblock;
6052 struct assembler a;
6053 int i, j, nblocks;
6054 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006056 /* Make sure every block that falls off the end returns None.
6057 XXX NEXT_BLOCK() isn't quite right, because if the last
6058 block ends with a jump or return b_next shouldn't set.
6059 */
6060 if (!c->u->u_curblock->b_return) {
6061 NEXT_BLOCK(c);
6062 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006063 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 ADDOP(c, RETURN_VALUE);
6065 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006067 nblocks = 0;
6068 entryblock = NULL;
6069 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6070 nblocks++;
6071 entryblock = b;
6072 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006074 /* Set firstlineno if it wasn't explicitly set. */
6075 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006076 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006077 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6078 else
6079 c->u->u_firstlineno = 1;
6080 }
6081 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6082 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006083 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 /* Can't modify the bytecode after computing jump offsets. */
6086 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006087
T. Wouters99b54d62019-09-12 07:05:33 -07006088 /* Emit code in reverse postorder from dfs. */
6089 for (i = a.a_nblocks - 1; i >= 0; i--) {
6090 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006091 for (j = 0; j < b->b_iused; j++)
6092 if (!assemble_emit(&a, &b->b_instr[j]))
6093 goto error;
6094 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006096 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6097 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006098 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006099 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006101 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006102 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006103 assemble_free(&a);
6104 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006105}
Georg Brandl8334fd92010-12-04 10:26:46 +00006106
6107#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006108PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006109PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6110 PyArena *arena)
6111{
6112 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6113}