blob: 98a4afa168c47cce0f116e0fb1f7aaf541ec1405 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Victor Stinnerc96be812019-05-14 17:34:56 +020027#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800200static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200201static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500203static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400204static int compiler_async_with(struct compiler *, stmt_ty, int);
205static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100206static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400208 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500209static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400210static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700212static int compiler_sync_comprehension_generator(
213 struct compiler *c,
214 asdl_seq *generators, int gen_index,
215 expr_ty elt, expr_ty val, int type);
216
217static int compiler_async_comprehension_generator(
218 struct compiler *c,
219 asdl_seq *generators, int gen_index,
220 expr_ty elt, expr_ty val, int type);
221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000223static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400225#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 /* Name mangling: __private becomes _classname__private.
231 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 PyObject *result;
233 size_t nlen, plen, ipriv;
234 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 PyUnicode_READ_CHAR(ident, 0) != '_' ||
237 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_INCREF(ident);
239 return ident;
240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 nlen = PyUnicode_GET_LENGTH(ident);
242 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 The only time a name with a dot can occur is when
246 we are compiling an import statement that has a
247 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 TODO(jhylton): Decide whether we want to support
250 mangling of the module name, e.g. __M.X.
251 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
253 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
254 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_INCREF(ident);
256 return ident; /* Don't mangle __whatever__ */
257 }
258 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 ipriv = 0;
260 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
261 ipriv++;
262 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_INCREF(ident);
264 return ident; /* Don't mangle if class is just underscores */
265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200266 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000267
Antoine Pitrou55bff892013-04-06 21:21:04 +0200268 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
269 PyErr_SetString(PyExc_OverflowError,
270 "private identifier too large to be mangled");
271 return NULL;
272 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000273
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
275 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
276 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
277
278 result = PyUnicode_New(1 + nlen + plen, maxchar);
279 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
282 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200283 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
284 Py_DECREF(result);
285 return NULL;
286 }
287 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
288 Py_DECREF(result);
289 return NULL;
290 }
Victor Stinner8f825062012-04-27 13:55:39 +0200291 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000293}
294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000295static int
296compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299
INADA Naokic2e16072018-11-26 21:23:22 +0900300 c->c_const_cache = PyDict_New();
301 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900303 }
304
305 c->c_stack = PyList_New(0);
306 if (!c->c_stack) {
307 Py_CLEAR(c->c_const_cache);
308 return 0;
309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312}
313
314PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200315PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
316 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 struct compiler c;
319 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200320 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200322 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!__doc__) {
325 __doc__ = PyUnicode_InternFromString("__doc__");
326 if (!__doc__)
327 return NULL;
328 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000329 if (!__annotations__) {
330 __annotations__ = PyUnicode_InternFromString("__annotations__");
331 if (!__annotations__)
332 return NULL;
333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!compiler_init(&c))
335 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 c.c_filename = filename;
338 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200339 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (c.c_future == NULL)
341 goto finally;
342 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 flags = &local_flags;
344 }
345 merged = c.c_future->ff_features | flags->cf_flags;
346 c.c_future->ff_features = merged;
347 flags->cf_flags = merged;
348 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200349 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100351 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200353 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900354 goto finally;
355 }
356
Victor Stinner14e461d2013-08-26 22:28:21 +0200357 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (c.c_st == NULL) {
359 if (!PyErr_Occurred())
360 PyErr_SetString(PyExc_SystemError, "no symtable");
361 goto finally;
362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Thomas Wouters1175c432006-02-27 22:49:54 +0000366 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 compiler_free(&c);
368 assert(co || PyErr_Occurred());
369 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370}
371
372PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200373PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
374 int optimize, PyArena *arena)
375{
376 PyObject *filename;
377 PyCodeObject *co;
378 filename = PyUnicode_DecodeFSDefault(filename_str);
379 if (filename == NULL)
380 return NULL;
381 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
382 Py_DECREF(filename);
383 return co;
384
385}
386
387PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388PyNode_Compile(struct _node *n, const char *filename)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyCodeObject *co = NULL;
391 mod_ty mod;
392 PyArena *arena = PyArena_New();
393 if (!arena)
394 return NULL;
395 mod = PyAST_FromNode(n, NULL, filename, arena);
396 if (mod)
397 co = PyAST_Compile(mod, filename, NULL, arena);
398 PyArena_Free(arena);
399 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000400}
401
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (c->c_st)
406 PySymtable_Free(c->c_st);
407 if (c->c_future)
408 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200409 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900410 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000412}
413
Guido van Rossum79f25d91997-04-29 20:08:16 +0000414static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_ssize_t i, n;
418 PyObject *v, *k;
419 PyObject *dict = PyDict_New();
420 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 n = PyList_Size(list);
423 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100424 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (!v) {
426 Py_DECREF(dict);
427 return NULL;
428 }
429 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300430 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(v);
432 Py_DECREF(dict);
433 return NULL;
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(v);
436 }
437 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438}
439
440/* Return new dict containing names from src that match scope(s).
441
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000442src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444values are integers, starting at offset and increasing by one for
445each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446*/
447
448static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100449dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700451 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500453 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 assert(offset >= 0);
456 if (dest == NULL)
457 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Meador Inge2ca63152012-07-18 14:20:11 -0500459 /* Sort the keys so that we have a deterministic order on the indexes
460 saved in the returned dictionary. These indexes are used as indexes
461 into the free and cell var storage. Therefore if they aren't
462 deterministic, then the generated bytecode is not deterministic.
463 */
464 sorted_keys = PyDict_Keys(src);
465 if (sorted_keys == NULL)
466 return NULL;
467 if (PyList_Sort(sorted_keys) != 0) {
468 Py_DECREF(sorted_keys);
469 return NULL;
470 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500471 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500472
473 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* XXX this should probably be a macro in symtable.h */
475 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500476 k = PyList_GET_ITEM(sorted_keys, key_i);
477 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 assert(PyLong_Check(v));
479 vi = PyLong_AS_LONG(v);
480 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300483 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500485 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_DECREF(dest);
487 return NULL;
488 }
489 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300490 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(item);
493 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
496 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 }
498 }
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000501}
502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503static void
504compiler_unit_check(struct compiler_unit *u)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 basicblock *block;
507 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700508 assert((uintptr_t)block != 0xcbcbcbcbU);
509 assert((uintptr_t)block != 0xfbfbfbfbU);
510 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (block->b_instr != NULL) {
512 assert(block->b_ialloc > 0);
513 assert(block->b_iused > 0);
514 assert(block->b_ialloc >= block->b_iused);
515 }
516 else {
517 assert (block->b_iused == 0);
518 assert (block->b_ialloc == 0);
519 }
520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521}
522
523static void
524compiler_unit_free(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 compiler_unit_check(u);
529 b = u->u_blocks;
530 while (b != NULL) {
531 if (b->b_instr)
532 PyObject_Free((void *)b->b_instr);
533 next = b->b_list;
534 PyObject_Free((void *)b);
535 b = next;
536 }
537 Py_CLEAR(u->u_ste);
538 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400539 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 Py_CLEAR(u->u_consts);
541 Py_CLEAR(u->u_names);
542 Py_CLEAR(u->u_varnames);
543 Py_CLEAR(u->u_freevars);
544 Py_CLEAR(u->u_cellvars);
545 Py_CLEAR(u->u_private);
546 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547}
548
549static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100550compiler_enter_scope(struct compiler *c, identifier name,
551 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100554 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
557 struct compiler_unit));
558 if (!u) {
559 PyErr_NoMemory();
560 return 0;
561 }
562 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100563 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100565 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 u->u_kwonlyargcount = 0;
567 u->u_ste = PySymtable_Lookup(c->c_st, key);
568 if (!u->u_ste) {
569 compiler_unit_free(u);
570 return 0;
571 }
572 Py_INCREF(name);
573 u->u_name = name;
574 u->u_varnames = list2dict(u->u_ste->ste_varnames);
575 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
576 if (!u->u_varnames || !u->u_cellvars) {
577 compiler_unit_free(u);
578 return 0;
579 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500580 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000581 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300583 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 int res;
585 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200586 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 name = _PyUnicode_FromId(&PyId___class__);
588 if (!name) {
589 compiler_unit_free(u);
590 return 0;
591 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300592 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (res < 0) {
594 compiler_unit_free(u);
595 return 0;
596 }
597 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200600 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (!u->u_freevars) {
602 compiler_unit_free(u);
603 return 0;
604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 u->u_blocks = NULL;
607 u->u_nfblocks = 0;
608 u->u_firstlineno = lineno;
609 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000610 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_lineno_set = 0;
612 u->u_consts = PyDict_New();
613 if (!u->u_consts) {
614 compiler_unit_free(u);
615 return 0;
616 }
617 u->u_names = PyDict_New();
618 if (!u->u_names) {
619 compiler_unit_free(u);
620 return 0;
621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Push the old compiler_unit on the stack. */
626 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400627 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
629 Py_XDECREF(capsule);
630 compiler_unit_free(u);
631 return 0;
632 }
633 Py_DECREF(capsule);
634 u->u_private = c->u->u_private;
635 Py_XINCREF(u->u_private);
636 }
637 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100640
641 block = compiler_new_block(c);
642 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100644 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400646 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
647 if (!compiler_set_qualname(c))
648 return 0;
649 }
650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652}
653
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000654static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655compiler_exit_scope(struct compiler *c)
656{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100657 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 c->c_nestlevel--;
661 compiler_unit_free(c->u);
662 /* Restore c->u to the parent unit. */
663 n = PyList_GET_SIZE(c->c_stack) - 1;
664 if (n >= 0) {
665 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400666 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(c->u);
668 /* we are deleting from a list so this really shouldn't fail */
669 if (PySequence_DelItem(c->c_stack, n) < 0)
670 Py_FatalError("compiler_exit_scope()");
671 compiler_unit_check(c->u);
672 }
673 else
674 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676}
677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678static int
679compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100681 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682 _Py_static_string(dot_locals, ".<locals>");
683 Py_ssize_t stack_size;
684 struct compiler_unit *u = c->u;
685 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100686
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400687 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400689 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 if (stack_size > 1) {
691 int scope, force_global = 0;
692 struct compiler_unit *parent;
693 PyObject *mangled, *capsule;
694
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400695 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400696 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 assert(parent);
698
Yury Selivanov75445082015-05-11 22:57:16 -0400699 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
700 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
701 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 assert(u->u_name);
703 mangled = _Py_Mangle(parent->u_private, u->u_name);
704 if (!mangled)
705 return 0;
706 scope = PyST_GetScope(parent->u_ste, mangled);
707 Py_DECREF(mangled);
708 assert(scope != GLOBAL_IMPLICIT);
709 if (scope == GLOBAL_EXPLICIT)
710 force_global = 1;
711 }
712
713 if (!force_global) {
714 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400715 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400716 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
717 dot_locals_str = _PyUnicode_FromId(&dot_locals);
718 if (dot_locals_str == NULL)
719 return 0;
720 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
721 if (base == NULL)
722 return 0;
723 }
724 else {
725 Py_INCREF(parent->u_qualname);
726 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400727 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728 }
729 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400730
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400731 if (base != NULL) {
732 dot_str = _PyUnicode_FromId(&dot);
733 if (dot_str == NULL) {
734 Py_DECREF(base);
735 return 0;
736 }
737 name = PyUnicode_Concat(base, dot_str);
738 Py_DECREF(base);
739 if (name == NULL)
740 return 0;
741 PyUnicode_Append(&name, u->u_name);
742 if (name == NULL)
743 return 0;
744 }
745 else {
746 Py_INCREF(u->u_name);
747 name = u->u_name;
748 }
749 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100750
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400751 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100752}
753
Eric V. Smith235a6f02015-09-19 14:51:32 -0400754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755/* Allocate a new block and return a pointer to it.
756 Returns NULL on error.
757*/
758
759static basicblock *
760compiler_new_block(struct compiler *c)
761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 basicblock *b;
763 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 u = c->u;
766 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
767 if (b == NULL) {
768 PyErr_NoMemory();
769 return NULL;
770 }
771 memset((void *)b, 0, sizeof(basicblock));
772 /* Extend the singly linked list of blocks with new block. */
773 b->b_list = u->u_blocks;
774 u->u_blocks = b;
775 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779compiler_next_block(struct compiler *c)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 basicblock *block = compiler_new_block(c);
782 if (block == NULL)
783 return NULL;
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789static basicblock *
790compiler_use_next_block(struct compiler *c, basicblock *block)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(block != NULL);
793 c->u->u_curblock->b_next = block;
794 c->u->u_curblock = block;
795 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796}
797
798/* Returns the offset of the next instruction in the current block's
799 b_instr array. Resizes the b_instr as necessary.
800 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802
803static int
804compiler_next_instr(struct compiler *c, basicblock *b)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(b != NULL);
807 if (b->b_instr == NULL) {
808 b->b_instr = (struct instr *)PyObject_Malloc(
809 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
810 if (b->b_instr == NULL) {
811 PyErr_NoMemory();
812 return -1;
813 }
814 b->b_ialloc = DEFAULT_BLOCK_SIZE;
815 memset((char *)b->b_instr, 0,
816 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
817 }
818 else if (b->b_iused == b->b_ialloc) {
819 struct instr *tmp;
820 size_t oldsize, newsize;
821 oldsize = b->b_ialloc * sizeof(struct instr);
822 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000823
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700824 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyErr_NoMemory();
826 return -1;
827 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (newsize == 0) {
830 PyErr_NoMemory();
831 return -1;
832 }
833 b->b_ialloc <<= 1;
834 tmp = (struct instr *)PyObject_Realloc(
835 (void *)b->b_instr, newsize);
836 if (tmp == NULL) {
837 PyErr_NoMemory();
838 return -1;
839 }
840 b->b_instr = tmp;
841 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
842 }
843 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844}
845
Christian Heimes2202f872008-02-06 14:31:34 +0000846/* Set the i_lineno member of the instruction at offset off if the
847 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 already been set. If it has been set, the call has no effect.
849
Christian Heimes2202f872008-02-06 14:31:34 +0000850 The line number is reset in the following cases:
851 - when entering a new scope
852 - on each statement
853 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200854 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000855 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858static void
859compiler_set_lineno(struct compiler *c, int off)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 basicblock *b;
862 if (c->u->u_lineno_set)
863 return;
864 c->u->u_lineno_set = 1;
865 b = c->u->u_curblock;
866 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867}
868
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200869/* Return the stack effect of opcode with argument oparg.
870
871 Some opcodes have different stack effect when jump to the target and
872 when not jump. The 'jump' parameter specifies the case:
873
874 * 0 -- when not jump
875 * 1 -- when jump
876 * -1 -- maximal
877 */
878/* XXX Make the stack effect of WITH_CLEANUP_START and
879 WITH_CLEANUP_FINISH deterministic. */
880static int
881stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300884 case NOP:
885 case EXTENDED_ARG:
886 return 0;
887
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200888 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case POP_TOP:
890 return -1;
891 case ROT_TWO:
892 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200893 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return 0;
895 case DUP_TOP:
896 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000897 case DUP_TOP_TWO:
898 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 case UNARY_POSITIVE:
902 case UNARY_NEGATIVE:
903 case UNARY_NOT:
904 case UNARY_INVERT:
905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case SET_ADD:
908 case LIST_APPEND:
909 return -1;
910 case MAP_ADD:
911 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000912
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200913 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_POWER:
915 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400916 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case BINARY_MODULO:
918 case BINARY_ADD:
919 case BINARY_SUBTRACT:
920 case BINARY_SUBSCR:
921 case BINARY_FLOOR_DIVIDE:
922 case BINARY_TRUE_DIVIDE:
923 return -1;
924 case INPLACE_FLOOR_DIVIDE:
925 case INPLACE_TRUE_DIVIDE:
926 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case INPLACE_ADD:
929 case INPLACE_SUBTRACT:
930 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400931 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case INPLACE_MODULO:
933 return -1;
934 case STORE_SUBSCR:
935 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case DELETE_SUBSCR:
937 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case BINARY_LSHIFT:
940 case BINARY_RSHIFT:
941 case BINARY_AND:
942 case BINARY_XOR:
943 case BINARY_OR:
944 return -1;
945 case INPLACE_POWER:
946 return -1;
947 case GET_ITER:
948 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case PRINT_EXPR:
951 return -1;
952 case LOAD_BUILD_CLASS:
953 return 1;
954 case INPLACE_LSHIFT:
955 case INPLACE_RSHIFT:
956 case INPLACE_AND:
957 case INPLACE_XOR:
958 case INPLACE_OR:
959 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200962 /* 1 in the normal flow.
963 * Restore the stack position and push 6 values before jumping to
964 * the handler if an exception be raised. */
965 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case RETURN_VALUE:
967 return -1;
968 case IMPORT_STAR:
969 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700970 case SETUP_ANNOTATIONS:
971 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case YIELD_VALUE:
973 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500974 case YIELD_FROM:
975 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 case POP_BLOCK:
977 return 0;
978 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case STORE_NAME:
982 return -1;
983 case DELETE_NAME:
984 return 0;
985 case UNPACK_SEQUENCE:
986 return oparg-1;
987 case UNPACK_EX:
988 return (oparg&0xFF) + (oparg>>8);
989 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200990 /* -1 at end of iterator, 1 if continue iterating. */
991 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case STORE_ATTR:
994 return -2;
995 case DELETE_ATTR:
996 return -1;
997 case STORE_GLOBAL:
998 return -1;
999 case DELETE_GLOBAL:
1000 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case LOAD_CONST:
1002 return 1;
1003 case LOAD_NAME:
1004 return 1;
1005 case BUILD_TUPLE:
1006 case BUILD_LIST:
1007 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001008 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001010 case BUILD_LIST_UNPACK:
1011 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001012 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001013 case BUILD_SET_UNPACK:
1014 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001015 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001016 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001018 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001019 case BUILD_CONST_KEY_MAP:
1020 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_ATTR:
1022 return 0;
1023 case COMPARE_OP:
1024 return -1;
1025 case IMPORT_NAME:
1026 return -1;
1027 case IMPORT_FROM:
1028 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001030 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case JUMP_ABSOLUTE:
1033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001035 case JUMP_IF_TRUE_OR_POP:
1036 case JUMP_IF_FALSE_OR_POP:
1037 return jump ? 0 : -1;
1038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case POP_JUMP_IF_FALSE:
1040 case POP_JUMP_IF_TRUE:
1041 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case LOAD_GLOBAL:
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001046 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* 0 in the normal flow.
1049 * Restore the stack position and push 6 values before jumping to
1050 * the handler if an exception be raised. */
1051 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001052 case RERAISE:
1053 return -3;
1054
1055 case WITH_EXCEPT_START:
1056 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_FAST:
1059 return 1;
1060 case STORE_FAST:
1061 return -1;
1062 case DELETE_FAST:
1063 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case RAISE_VARARGS:
1066 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001070 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001071 case CALL_METHOD:
1072 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg-1;
1075 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001076 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001077 case MAKE_FUNCTION:
1078 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1079 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case BUILD_SLICE:
1081 if (oparg == 3)
1082 return -2;
1083 else
1084 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case LOAD_CLOSURE:
1088 return 1;
1089 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001090 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 return 1;
1092 case STORE_DEREF:
1093 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001094 case DELETE_DEREF:
1095 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001096
1097 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001098 case GET_AWAITABLE:
1099 return 0;
1100 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001101 /* 0 in the normal flow.
1102 * Restore the stack position to the position before the result
1103 * of __aenter__ and push 6 values before jumping to the handler
1104 * if an exception be raised. */
1105 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001106 case BEFORE_ASYNC_WITH:
1107 return 1;
1108 case GET_AITER:
1109 return 0;
1110 case GET_ANEXT:
1111 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001112 case GET_YIELD_FROM_ITER:
1113 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001114 case END_ASYNC_FOR:
1115 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001116 case FORMAT_VALUE:
1117 /* If there's a fmt_spec on the stack, we go from 2->1,
1118 else 1->1. */
1119 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001120 case LOAD_METHOD:
1121 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001122 case LOAD_ASSERTION_ERROR:
1123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001125 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
Larry Hastings3a907972013-11-23 14:49:22 -08001127 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128}
1129
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001130int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001131PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1132{
1133 return stack_effect(opcode, oparg, jump);
1134}
1135
1136int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001137PyCompile_OpcodeStackEffect(int opcode, int oparg)
1138{
1139 return stack_effect(opcode, oparg, -1);
1140}
1141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142/* Add an opcode with no argument.
1143 Returns 0 on failure, 1 on success.
1144*/
1145
1146static int
1147compiler_addop(struct compiler *c, int opcode)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 basicblock *b;
1150 struct instr *i;
1151 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001152 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001153 if (c->c_do_not_emit_bytecode) {
1154 return 1;
1155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 off = compiler_next_instr(c, c->u->u_curblock);
1157 if (off < 0)
1158 return 0;
1159 b = c->u->u_curblock;
1160 i = &b->b_instr[off];
1161 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001162 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (opcode == RETURN_VALUE)
1164 b->b_return = 1;
1165 compiler_set_lineno(c, off);
1166 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167}
1168
Victor Stinnerf8e32212013-11-19 23:56:34 +01001169static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1171{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001175 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001177 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001179 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001180 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001181 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return -1;
1184 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001185 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(v);
1187 return -1;
1188 }
1189 Py_DECREF(v);
1190 }
1191 else
1192 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001193 return arg;
1194}
1195
INADA Naokic2e16072018-11-26 21:23:22 +09001196// Merge const *o* recursively and return constant key object.
1197static PyObject*
1198merge_consts_recursive(struct compiler *c, PyObject *o)
1199{
1200 // None and Ellipsis are singleton, and key is the singleton.
1201 // No need to merge object and key.
1202 if (o == Py_None || o == Py_Ellipsis) {
1203 Py_INCREF(o);
1204 return o;
1205 }
1206
1207 PyObject *key = _PyCode_ConstantKey(o);
1208 if (key == NULL) {
1209 return NULL;
1210 }
1211
1212 // t is borrowed reference
1213 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1214 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001215 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001216 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001217 Py_DECREF(key);
1218 return t;
1219 }
1220
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001222 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001223 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001224 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 Py_ssize_t len = PyTuple_GET_SIZE(o);
1226 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001227 PyObject *item = PyTuple_GET_ITEM(o, i);
1228 PyObject *u = merge_consts_recursive(c, item);
1229 if (u == NULL) {
1230 Py_DECREF(key);
1231 return NULL;
1232 }
1233
1234 // See _PyCode_ConstantKey()
1235 PyObject *v; // borrowed
1236 if (PyTuple_CheckExact(u)) {
1237 v = PyTuple_GET_ITEM(u, 1);
1238 }
1239 else {
1240 v = u;
1241 }
1242 if (v != item) {
1243 Py_INCREF(v);
1244 PyTuple_SET_ITEM(o, i, v);
1245 Py_DECREF(item);
1246 }
1247
1248 Py_DECREF(u);
1249 }
1250 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001251 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001252 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001253 // constant keys.
1254 // See _PyCode_ConstantKey() for detail.
1255 assert(PyTuple_CheckExact(key));
1256 assert(PyTuple_GET_SIZE(key) == 2);
1257
1258 Py_ssize_t len = PySet_GET_SIZE(o);
1259 if (len == 0) { // empty frozenset should not be re-created.
1260 return key;
1261 }
1262 PyObject *tuple = PyTuple_New(len);
1263 if (tuple == NULL) {
1264 Py_DECREF(key);
1265 return NULL;
1266 }
1267 Py_ssize_t i = 0, pos = 0;
1268 PyObject *item;
1269 Py_hash_t hash;
1270 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1271 PyObject *k = merge_consts_recursive(c, item);
1272 if (k == NULL) {
1273 Py_DECREF(tuple);
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 PyObject *u;
1278 if (PyTuple_CheckExact(k)) {
1279 u = PyTuple_GET_ITEM(k, 1);
1280 Py_INCREF(u);
1281 Py_DECREF(k);
1282 }
1283 else {
1284 u = k;
1285 }
1286 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1287 i++;
1288 }
1289
1290 // Instead of rewriting o, we create new frozenset and embed in the
1291 // key tuple. Caller should get merged frozenset from the key tuple.
1292 PyObject *new = PyFrozenSet_New(tuple);
1293 Py_DECREF(tuple);
1294 if (new == NULL) {
1295 Py_DECREF(key);
1296 return NULL;
1297 }
1298 assert(PyTuple_GET_ITEM(key, 1) == o);
1299 Py_DECREF(o);
1300 PyTuple_SET_ITEM(key, 1, new);
1301 }
INADA Naokic2e16072018-11-26 21:23:22 +09001302
1303 return key;
1304}
1305
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001306static Py_ssize_t
1307compiler_add_const(struct compiler *c, PyObject *o)
1308{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001309 if (c->c_do_not_emit_bytecode) {
1310 return 0;
1311 }
1312
INADA Naokic2e16072018-11-26 21:23:22 +09001313 PyObject *key = merge_consts_recursive(c, o);
1314 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001315 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001316 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001317
INADA Naokic2e16072018-11-26 21:23:22 +09001318 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1319 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321}
1322
1323static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001324compiler_addop_load_const(struct compiler *c, PyObject *o)
1325{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001326 if (c->c_do_not_emit_bytecode) {
1327 return 1;
1328 }
1329
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001330 Py_ssize_t arg = compiler_add_const(c, o);
1331 if (arg < 0)
1332 return 0;
1333 return compiler_addop_i(c, LOAD_CONST, arg);
1334}
1335
1336static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001340 if (c->c_do_not_emit_bytecode) {
1341 return 1;
1342 }
1343
Victor Stinnerad9a0662013-11-19 22:23:20 +01001344 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return compiler_addop_i(c, opcode, arg);
1348}
1349
1350static int
1351compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001354 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001355
1356 if (c->c_do_not_emit_bytecode) {
1357 return 1;
1358 }
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1361 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363 arg = compiler_add_o(c, dict, mangled);
1364 Py_DECREF(mangled);
1365 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001367 return compiler_addop_i(c, opcode, arg);
1368}
1369
1370/* Add an opcode with an integer argument.
1371 Returns 0 on failure, 1 on success.
1372*/
1373
1374static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001375compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 struct instr *i;
1378 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001379
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001380 if (c->c_do_not_emit_bytecode) {
1381 return 1;
1382 }
1383
Victor Stinner2ad474b2016-03-01 23:34:47 +01001384 /* oparg value is unsigned, but a signed C int is usually used to store
1385 it in the C code (like Python/ceval.c).
1386
1387 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1388
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001389 The argument of a concrete bytecode instruction is limited to 8-bit.
1390 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1391 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001392 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 off = compiler_next_instr(c, c->u->u_curblock);
1395 if (off < 0)
1396 return 0;
1397 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001398 i->i_opcode = opcode;
1399 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 compiler_set_lineno(c, off);
1401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402}
1403
1404static int
1405compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 struct instr *i;
1408 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001410 if (c->c_do_not_emit_bytecode) {
1411 return 1;
1412 }
1413
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001414 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 assert(b != NULL);
1416 off = compiler_next_instr(c, c->u->u_curblock);
1417 if (off < 0)
1418 return 0;
1419 i = &c->u->u_curblock->b_instr[off];
1420 i->i_opcode = opcode;
1421 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (absolute)
1423 i->i_jabs = 1;
1424 else
1425 i->i_jrel = 1;
1426 compiler_set_lineno(c, off);
1427 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428}
1429
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001430/* NEXT_BLOCK() creates an implicit jump from the current block
1431 to the new block.
1432
1433 The returns inside this macro make it impossible to decref objects
1434 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (compiler_next_block((C)) == NULL) \
1438 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439}
1440
1441#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (!compiler_addop((C), (OP))) \
1443 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001446#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_addop((C), (OP))) { \
1448 compiler_exit_scope(c); \
1449 return 0; \
1450 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001451}
1452
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001453#define ADDOP_LOAD_CONST(C, O) { \
1454 if (!compiler_addop_load_const((C), (O))) \
1455 return 0; \
1456}
1457
1458/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1459#define ADDOP_LOAD_CONST_NEW(C, O) { \
1460 PyObject *__new_const = (O); \
1461 if (__new_const == NULL) { \
1462 return 0; \
1463 } \
1464 if (!compiler_addop_load_const((C), __new_const)) { \
1465 Py_DECREF(__new_const); \
1466 return 0; \
1467 } \
1468 Py_DECREF(__new_const); \
1469}
1470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001476/* Same as ADDOP_O, but steals a reference. */
1477#define ADDOP_N(C, OP, O, TYPE) { \
1478 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1479 Py_DECREF((O)); \
1480 return 0; \
1481 } \
1482 Py_DECREF((O)); \
1483}
1484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1487 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488}
1489
1490#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_i((C), (OP), (O))) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_j((C), (OP), (O), 1)) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_j((C), (OP), (O), 0)) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1506 the ASDL name to synthesize the name of the C type and the visit function.
1507*/
1508
1509#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 if (!compiler_visit_ ## TYPE((C), (V))) \
1511 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512}
1513
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001514#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!compiler_visit_ ## TYPE((C), (V))) { \
1516 compiler_exit_scope(c); \
1517 return 0; \
1518 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001519}
1520
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_visit_slice((C), (V), (CTX))) \
1523 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
1526#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 int _i; \
1528 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1529 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1530 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1531 if (!compiler_visit_ ## TYPE((C), elt)) \
1532 return 0; \
1533 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534}
1535
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001536#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 int _i; \
1538 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1539 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1540 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1541 if (!compiler_visit_ ## TYPE((C), elt)) { \
1542 compiler_exit_scope(c); \
1543 return 0; \
1544 } \
1545 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546}
1547
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001548/* These macros allows to check only for errors and not emmit bytecode
1549 * while visiting nodes.
1550*/
1551
1552#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1553 c->c_do_not_emit_bytecode++;
1554
1555#define END_DO_NOT_EMIT_BYTECODE \
1556 c->c_do_not_emit_bytecode--; \
1557}
1558
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001559/* Search if variable annotations are present statically in a block. */
1560
1561static int
1562find_ann(asdl_seq *stmts)
1563{
1564 int i, j, res = 0;
1565 stmt_ty st;
1566
1567 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1568 st = (stmt_ty)asdl_seq_GET(stmts, i);
1569 switch (st->kind) {
1570 case AnnAssign_kind:
1571 return 1;
1572 case For_kind:
1573 res = find_ann(st->v.For.body) ||
1574 find_ann(st->v.For.orelse);
1575 break;
1576 case AsyncFor_kind:
1577 res = find_ann(st->v.AsyncFor.body) ||
1578 find_ann(st->v.AsyncFor.orelse);
1579 break;
1580 case While_kind:
1581 res = find_ann(st->v.While.body) ||
1582 find_ann(st->v.While.orelse);
1583 break;
1584 case If_kind:
1585 res = find_ann(st->v.If.body) ||
1586 find_ann(st->v.If.orelse);
1587 break;
1588 case With_kind:
1589 res = find_ann(st->v.With.body);
1590 break;
1591 case AsyncWith_kind:
1592 res = find_ann(st->v.AsyncWith.body);
1593 break;
1594 case Try_kind:
1595 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1596 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1597 st->v.Try.handlers, j);
1598 if (find_ann(handler->v.ExceptHandler.body)) {
1599 return 1;
1600 }
1601 }
1602 res = find_ann(st->v.Try.body) ||
1603 find_ann(st->v.Try.finalbody) ||
1604 find_ann(st->v.Try.orelse);
1605 break;
1606 default:
1607 res = 0;
1608 }
1609 if (res) {
1610 break;
1611 }
1612 }
1613 return res;
1614}
1615
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001616/*
1617 * Frame block handling functions
1618 */
1619
1620static int
1621compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001622 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001623{
1624 struct fblockinfo *f;
1625 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1626 PyErr_SetString(PyExc_SyntaxError,
1627 "too many statically nested blocks");
1628 return 0;
1629 }
1630 f = &c->u->u_fblock[c->u->u_nfblocks++];
1631 f->fb_type = t;
1632 f->fb_block = b;
1633 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001634 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001635 return 1;
1636}
1637
1638static void
1639compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1640{
1641 struct compiler_unit *u = c->u;
1642 assert(u->u_nfblocks > 0);
1643 u->u_nfblocks--;
1644 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1645 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1646}
1647
Mark Shannonfee55262019-11-21 09:11:43 +00001648static int
1649compiler_call_exit_with_nones(struct compiler *c) {
1650 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1651 ADDOP(c, DUP_TOP);
1652 ADDOP(c, DUP_TOP);
1653 ADDOP_I(c, CALL_FUNCTION, 3);
1654 return 1;
1655}
1656
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001657/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001658 * popping the blocks will be restored afterwards, unless another
1659 * return, break or continue is found. In which case, the TOS will
1660 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001661 */
1662static int
1663compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1664 int preserve_tos)
1665{
1666 switch (info->fb_type) {
1667 case WHILE_LOOP:
1668 return 1;
1669
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001670 case FOR_LOOP:
1671 /* Pop the iterator */
1672 if (preserve_tos) {
1673 ADDOP(c, ROT_TWO);
1674 }
1675 ADDOP(c, POP_TOP);
1676 return 1;
1677
1678 case EXCEPT:
1679 ADDOP(c, POP_BLOCK);
1680 return 1;
1681
1682 case FINALLY_TRY:
1683 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001684 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001685 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1686 return 0;
1687 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001688 }
Mark Shannonfee55262019-11-21 09:11:43 +00001689 VISIT_SEQ(c, stmt, info->fb_datum);
1690 if (preserve_tos) {
1691 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001692 }
1693 return 1;
Mark Shannonfee55262019-11-21 09:11:43 +00001694
1695 case FINALLY_END:
1696 if (preserve_tos) {
1697 ADDOP(c, ROT_FOUR);
1698 }
1699 ADDOP(c, POP_TOP);
1700 ADDOP(c, POP_TOP);
1701 ADDOP(c, POP_TOP);
1702 if (preserve_tos) {
1703 ADDOP(c, ROT_FOUR);
1704 }
1705 ADDOP(c, POP_EXCEPT);
1706 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001707
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001708 case WITH:
1709 case ASYNC_WITH:
1710 ADDOP(c, POP_BLOCK);
1711 if (preserve_tos) {
1712 ADDOP(c, ROT_TWO);
1713 }
Mark Shannonfee55262019-11-21 09:11:43 +00001714 if(!compiler_call_exit_with_nones(c)) {
1715 return 0;
1716 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001717 if (info->fb_type == ASYNC_WITH) {
1718 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001719 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001720 ADDOP(c, YIELD_FROM);
1721 }
Mark Shannonfee55262019-11-21 09:11:43 +00001722 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001723 return 1;
1724
1725 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001726 if (info->fb_datum) {
1727 ADDOP(c, POP_BLOCK);
1728 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001729 if (preserve_tos) {
1730 ADDOP(c, ROT_FOUR);
1731 }
Mark Shannonfee55262019-11-21 09:11:43 +00001732 ADDOP(c, POP_EXCEPT);
1733 if (info->fb_datum) {
1734 ADDOP_LOAD_CONST(c, Py_None);
1735 compiler_nameop(c, info->fb_datum, Store);
1736 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 }
Mark Shannonfee55262019-11-21 09:11:43 +00001738 return 1;
1739
1740 case POP_VALUE:
1741 if (preserve_tos) {
1742 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001743 }
Mark Shannonfee55262019-11-21 09:11:43 +00001744 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001745 return 1;
1746 }
1747 Py_UNREACHABLE();
1748}
1749
Mark Shannonfee55262019-11-21 09:11:43 +00001750/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1751static int
1752compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1753 if (c->u->u_nfblocks == 0) {
1754 return 1;
1755 }
1756 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1757 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1758 *loop = top;
1759 return 1;
1760 }
1761 struct fblockinfo copy = *top;
1762 c->u->u_nfblocks--;
1763 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1764 return 0;
1765 }
1766 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1767 return 0;
1768 }
1769 c->u->u_fblock[c->u->u_nfblocks] = copy;
1770 c->u->u_nfblocks++;
1771 return 1;
1772}
1773
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001774/* Compile a sequence of statements, checking for a docstring
1775 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776
1777static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001778compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001780 int i = 0;
1781 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001782 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001783
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001784 /* Set current line number to the line number of first statement.
1785 This way line number for SETUP_ANNOTATIONS will always
1786 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301787 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001788 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1789 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001790 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001791 c->u->u_lineno = st->lineno;
1792 }
1793 /* Every annotated class and module should have __annotations__. */
1794 if (find_ann(stmts)) {
1795 ADDOP(c, SETUP_ANNOTATIONS);
1796 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001797 if (!asdl_seq_LEN(stmts))
1798 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001799 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001800 if (c->c_optimize < 2) {
1801 docstring = _PyAST_GetDocString(stmts);
1802 if (docstring) {
1803 i = 1;
1804 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1805 assert(st->kind == Expr_kind);
1806 VISIT(c, expr, st->v.Expr.value);
1807 if (!compiler_nameop(c, __doc__, Store))
1808 return 0;
1809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001811 for (; i < asdl_seq_LEN(stmts); i++)
1812 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814}
1815
1816static PyCodeObject *
1817compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyCodeObject *co;
1820 int addNone = 1;
1821 static PyObject *module;
1822 if (!module) {
1823 module = PyUnicode_InternFromString("<module>");
1824 if (!module)
1825 return NULL;
1826 }
1827 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001828 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return NULL;
1830 switch (mod->kind) {
1831 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001832 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 compiler_exit_scope(c);
1834 return 0;
1835 }
1836 break;
1837 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001838 if (find_ann(mod->v.Interactive.body)) {
1839 ADDOP(c, SETUP_ANNOTATIONS);
1840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 c->c_interactive = 1;
1842 VISIT_SEQ_IN_SCOPE(c, stmt,
1843 mod->v.Interactive.body);
1844 break;
1845 case Expression_kind:
1846 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1847 addNone = 0;
1848 break;
1849 case Suite_kind:
1850 PyErr_SetString(PyExc_SystemError,
1851 "suite should not be possible");
1852 return 0;
1853 default:
1854 PyErr_Format(PyExc_SystemError,
1855 "module kind %d should not be possible",
1856 mod->kind);
1857 return 0;
1858 }
1859 co = assemble(c, addNone);
1860 compiler_exit_scope(c);
1861 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001862}
1863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864/* The test for LOCAL must come before the test for FREE in order to
1865 handle classes where name is both local and free. The local var is
1866 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001867*/
1868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869static int
1870get_ref_type(struct compiler *c, PyObject *name)
1871{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001872 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001873 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001874 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001875 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001876 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (scope == 0) {
1878 char buf[350];
1879 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001880 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001882 PyUnicode_AsUTF8(name),
1883 PyUnicode_AsUTF8(c->u->u_name),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1887 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 );
1889 Py_FatalError(buf);
1890 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893}
1894
1895static int
1896compiler_lookup_arg(PyObject *dict, PyObject *name)
1897{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001898 PyObject *v;
1899 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001900 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001901 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001902 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903}
1904
1905static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001908 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001909 if (qualname == NULL)
1910 qualname = co->co_name;
1911
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001912 if (free) {
1913 for (i = 0; i < free; ++i) {
1914 /* Bypass com_addop_varname because it will generate
1915 LOAD_DEREF but LOAD_CLOSURE is needed.
1916 */
1917 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1918 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001920 /* Special case: If a class contains a method with a
1921 free variable that has the same name as a method,
1922 the name will be considered free *and* local in the
1923 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001924 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001925 */
1926 reftype = get_ref_type(c, name);
1927 if (reftype == CELL)
1928 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1929 else /* (reftype == FREE) */
1930 arg = compiler_lookup_arg(c->u->u_freevars, name);
1931 if (arg == -1) {
1932 fprintf(stderr,
1933 "lookup %s in %s %d %d\n"
1934 "freevars of %s: %s\n",
1935 PyUnicode_AsUTF8(PyObject_Repr(name)),
1936 PyUnicode_AsUTF8(c->u->u_name),
1937 reftype, arg,
1938 PyUnicode_AsUTF8(co->co_name),
1939 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1940 Py_FatalError("compiler_make_closure()");
1941 }
1942 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001944 flags |= 0x08;
1945 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001947 ADDOP_LOAD_CONST(c, (PyObject*)co);
1948 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001949 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951}
1952
1953static int
1954compiler_decorators(struct compiler *c, asdl_seq* decos)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (!decos)
1959 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1962 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1963 }
1964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965}
1966
1967static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001968compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001970{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001971 /* Push a dict of keyword-only default values.
1972
1973 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1974 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001975 int i;
1976 PyObject *keys = NULL;
1977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1979 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1980 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1981 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001982 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 if (!mangled) {
1984 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 if (keys == NULL) {
1987 keys = PyList_New(1);
1988 if (keys == NULL) {
1989 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 }
1992 PyList_SET_ITEM(keys, 0, mangled);
1993 }
1994 else {
1995 int res = PyList_Append(keys, mangled);
1996 Py_DECREF(mangled);
1997 if (res == -1) {
1998 goto error;
1999 }
2000 }
2001 if (!compiler_visit_expr(c, default_)) {
2002 goto error;
2003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
2005 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 if (keys != NULL) {
2007 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2008 PyObject *keys_tuple = PyList_AsTuple(keys);
2009 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002010 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002012 assert(default_count > 0);
2013 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 }
2015 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002016 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 }
2018
2019error:
2020 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002021 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002022}
2023
2024static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002025compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2026{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002027 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002028 return 1;
2029}
2030
2031static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002032compiler_visit_argannotation(struct compiler *c, identifier id,
2033 expr_ty annotation, PyObject *names)
2034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002036 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002037 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2038 VISIT(c, annexpr, annotation)
2039 }
2040 else {
2041 VISIT(c, expr, annotation);
2042 }
Victor Stinner065efc32014-02-18 22:07:56 +01002043 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002044 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002045 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002046 if (PyList_Append(names, mangled) < 0) {
2047 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002048 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002049 }
2050 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002052 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002053}
2054
2055static int
2056compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2057 PyObject *names)
2058{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002059 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 for (i = 0; i < asdl_seq_LEN(args); i++) {
2061 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002062 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 c,
2064 arg->arg,
2065 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 names))
2067 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002069 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002070}
2071
2072static int
2073compiler_visit_annotations(struct compiler *c, arguments_ty args,
2074 expr_ty returns)
2075{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002076 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002077 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002078
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002079 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 */
2081 static identifier return_str;
2082 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002083 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 names = PyList_New(0);
2085 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002086 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002087
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002090 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2091 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002092 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002093 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002094 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002096 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002098 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002099 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002100 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (!return_str) {
2104 return_str = PyUnicode_InternFromString("return");
2105 if (!return_str)
2106 goto error;
2107 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002108 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 goto error;
2110 }
2111
2112 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002114 PyObject *keytuple = PyList_AsTuple(names);
2115 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002116 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002117 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002118 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002120 else {
2121 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002122 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002123 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002124
2125error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002127 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002128}
2129
2130static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002131compiler_visit_defaults(struct compiler *c, arguments_ty args)
2132{
2133 VISIT_SEQ(c, expr, args->defaults);
2134 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2135 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136}
2137
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002138static Py_ssize_t
2139compiler_default_arguments(struct compiler *c, arguments_ty args)
2140{
2141 Py_ssize_t funcflags = 0;
2142 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002143 if (!compiler_visit_defaults(c, args))
2144 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002145 funcflags |= 0x01;
2146 }
2147 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002148 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002149 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002150 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002151 return -1;
2152 }
2153 else if (res > 0) {
2154 funcflags |= 0x02;
2155 }
2156 }
2157 return funcflags;
2158}
2159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160static int
Yury Selivanov75445082015-05-11 22:57:16 -04002161compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002164 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002165 arguments_ty args;
2166 expr_ty returns;
2167 identifier name;
2168 asdl_seq* decos;
2169 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002170 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002171 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002172 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002173 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174
Yury Selivanov75445082015-05-11 22:57:16 -04002175 if (is_async) {
2176 assert(s->kind == AsyncFunctionDef_kind);
2177
2178 args = s->v.AsyncFunctionDef.args;
2179 returns = s->v.AsyncFunctionDef.returns;
2180 decos = s->v.AsyncFunctionDef.decorator_list;
2181 name = s->v.AsyncFunctionDef.name;
2182 body = s->v.AsyncFunctionDef.body;
2183
2184 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2185 } else {
2186 assert(s->kind == FunctionDef_kind);
2187
2188 args = s->v.FunctionDef.args;
2189 returns = s->v.FunctionDef.returns;
2190 decos = s->v.FunctionDef.decorator_list;
2191 name = s->v.FunctionDef.name;
2192 body = s->v.FunctionDef.body;
2193
2194 scope_type = COMPILER_SCOPE_FUNCTION;
2195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (!compiler_decorators(c, decos))
2198 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002199
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002200 firstlineno = s->lineno;
2201 if (asdl_seq_LEN(decos)) {
2202 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2203 }
2204
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002205 funcflags = compiler_default_arguments(c, args);
2206 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002208 }
2209
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002210 annotations = compiler_visit_annotations(c, args, returns);
2211 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002212 return 0;
2213 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002214 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002215 funcflags |= 0x04;
2216 }
2217
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002218 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002219 return 0;
2220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
INADA Naokicb41b272017-02-23 00:31:59 +09002222 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002223 if (c->c_optimize < 2) {
2224 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002225 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002226 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 compiler_exit_scope(c);
2228 return 0;
2229 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002232 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002234 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002236 qualname = c->u->u_qualname;
2237 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002239 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002240 Py_XDECREF(qualname);
2241 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002243 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002245 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002246 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* decorators */
2250 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2251 ADDOP_I(c, CALL_FUNCTION, 1);
2252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
Yury Selivanov75445082015-05-11 22:57:16 -04002254 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255}
2256
2257static int
2258compiler_class(struct compiler *c, stmt_ty s)
2259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyCodeObject *co;
2261 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002262 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (!compiler_decorators(c, decos))
2266 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002267
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002268 firstlineno = s->lineno;
2269 if (asdl_seq_LEN(decos)) {
2270 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2271 }
2272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 /* ultimately generate code for:
2274 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2275 where:
2276 <func> is a function/closure created from the class body;
2277 it has a single argument (__locals__) where the dict
2278 (or MutableSequence) representing the locals is passed
2279 <name> is the class name
2280 <bases> is the positional arguments and *varargs argument
2281 <keywords> is the keyword arguments and **kwds argument
2282 This borrows from compiler_call.
2283 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002286 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002287 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return 0;
2289 /* this block represents what we do in the new scope */
2290 {
2291 /* use the class name for name mangling */
2292 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002293 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* load (global) __name__ ... */
2295 str = PyUnicode_InternFromString("__name__");
2296 if (!str || !compiler_nameop(c, str, Load)) {
2297 Py_XDECREF(str);
2298 compiler_exit_scope(c);
2299 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002300 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 Py_DECREF(str);
2302 /* ... and store it as __module__ */
2303 str = PyUnicode_InternFromString("__module__");
2304 if (!str || !compiler_nameop(c, str, Store)) {
2305 Py_XDECREF(str);
2306 compiler_exit_scope(c);
2307 return 0;
2308 }
2309 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002310 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002311 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002312 str = PyUnicode_InternFromString("__qualname__");
2313 if (!str || !compiler_nameop(c, str, Store)) {
2314 Py_XDECREF(str);
2315 compiler_exit_scope(c);
2316 return 0;
2317 }
2318 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002320 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 compiler_exit_scope(c);
2322 return 0;
2323 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002324 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002325 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002326 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002327 str = PyUnicode_InternFromString("__class__");
2328 if (str == NULL) {
2329 compiler_exit_scope(c);
2330 return 0;
2331 }
2332 i = compiler_lookup_arg(c->u->u_cellvars, str);
2333 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002334 if (i < 0) {
2335 compiler_exit_scope(c);
2336 return 0;
2337 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002338 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002341 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002342 str = PyUnicode_InternFromString("__classcell__");
2343 if (!str || !compiler_nameop(c, str, Store)) {
2344 Py_XDECREF(str);
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002350 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002351 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002352 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002353 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002354 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002355 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 /* create the code object */
2357 co = assemble(c, 1);
2358 }
2359 /* leave the new scope */
2360 compiler_exit_scope(c);
2361 if (co == NULL)
2362 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* 2. load the 'build_class' function */
2365 ADDOP(c, LOAD_BUILD_CLASS);
2366
2367 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002368 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 Py_DECREF(co);
2370
2371 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002372 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373
2374 /* 5. generate the rest of the code for the call */
2375 if (!compiler_call_helper(c, 2,
2376 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002377 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return 0;
2379
2380 /* 6. apply decorators */
2381 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2382 ADDOP_I(c, CALL_FUNCTION, 1);
2383 }
2384
2385 /* 7. store into <name> */
2386 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2387 return 0;
2388 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389}
2390
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002391/* Return 0 if the expression is a constant value except named singletons.
2392 Return 1 otherwise. */
2393static int
2394check_is_arg(expr_ty e)
2395{
2396 if (e->kind != Constant_kind) {
2397 return 1;
2398 }
2399 PyObject *value = e->v.Constant.value;
2400 return (value == Py_None
2401 || value == Py_False
2402 || value == Py_True
2403 || value == Py_Ellipsis);
2404}
2405
2406/* Check operands of identity chacks ("is" and "is not").
2407 Emit a warning if any operand is a constant except named singletons.
2408 Return 0 on error.
2409 */
2410static int
2411check_compare(struct compiler *c, expr_ty e)
2412{
2413 Py_ssize_t i, n;
2414 int left = check_is_arg(e->v.Compare.left);
2415 n = asdl_seq_LEN(e->v.Compare.ops);
2416 for (i = 0; i < n; i++) {
2417 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2418 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2419 if (op == Is || op == IsNot) {
2420 if (!right || !left) {
2421 const char *msg = (op == Is)
2422 ? "\"is\" with a literal. Did you mean \"==\"?"
2423 : "\"is not\" with a literal. Did you mean \"!=\"?";
2424 return compiler_warn(c, msg);
2425 }
2426 }
2427 left = right;
2428 }
2429 return 1;
2430}
2431
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002433cmpop(cmpop_ty op)
2434{
2435 switch (op) {
2436 case Eq:
2437 return PyCmp_EQ;
2438 case NotEq:
2439 return PyCmp_NE;
2440 case Lt:
2441 return PyCmp_LT;
2442 case LtE:
2443 return PyCmp_LE;
2444 case Gt:
2445 return PyCmp_GT;
2446 case GtE:
2447 return PyCmp_GE;
2448 case Is:
2449 return PyCmp_IS;
2450 case IsNot:
2451 return PyCmp_IS_NOT;
2452 case In:
2453 return PyCmp_IN;
2454 case NotIn:
2455 return PyCmp_NOT_IN;
2456 default:
2457 return PyCmp_BAD;
2458 }
2459}
2460
2461static int
2462compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2463{
2464 switch (e->kind) {
2465 case UnaryOp_kind:
2466 if (e->v.UnaryOp.op == Not)
2467 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2468 /* fallback to general implementation */
2469 break;
2470 case BoolOp_kind: {
2471 asdl_seq *s = e->v.BoolOp.values;
2472 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2473 assert(n >= 0);
2474 int cond2 = e->v.BoolOp.op == Or;
2475 basicblock *next2 = next;
2476 if (!cond2 != !cond) {
2477 next2 = compiler_new_block(c);
2478 if (next2 == NULL)
2479 return 0;
2480 }
2481 for (i = 0; i < n; ++i) {
2482 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2483 return 0;
2484 }
2485 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2486 return 0;
2487 if (next2 != next)
2488 compiler_use_next_block(c, next2);
2489 return 1;
2490 }
2491 case IfExp_kind: {
2492 basicblock *end, *next2;
2493 end = compiler_new_block(c);
2494 if (end == NULL)
2495 return 0;
2496 next2 = compiler_new_block(c);
2497 if (next2 == NULL)
2498 return 0;
2499 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2500 return 0;
2501 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2502 return 0;
2503 ADDOP_JREL(c, JUMP_FORWARD, end);
2504 compiler_use_next_block(c, next2);
2505 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2506 return 0;
2507 compiler_use_next_block(c, end);
2508 return 1;
2509 }
2510 case Compare_kind: {
2511 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2512 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002513 if (!check_compare(c, e)) {
2514 return 0;
2515 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002516 basicblock *cleanup = compiler_new_block(c);
2517 if (cleanup == NULL)
2518 return 0;
2519 VISIT(c, expr, e->v.Compare.left);
2520 for (i = 0; i < n; i++) {
2521 VISIT(c, expr,
2522 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2523 ADDOP(c, DUP_TOP);
2524 ADDOP(c, ROT_THREE);
2525 ADDOP_I(c, COMPARE_OP,
2526 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2527 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2528 NEXT_BLOCK(c);
2529 }
2530 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2531 ADDOP_I(c, COMPARE_OP,
2532 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2533 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2534 basicblock *end = compiler_new_block(c);
2535 if (end == NULL)
2536 return 0;
2537 ADDOP_JREL(c, JUMP_FORWARD, end);
2538 compiler_use_next_block(c, cleanup);
2539 ADDOP(c, POP_TOP);
2540 if (!cond) {
2541 ADDOP_JREL(c, JUMP_FORWARD, next);
2542 }
2543 compiler_use_next_block(c, end);
2544 return 1;
2545 }
2546 /* fallback to general implementation */
2547 break;
2548 }
2549 default:
2550 /* fallback to general implementation */
2551 break;
2552 }
2553
2554 /* general implementation */
2555 VISIT(c, expr, e);
2556 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2557 return 1;
2558}
2559
2560static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002561compiler_ifexp(struct compiler *c, expr_ty e)
2562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 basicblock *end, *next;
2564
2565 assert(e->kind == IfExp_kind);
2566 end = compiler_new_block(c);
2567 if (end == NULL)
2568 return 0;
2569 next = compiler_new_block(c);
2570 if (next == NULL)
2571 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002572 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2573 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 VISIT(c, expr, e->v.IfExp.body);
2575 ADDOP_JREL(c, JUMP_FORWARD, end);
2576 compiler_use_next_block(c, next);
2577 VISIT(c, expr, e->v.IfExp.orelse);
2578 compiler_use_next_block(c, end);
2579 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002580}
2581
2582static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583compiler_lambda(struct compiler *c, expr_ty e)
2584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002586 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002588 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 arguments_ty args = e->v.Lambda.args;
2590 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 if (!name) {
2593 name = PyUnicode_InternFromString("<lambda>");
2594 if (!name)
2595 return 0;
2596 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002598 funcflags = compiler_default_arguments(c, args);
2599 if (funcflags == -1) {
2600 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002602
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002603 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002604 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Make None the first constant, so the lambda can't have a
2608 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002609 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002613 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2615 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2616 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002617 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 }
2619 else {
2620 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002621 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002623 qualname = c->u->u_qualname;
2624 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002626 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002629 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002630 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 Py_DECREF(co);
2632
2633 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634}
2635
2636static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637compiler_if(struct compiler *c, stmt_ty s)
2638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 basicblock *end, *next;
2640 int constant;
2641 assert(s->kind == If_kind);
2642 end = compiler_new_block(c);
2643 if (end == NULL)
2644 return 0;
2645
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002646 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002647 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 * constant = 1: "if 1", "if 2", ...
2649 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002650 if (constant == 0) {
2651 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002653 END_DO_NOT_EMIT_BYTECODE
2654 if (s->v.If.orelse) {
2655 VISIT_SEQ(c, stmt, s->v.If.orelse);
2656 }
2657 } else if (constant == 1) {
2658 VISIT_SEQ(c, stmt, s->v.If.body);
2659 if (s->v.If.orelse) {
2660 BEGIN_DO_NOT_EMIT_BYTECODE
2661 VISIT_SEQ(c, stmt, s->v.If.orelse);
2662 END_DO_NOT_EMIT_BYTECODE
2663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002665 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 next = compiler_new_block(c);
2667 if (next == NULL)
2668 return 0;
2669 }
Mark Shannonfee55262019-11-21 09:11:43 +00002670 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002672 }
2673 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002674 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002677 if (asdl_seq_LEN(s->v.If.orelse)) {
2678 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 compiler_use_next_block(c, next);
2680 VISIT_SEQ(c, stmt, s->v.If.orelse);
2681 }
2682 }
2683 compiler_use_next_block(c, end);
2684 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685}
2686
2687static int
2688compiler_for(struct compiler *c, stmt_ty s)
2689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 start = compiler_new_block(c);
2693 cleanup = compiler_new_block(c);
2694 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002695 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002697 }
2698 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002700 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 VISIT(c, expr, s->v.For.iter);
2702 ADDOP(c, GET_ITER);
2703 compiler_use_next_block(c, start);
2704 ADDOP_JREL(c, FOR_ITER, cleanup);
2705 VISIT(c, expr, s->v.For.target);
2706 VISIT_SEQ(c, stmt, s->v.For.body);
2707 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2708 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709
2710 compiler_pop_fblock(c, FOR_LOOP, start);
2711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 VISIT_SEQ(c, stmt, s->v.For.orelse);
2713 compiler_use_next_block(c, end);
2714 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715}
2716
Yury Selivanov75445082015-05-11 22:57:16 -04002717
2718static int
2719compiler_async_for(struct compiler *c, stmt_ty s)
2720{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002721 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002722 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2723 c->u->u_ste->ste_coroutine = 1;
2724 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002725 return compiler_error(c, "'async for' outside async function");
2726 }
2727
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002728 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002729 except = compiler_new_block(c);
2730 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002731
Mark Shannonfee55262019-11-21 09:11:43 +00002732 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002733 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002734 }
Yury Selivanov75445082015-05-11 22:57:16 -04002735 VISIT(c, expr, s->v.AsyncFor.iter);
2736 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002737
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002738 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002739 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002740 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002741 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002742 /* SETUP_FINALLY to guard the __anext__ call */
2743 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002744 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002745 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002746 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002747 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002748
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002749 /* Success block for __anext__ */
2750 VISIT(c, expr, s->v.AsyncFor.target);
2751 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2752 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2753
2754 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002755
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002756 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002757 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002758 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002759
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002760 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002761 VISIT_SEQ(c, stmt, s->v.For.orelse);
2762
2763 compiler_use_next_block(c, end);
2764
2765 return 1;
2766}
2767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768static int
2769compiler_while(struct compiler *c, stmt_ty s)
2770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002772 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002775 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002776 // Push a dummy block so the VISIT_SEQ knows that we are
2777 // inside a while loop so it can correctly evaluate syntax
2778 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002779 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002780 return 0;
2781 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002782 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002783 // Remove the dummy block now that is not needed.
2784 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002785 END_DO_NOT_EMIT_BYTECODE
2786 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 return 1;
2790 }
2791 loop = compiler_new_block(c);
2792 end = compiler_new_block(c);
2793 if (constant == -1) {
2794 anchor = compiler_new_block(c);
2795 if (anchor == NULL)
2796 return 0;
2797 }
2798 if (loop == NULL || end == NULL)
2799 return 0;
2800 if (s->v.While.orelse) {
2801 orelse = compiler_new_block(c);
2802 if (orelse == NULL)
2803 return 0;
2804 }
2805 else
2806 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002809 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 return 0;
2811 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002812 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2813 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 }
2815 VISIT_SEQ(c, stmt, s->v.While.body);
2816 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 /* XXX should the two POP instructions be in a separate block
2819 if there is no else clause ?
2820 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002822 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002824 compiler_pop_fblock(c, WHILE_LOOP, loop);
2825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 if (orelse != NULL) /* what if orelse is just pass? */
2827 VISIT_SEQ(c, stmt, s->v.While.orelse);
2828 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831}
2832
2833static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002834compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002836 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002837 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002838 if (c->u->u_ste->ste_type != FunctionBlock)
2839 return compiler_error(c, "'return' outside function");
2840 if (s->v.Return.value != NULL &&
2841 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2842 {
2843 return compiler_error(
2844 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002846 if (preserve_tos) {
2847 VISIT(c, expr, s->v.Return.value);
2848 }
Mark Shannonfee55262019-11-21 09:11:43 +00002849 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2850 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002851 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002852 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002853 }
2854 else if (!preserve_tos) {
2855 VISIT(c, expr, s->v.Return.value);
2856 }
2857 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860}
2861
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862static int
2863compiler_break(struct compiler *c)
2864{
Mark Shannonfee55262019-11-21 09:11:43 +00002865 struct fblockinfo *loop = NULL;
2866 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2867 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002868 }
Mark Shannonfee55262019-11-21 09:11:43 +00002869 if (loop == NULL) {
2870 return compiler_error(c, "'break' outside loop");
2871 }
2872 if (!compiler_unwind_fblock(c, loop, 0)) {
2873 return 0;
2874 }
2875 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2876 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877}
2878
2879static int
2880compiler_continue(struct compiler *c)
2881{
Mark Shannonfee55262019-11-21 09:11:43 +00002882 struct fblockinfo *loop = NULL;
2883 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2884 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 }
Mark Shannonfee55262019-11-21 09:11:43 +00002886 if (loop == NULL) {
2887 return compiler_error(c, "'continue' not properly in loop");
2888 }
2889 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2890 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891}
2892
2893
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895
2896 SETUP_FINALLY L
2897 <code for body>
2898 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002899 <code for finalbody>
2900 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002901 L:
2902 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002903 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905 The special instructions use the block stack. Each block
2906 stack entry contains the instruction that created it (here
2907 SETUP_FINALLY), the level of the value stack at the time the
2908 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 Pushes the current value stack level and the label
2912 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002913 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002917 when a SETUP_FINALLY entry is found, the raised and the caught
2918 exceptions are pushed onto the value stack (and the exception
2919 condition is cleared), and the interpreter jumps to the label
2920 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921*/
2922
2923static int
2924compiler_try_finally(struct compiler *c, stmt_ty s)
2925{
Mark Shannonfee55262019-11-21 09:11:43 +00002926 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 body = compiler_new_block(c);
2929 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002930 exit = compiler_new_block(c);
2931 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002934 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 ADDOP_JREL(c, SETUP_FINALLY, end);
2936 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002937 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002939 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2940 if (!compiler_try_except(c, s))
2941 return 0;
2942 }
2943 else {
2944 VISIT_SEQ(c, stmt, s->v.Try.body);
2945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002947 compiler_pop_fblock(c, FINALLY_TRY, body);
2948 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2949 ADDOP_JREL(c, JUMP_FORWARD, exit);
2950 /* `finally` block */
2951 compiler_use_next_block(c, end);
2952 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2953 return 0;
2954 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2955 compiler_pop_fblock(c, FINALLY_END, end);
2956 ADDOP(c, RERAISE);
2957 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959}
2960
2961/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002962 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 (The contents of the value stack is shown in [], with the top
2964 at the right; 'tb' is trace-back info, 'val' the exception's
2965 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966
2967 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002968 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 [] <code for S>
2970 [] POP_BLOCK
2971 [] JUMP_FORWARD L0
2972
2973 [tb, val, exc] L1: DUP )
2974 [tb, val, exc, exc] <evaluate E1> )
2975 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2976 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2977 [tb, val, exc] POP
2978 [tb, val] <assign to V1> (or POP if no V1)
2979 [tb] POP
2980 [] <code for S1>
2981 JUMP_FORWARD L0
2982
2983 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 .............................etc.......................
2985
Mark Shannonfee55262019-11-21 09:11:43 +00002986 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987
2988 [] L0: <next statement>
2989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 Of course, parts are not generated if Vi or Ei is not present.
2991*/
2992static int
2993compiler_try_except(struct compiler *c, stmt_ty s)
2994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002996 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 body = compiler_new_block(c);
2999 except = compiler_new_block(c);
3000 orelse = compiler_new_block(c);
3001 end = compiler_new_block(c);
3002 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3003 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003004 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003006 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003008 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 ADDOP(c, POP_BLOCK);
3010 compiler_pop_fblock(c, EXCEPT, body);
3011 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003012 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 compiler_use_next_block(c, except);
3014 for (i = 0; i < n; i++) {
3015 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003016 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 if (!handler->v.ExceptHandler.type && i < n-1)
3018 return compiler_error(c, "default 'except:' must be last");
3019 c->u->u_lineno_set = 0;
3020 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003021 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 except = compiler_new_block(c);
3023 if (except == NULL)
3024 return 0;
3025 if (handler->v.ExceptHandler.type) {
3026 ADDOP(c, DUP_TOP);
3027 VISIT(c, expr, handler->v.ExceptHandler.type);
3028 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3029 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
3030 }
3031 ADDOP(c, POP_TOP);
3032 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003033 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003034
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003035 cleanup_end = compiler_new_block(c);
3036 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003037 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003038 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003039 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003040
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003041 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3042 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003044 /*
3045 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003046 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003048 try:
3049 # body
3050 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003051 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003052 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003053 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003055 /* second try: */
3056 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3057 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003058 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 /* second # body */
3062 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003063 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003064 ADDOP(c, POP_BLOCK);
3065 ADDOP(c, POP_EXCEPT);
3066 /* name = None; del name */
3067 ADDOP_LOAD_CONST(c, Py_None);
3068 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3069 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3070 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071
Mark Shannonfee55262019-11-21 09:11:43 +00003072 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003075 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003076 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003078 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079
Mark Shannonfee55262019-11-21 09:11:43 +00003080 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 }
3082 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003086 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088
Guido van Rossumb940e112007-01-10 16:19:56 +00003089 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003090 ADDOP(c, POP_TOP);
3091 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003092 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003095 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003096 ADDOP(c, POP_EXCEPT);
3097 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 compiler_use_next_block(c, except);
3100 }
Mark Shannonfee55262019-11-21 09:11:43 +00003101 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003103 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 compiler_use_next_block(c, end);
3105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106}
3107
3108static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003109compiler_try(struct compiler *c, stmt_ty s) {
3110 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3111 return compiler_try_finally(c, s);
3112 else
3113 return compiler_try_except(c, s);
3114}
3115
3116
3117static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118compiler_import_as(struct compiler *c, identifier name, identifier asname)
3119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* The IMPORT_NAME opcode was already generated. This function
3121 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003124 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003126 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3127 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003128 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003129 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003130 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003132 while (1) {
3133 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003135 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003136 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003137 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003138 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003140 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003141 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003142 if (dot == -1) {
3143 break;
3144 }
3145 ADDOP(c, ROT_TWO);
3146 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003148 if (!compiler_nameop(c, asname, Store)) {
3149 return 0;
3150 }
3151 ADDOP(c, POP_TOP);
3152 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 }
3154 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155}
3156
3157static int
3158compiler_import(struct compiler *c, stmt_ty s)
3159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 /* The Import node stores a module name like a.b.c as a single
3161 string. This is convenient for all cases except
3162 import a.b.c as d
3163 where we need to parse that string to extract the individual
3164 module names.
3165 XXX Perhaps change the representation to make this case simpler?
3166 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003167 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 for (i = 0; i < n; i++) {
3170 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3171 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003173 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3174 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 if (alias->asname) {
3178 r = compiler_import_as(c, alias->name, alias->asname);
3179 if (!r)
3180 return r;
3181 }
3182 else {
3183 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003184 Py_ssize_t dot = PyUnicode_FindChar(
3185 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003186 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003187 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003188 if (tmp == NULL)
3189 return 0;
3190 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003192 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 Py_DECREF(tmp);
3194 }
3195 if (!r)
3196 return r;
3197 }
3198 }
3199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200}
3201
3202static int
3203compiler_from_import(struct compiler *c, stmt_ty s)
3204{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003205 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003206 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 if (!empty_string) {
3210 empty_string = PyUnicode_FromString("");
3211 if (!empty_string)
3212 return 0;
3213 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003215 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003216
3217 names = PyTuple_New(n);
3218 if (!names)
3219 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 /* build up the names */
3222 for (i = 0; i < n; i++) {
3223 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3224 Py_INCREF(alias->name);
3225 PyTuple_SET_ITEM(names, i, alias->name);
3226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003229 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 Py_DECREF(names);
3231 return compiler_error(c, "from __future__ imports must occur "
3232 "at the beginning of the file");
3233 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003234 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 if (s->v.ImportFrom.module) {
3237 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3238 }
3239 else {
3240 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3241 }
3242 for (i = 0; i < n; i++) {
3243 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3244 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003246 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 assert(n == 1);
3248 ADDOP(c, IMPORT_STAR);
3249 return 1;
3250 }
3251
3252 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3253 store_name = alias->name;
3254 if (alias->asname)
3255 store_name = alias->asname;
3256
3257 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 return 0;
3259 }
3260 }
3261 /* remove imported module */
3262 ADDOP(c, POP_TOP);
3263 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264}
3265
3266static int
3267compiler_assert(struct compiler *c, stmt_ty s)
3268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Georg Brandl8334fd92010-12-04 10:26:46 +00003271 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003274 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3275 {
3276 if (!compiler_warn(c, "assertion is always true, "
3277 "perhaps remove parentheses?"))
3278 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003279 return 0;
3280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 end = compiler_new_block(c);
3283 if (end == NULL)
3284 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003285 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3286 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003287 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 if (s->v.Assert.msg) {
3289 VISIT(c, expr, s->v.Assert.msg);
3290 ADDOP_I(c, CALL_FUNCTION, 1);
3291 }
3292 ADDOP_I(c, RAISE_VARARGS, 1);
3293 compiler_use_next_block(c, end);
3294 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295}
3296
3297static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003298compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3299{
3300 if (c->c_interactive && c->c_nestlevel <= 1) {
3301 VISIT(c, expr, value);
3302 ADDOP(c, PRINT_EXPR);
3303 return 1;
3304 }
3305
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003306 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003307 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003308 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003309 }
3310
3311 VISIT(c, expr, value);
3312 ADDOP(c, POP_TOP);
3313 return 1;
3314}
3315
3316static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317compiler_visit_stmt(struct compiler *c, stmt_ty s)
3318{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003319 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 /* Always assign a lineno to the next instruction for a stmt. */
3322 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003323 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 switch (s->kind) {
3327 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003328 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 case ClassDef_kind:
3330 return compiler_class(c, s);
3331 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003332 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 case Delete_kind:
3334 VISIT_SEQ(c, expr, s->v.Delete.targets)
3335 break;
3336 case Assign_kind:
3337 n = asdl_seq_LEN(s->v.Assign.targets);
3338 VISIT(c, expr, s->v.Assign.value);
3339 for (i = 0; i < n; i++) {
3340 if (i < n - 1)
3341 ADDOP(c, DUP_TOP);
3342 VISIT(c, expr,
3343 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3344 }
3345 break;
3346 case AugAssign_kind:
3347 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003348 case AnnAssign_kind:
3349 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 case For_kind:
3351 return compiler_for(c, s);
3352 case While_kind:
3353 return compiler_while(c, s);
3354 case If_kind:
3355 return compiler_if(c, s);
3356 case Raise_kind:
3357 n = 0;
3358 if (s->v.Raise.exc) {
3359 VISIT(c, expr, s->v.Raise.exc);
3360 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003361 if (s->v.Raise.cause) {
3362 VISIT(c, expr, s->v.Raise.cause);
3363 n++;
3364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003366 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003368 case Try_kind:
3369 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 case Assert_kind:
3371 return compiler_assert(c, s);
3372 case Import_kind:
3373 return compiler_import(c, s);
3374 case ImportFrom_kind:
3375 return compiler_from_import(c, s);
3376 case Global_kind:
3377 case Nonlocal_kind:
3378 break;
3379 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003380 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 case Pass_kind:
3382 break;
3383 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003384 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 case Continue_kind:
3386 return compiler_continue(c);
3387 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003388 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003389 case AsyncFunctionDef_kind:
3390 return compiler_function(c, s, 1);
3391 case AsyncWith_kind:
3392 return compiler_async_with(c, s, 0);
3393 case AsyncFor_kind:
3394 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 }
Yury Selivanov75445082015-05-11 22:57:16 -04003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398}
3399
3400static int
3401unaryop(unaryop_ty op)
3402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 switch (op) {
3404 case Invert:
3405 return UNARY_INVERT;
3406 case Not:
3407 return UNARY_NOT;
3408 case UAdd:
3409 return UNARY_POSITIVE;
3410 case USub:
3411 return UNARY_NEGATIVE;
3412 default:
3413 PyErr_Format(PyExc_SystemError,
3414 "unary op %d should not be possible", op);
3415 return 0;
3416 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003417}
3418
3419static int
3420binop(struct compiler *c, operator_ty op)
3421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 switch (op) {
3423 case Add:
3424 return BINARY_ADD;
3425 case Sub:
3426 return BINARY_SUBTRACT;
3427 case Mult:
3428 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003429 case MatMult:
3430 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 case Div:
3432 return BINARY_TRUE_DIVIDE;
3433 case Mod:
3434 return BINARY_MODULO;
3435 case Pow:
3436 return BINARY_POWER;
3437 case LShift:
3438 return BINARY_LSHIFT;
3439 case RShift:
3440 return BINARY_RSHIFT;
3441 case BitOr:
3442 return BINARY_OR;
3443 case BitXor:
3444 return BINARY_XOR;
3445 case BitAnd:
3446 return BINARY_AND;
3447 case FloorDiv:
3448 return BINARY_FLOOR_DIVIDE;
3449 default:
3450 PyErr_Format(PyExc_SystemError,
3451 "binary op %d should not be possible", op);
3452 return 0;
3453 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454}
3455
3456static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003457inplace_binop(struct compiler *c, operator_ty op)
3458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 switch (op) {
3460 case Add:
3461 return INPLACE_ADD;
3462 case Sub:
3463 return INPLACE_SUBTRACT;
3464 case Mult:
3465 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003466 case MatMult:
3467 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 case Div:
3469 return INPLACE_TRUE_DIVIDE;
3470 case Mod:
3471 return INPLACE_MODULO;
3472 case Pow:
3473 return INPLACE_POWER;
3474 case LShift:
3475 return INPLACE_LSHIFT;
3476 case RShift:
3477 return INPLACE_RSHIFT;
3478 case BitOr:
3479 return INPLACE_OR;
3480 case BitXor:
3481 return INPLACE_XOR;
3482 case BitAnd:
3483 return INPLACE_AND;
3484 case FloorDiv:
3485 return INPLACE_FLOOR_DIVIDE;
3486 default:
3487 PyErr_Format(PyExc_SystemError,
3488 "inplace binary op %d should not be possible", op);
3489 return 0;
3490 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491}
3492
3493static int
3494compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3495{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003496 int op, scope;
3497 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 PyObject *dict = c->u->u_names;
3501 PyObject *mangled;
3502 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003504 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3505 !_PyUnicode_EqualToASCIIString(name, "True") &&
3506 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003507
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003508 mangled = _Py_Mangle(c->u->u_private, name);
3509 if (!mangled)
3510 return 0;
3511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 op = 0;
3513 optype = OP_NAME;
3514 scope = PyST_GetScope(c->u->u_ste, mangled);
3515 switch (scope) {
3516 case FREE:
3517 dict = c->u->u_freevars;
3518 optype = OP_DEREF;
3519 break;
3520 case CELL:
3521 dict = c->u->u_cellvars;
3522 optype = OP_DEREF;
3523 break;
3524 case LOCAL:
3525 if (c->u->u_ste->ste_type == FunctionBlock)
3526 optype = OP_FAST;
3527 break;
3528 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003529 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 optype = OP_GLOBAL;
3531 break;
3532 case GLOBAL_EXPLICIT:
3533 optype = OP_GLOBAL;
3534 break;
3535 default:
3536 /* scope can be 0 */
3537 break;
3538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003541 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 switch (optype) {
3544 case OP_DEREF:
3545 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003546 case Load:
3547 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3548 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003549 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003550 op = STORE_DEREF;
3551 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 case AugLoad:
3553 case AugStore:
3554 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003555 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 case Param:
3557 default:
3558 PyErr_SetString(PyExc_SystemError,
3559 "param invalid for deref variable");
3560 return 0;
3561 }
3562 break;
3563 case OP_FAST:
3564 switch (ctx) {
3565 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003566 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003567 op = STORE_FAST;
3568 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 case Del: op = DELETE_FAST; break;
3570 case AugLoad:
3571 case AugStore:
3572 break;
3573 case Param:
3574 default:
3575 PyErr_SetString(PyExc_SystemError,
3576 "param invalid for local variable");
3577 return 0;
3578 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003579 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 return 1;
3581 case OP_GLOBAL:
3582 switch (ctx) {
3583 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003584 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003585 op = STORE_GLOBAL;
3586 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 case Del: op = DELETE_GLOBAL; break;
3588 case AugLoad:
3589 case AugStore:
3590 break;
3591 case Param:
3592 default:
3593 PyErr_SetString(PyExc_SystemError,
3594 "param invalid for global variable");
3595 return 0;
3596 }
3597 break;
3598 case OP_NAME:
3599 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003600 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003601 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003602 op = STORE_NAME;
3603 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 case Del: op = DELETE_NAME; break;
3605 case AugLoad:
3606 case AugStore:
3607 break;
3608 case Param:
3609 default:
3610 PyErr_SetString(PyExc_SystemError,
3611 "param invalid for name variable");
3612 return 0;
3613 }
3614 break;
3615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 assert(op);
3618 arg = compiler_add_o(c, dict, mangled);
3619 Py_DECREF(mangled);
3620 if (arg < 0)
3621 return 0;
3622 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623}
3624
3625static int
3626compiler_boolop(struct compiler *c, expr_ty e)
3627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003629 int jumpi;
3630 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 assert(e->kind == BoolOp_kind);
3634 if (e->v.BoolOp.op == And)
3635 jumpi = JUMP_IF_FALSE_OR_POP;
3636 else
3637 jumpi = JUMP_IF_TRUE_OR_POP;
3638 end = compiler_new_block(c);
3639 if (end == NULL)
3640 return 0;
3641 s = e->v.BoolOp.values;
3642 n = asdl_seq_LEN(s) - 1;
3643 assert(n >= 0);
3644 for (i = 0; i < n; ++i) {
3645 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3646 ADDOP_JABS(c, jumpi, end);
3647 }
3648 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3649 compiler_use_next_block(c, end);
3650 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651}
3652
3653static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003654starunpack_helper(struct compiler *c, asdl_seq *elts,
3655 int single_op, int inner_op, int outer_op)
3656{
3657 Py_ssize_t n = asdl_seq_LEN(elts);
3658 Py_ssize_t i, nsubitems = 0, nseen = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003659 if (n > 2 && are_all_items_const(elts, 0, n)) {
3660 PyObject *folded = PyTuple_New(n);
3661 if (folded == NULL) {
3662 return 0;
3663 }
3664 PyObject *val;
3665 for (i = 0; i < n; i++) {
3666 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3667 Py_INCREF(val);
3668 PyTuple_SET_ITEM(folded, i, val);
3669 }
3670 if (outer_op == BUILD_SET_UNPACK) {
3671 Py_SETREF(folded, PyFrozenSet_New(folded));
3672 if (folded == NULL) {
3673 return 0;
3674 }
3675 }
3676 ADDOP_LOAD_CONST_NEW(c, folded);
3677 ADDOP_I(c, outer_op, 1);
3678 return 1;
3679 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003680 for (i = 0; i < n; i++) {
3681 expr_ty elt = asdl_seq_GET(elts, i);
3682 if (elt->kind == Starred_kind) {
3683 if (nseen) {
3684 ADDOP_I(c, inner_op, nseen);
3685 nseen = 0;
3686 nsubitems++;
3687 }
3688 VISIT(c, expr, elt->v.Starred.value);
3689 nsubitems++;
3690 }
3691 else {
3692 VISIT(c, expr, elt);
3693 nseen++;
3694 }
3695 }
3696 if (nsubitems) {
3697 if (nseen) {
3698 ADDOP_I(c, inner_op, nseen);
3699 nsubitems++;
3700 }
3701 ADDOP_I(c, outer_op, nsubitems);
3702 }
3703 else
3704 ADDOP_I(c, single_op, nseen);
3705 return 1;
3706}
3707
3708static int
3709assignment_helper(struct compiler *c, asdl_seq *elts)
3710{
3711 Py_ssize_t n = asdl_seq_LEN(elts);
3712 Py_ssize_t i;
3713 int seen_star = 0;
3714 for (i = 0; i < n; i++) {
3715 expr_ty elt = asdl_seq_GET(elts, i);
3716 if (elt->kind == Starred_kind && !seen_star) {
3717 if ((i >= (1 << 8)) ||
3718 (n-i-1 >= (INT_MAX >> 8)))
3719 return compiler_error(c,
3720 "too many expressions in "
3721 "star-unpacking assignment");
3722 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3723 seen_star = 1;
3724 asdl_seq_SET(elts, i, elt->v.Starred.value);
3725 }
3726 else if (elt->kind == Starred_kind) {
3727 return compiler_error(c,
3728 "two starred expressions in assignment");
3729 }
3730 }
3731 if (!seen_star) {
3732 ADDOP_I(c, UNPACK_SEQUENCE, n);
3733 }
3734 VISIT_SEQ(c, expr, elts);
3735 return 1;
3736}
3737
3738static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739compiler_list(struct compiler *c, expr_ty e)
3740{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003741 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003742 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003745 else if (e->v.List.ctx == Load) {
3746 return starunpack_helper(c, elts,
3747 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 else
3750 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003752}
3753
3754static int
3755compiler_tuple(struct compiler *c, expr_ty e)
3756{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003758 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003759 return assignment_helper(c, elts);
3760 }
3761 else if (e->v.Tuple.ctx == Load) {
3762 return starunpack_helper(c, elts,
3763 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3764 }
3765 else
3766 VISIT_SEQ(c, expr, elts);
3767 return 1;
3768}
3769
3770static int
3771compiler_set(struct compiler *c, expr_ty e)
3772{
3773 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3774 BUILD_SET, BUILD_SET_UNPACK);
3775}
3776
3777static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003778are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3779{
3780 Py_ssize_t i;
3781 for (i = begin; i < end; i++) {
3782 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003783 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003784 return 0;
3785 }
3786 return 1;
3787}
3788
3789static int
3790compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3791{
3792 Py_ssize_t i, n = end - begin;
3793 PyObject *keys, *key;
3794 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3795 for (i = begin; i < end; i++) {
3796 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3797 }
3798 keys = PyTuple_New(n);
3799 if (keys == NULL) {
3800 return 0;
3801 }
3802 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003803 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003804 Py_INCREF(key);
3805 PyTuple_SET_ITEM(keys, i - begin, key);
3806 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003807 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003808 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3809 }
3810 else {
3811 for (i = begin; i < end; i++) {
3812 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3813 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3814 }
3815 ADDOP_I(c, BUILD_MAP, n);
3816 }
3817 return 1;
3818}
3819
3820static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821compiler_dict(struct compiler *c, expr_ty e)
3822{
Victor Stinner976bb402016-03-23 11:36:19 +01003823 Py_ssize_t i, n, elements;
3824 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003825 int is_unpacking = 0;
3826 n = asdl_seq_LEN(e->v.Dict.values);
3827 containers = 0;
3828 elements = 0;
3829 for (i = 0; i < n; i++) {
3830 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3831 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003832 if (!compiler_subdict(c, e, i - elements, i))
3833 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003834 containers++;
3835 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003837 if (is_unpacking) {
3838 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3839 containers++;
3840 }
3841 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003842 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 }
3844 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003845 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003846 if (!compiler_subdict(c, e, n - elements, n))
3847 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003848 containers++;
3849 }
3850 /* If there is more than one dict, they need to be merged into a new
3851 * dict. If there is one dict and it's an unpacking, then it needs
3852 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003853 if (containers > 1 || is_unpacking) {
3854 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 }
3856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857}
3858
3859static int
3860compiler_compare(struct compiler *c, expr_ty e)
3861{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003862 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003864 if (!check_compare(c, e)) {
3865 return 0;
3866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003868 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3869 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3870 if (n == 0) {
3871 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3872 ADDOP_I(c, COMPARE_OP,
3873 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3874 }
3875 else {
3876 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 if (cleanup == NULL)
3878 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003879 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 VISIT(c, expr,
3881 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003882 ADDOP(c, DUP_TOP);
3883 ADDOP(c, ROT_THREE);
3884 ADDOP_I(c, COMPARE_OP,
3885 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3886 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3887 NEXT_BLOCK(c);
3888 }
3889 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3890 ADDOP_I(c, COMPARE_OP,
3891 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 basicblock *end = compiler_new_block(c);
3893 if (end == NULL)
3894 return 0;
3895 ADDOP_JREL(c, JUMP_FORWARD, end);
3896 compiler_use_next_block(c, cleanup);
3897 ADDOP(c, ROT_TWO);
3898 ADDOP(c, POP_TOP);
3899 compiler_use_next_block(c, end);
3900 }
3901 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902}
3903
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003904static PyTypeObject *
3905infer_type(expr_ty e)
3906{
3907 switch (e->kind) {
3908 case Tuple_kind:
3909 return &PyTuple_Type;
3910 case List_kind:
3911 case ListComp_kind:
3912 return &PyList_Type;
3913 case Dict_kind:
3914 case DictComp_kind:
3915 return &PyDict_Type;
3916 case Set_kind:
3917 case SetComp_kind:
3918 return &PySet_Type;
3919 case GeneratorExp_kind:
3920 return &PyGen_Type;
3921 case Lambda_kind:
3922 return &PyFunction_Type;
3923 case JoinedStr_kind:
3924 case FormattedValue_kind:
3925 return &PyUnicode_Type;
3926 case Constant_kind:
3927 return e->v.Constant.value->ob_type;
3928 default:
3929 return NULL;
3930 }
3931}
3932
3933static int
3934check_caller(struct compiler *c, expr_ty e)
3935{
3936 switch (e->kind) {
3937 case Constant_kind:
3938 case Tuple_kind:
3939 case List_kind:
3940 case ListComp_kind:
3941 case Dict_kind:
3942 case DictComp_kind:
3943 case Set_kind:
3944 case SetComp_kind:
3945 case GeneratorExp_kind:
3946 case JoinedStr_kind:
3947 case FormattedValue_kind:
3948 return compiler_warn(c, "'%.200s' object is not callable; "
3949 "perhaps you missed a comma?",
3950 infer_type(e)->tp_name);
3951 default:
3952 return 1;
3953 }
3954}
3955
3956static int
3957check_subscripter(struct compiler *c, expr_ty e)
3958{
3959 PyObject *v;
3960
3961 switch (e->kind) {
3962 case Constant_kind:
3963 v = e->v.Constant.value;
3964 if (!(v == Py_None || v == Py_Ellipsis ||
3965 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3966 PyAnySet_Check(v)))
3967 {
3968 return 1;
3969 }
3970 /* fall through */
3971 case Set_kind:
3972 case SetComp_kind:
3973 case GeneratorExp_kind:
3974 case Lambda_kind:
3975 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3976 "perhaps you missed a comma?",
3977 infer_type(e)->tp_name);
3978 default:
3979 return 1;
3980 }
3981}
3982
3983static int
3984check_index(struct compiler *c, expr_ty e, slice_ty s)
3985{
3986 PyObject *v;
3987
3988 if (s->kind != Index_kind) {
3989 return 1;
3990 }
3991 PyTypeObject *index_type = infer_type(s->v.Index.value);
3992 if (index_type == NULL
3993 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3994 || index_type == &PySlice_Type) {
3995 return 1;
3996 }
3997
3998 switch (e->kind) {
3999 case Constant_kind:
4000 v = e->v.Constant.value;
4001 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4002 return 1;
4003 }
4004 /* fall through */
4005 case Tuple_kind:
4006 case List_kind:
4007 case ListComp_kind:
4008 case JoinedStr_kind:
4009 case FormattedValue_kind:
4010 return compiler_warn(c, "%.200s indices must be integers or slices, "
4011 "not %.200s; "
4012 "perhaps you missed a comma?",
4013 infer_type(e)->tp_name,
4014 index_type->tp_name);
4015 default:
4016 return 1;
4017 }
4018}
4019
Zackery Spytz97f5de02019-03-22 01:30:32 -06004020// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004021static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004022maybe_optimize_method_call(struct compiler *c, expr_ty e)
4023{
4024 Py_ssize_t argsl, i;
4025 expr_ty meth = e->v.Call.func;
4026 asdl_seq *args = e->v.Call.args;
4027
4028 /* Check that the call node is an attribute access, and that
4029 the call doesn't have keyword parameters. */
4030 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4031 asdl_seq_LEN(e->v.Call.keywords))
4032 return -1;
4033
4034 /* Check that there are no *varargs types of arguments. */
4035 argsl = asdl_seq_LEN(args);
4036 for (i = 0; i < argsl; i++) {
4037 expr_ty elt = asdl_seq_GET(args, i);
4038 if (elt->kind == Starred_kind) {
4039 return -1;
4040 }
4041 }
4042
4043 /* Alright, we can optimize the code. */
4044 VISIT(c, expr, meth->v.Attribute.value);
4045 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4046 VISIT_SEQ(c, expr, e->v.Call.args);
4047 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4048 return 1;
4049}
4050
4051static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004052compiler_call(struct compiler *c, expr_ty e)
4053{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004054 int ret = maybe_optimize_method_call(c, e);
4055 if (ret >= 0) {
4056 return ret;
4057 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004058 if (!check_caller(c, e->v.Call.func)) {
4059 return 0;
4060 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 VISIT(c, expr, e->v.Call.func);
4062 return compiler_call_helper(c, 0,
4063 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004064 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004065}
4066
Eric V. Smith235a6f02015-09-19 14:51:32 -04004067static int
4068compiler_joined_str(struct compiler *c, expr_ty e)
4069{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004070 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004071 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4072 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004073 return 1;
4074}
4075
Eric V. Smitha78c7952015-11-03 12:45:05 -05004076/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004077static int
4078compiler_formatted_value(struct compiler *c, expr_ty e)
4079{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004080 /* Our oparg encodes 2 pieces of information: the conversion
4081 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004082
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004083 Convert the conversion char to 3 bits:
4084 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004085 !s : 001 0x1 FVC_STR
4086 !r : 010 0x2 FVC_REPR
4087 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004088
Eric V. Smitha78c7952015-11-03 12:45:05 -05004089 next bit is whether or not we have a format spec:
4090 yes : 100 0x4
4091 no : 000 0x0
4092 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004093
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004094 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004095 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004096
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004097 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004098 VISIT(c, expr, e->v.FormattedValue.value);
4099
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004100 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004101 case 's': oparg = FVC_STR; break;
4102 case 'r': oparg = FVC_REPR; break;
4103 case 'a': oparg = FVC_ASCII; break;
4104 case -1: oparg = FVC_NONE; break;
4105 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004106 PyErr_Format(PyExc_SystemError,
4107 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004108 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004109 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004110 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004111 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004112 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004113 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004114 }
4115
Eric V. Smitha78c7952015-11-03 12:45:05 -05004116 /* And push our opcode and oparg */
4117 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004118
Eric V. Smith235a6f02015-09-19 14:51:32 -04004119 return 1;
4120}
4121
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004122static int
4123compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4124{
4125 Py_ssize_t i, n = end - begin;
4126 keyword_ty kw;
4127 PyObject *keys, *key;
4128 assert(n > 0);
4129 if (n > 1) {
4130 for (i = begin; i < end; i++) {
4131 kw = asdl_seq_GET(keywords, i);
4132 VISIT(c, expr, kw->value);
4133 }
4134 keys = PyTuple_New(n);
4135 if (keys == NULL) {
4136 return 0;
4137 }
4138 for (i = begin; i < end; i++) {
4139 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4140 Py_INCREF(key);
4141 PyTuple_SET_ITEM(keys, i - begin, key);
4142 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004143 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004144 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4145 }
4146 else {
4147 /* a for loop only executes once */
4148 for (i = begin; i < end; i++) {
4149 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004150 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004151 VISIT(c, expr, kw->value);
4152 }
4153 ADDOP_I(c, BUILD_MAP, n);
4154 }
4155 return 1;
4156}
4157
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004158/* shared code between compiler_call and compiler_class */
4159static int
4160compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004161 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004162 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004163 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004164{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004165 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004166 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004167
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004168 /* the number of tuples and dictionaries on the stack */
4169 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4170
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004171 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004172 nkwelts = asdl_seq_LEN(keywords);
4173
4174 for (i = 0; i < nkwelts; i++) {
4175 keyword_ty kw = asdl_seq_GET(keywords, i);
4176 if (kw->arg == NULL) {
4177 mustdictunpack = 1;
4178 break;
4179 }
4180 }
4181
4182 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004183 for (i = 0; i < nelts; i++) {
4184 expr_ty elt = asdl_seq_GET(args, i);
4185 if (elt->kind == Starred_kind) {
4186 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004187 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004188 if (nseen) {
4189 ADDOP_I(c, BUILD_TUPLE, nseen);
4190 nseen = 0;
4191 nsubargs++;
4192 }
4193 VISIT(c, expr, elt->v.Starred.value);
4194 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004195 }
4196 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004197 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004198 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004199 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004201
4202 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004203 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004204 if (nseen) {
4205 /* Pack up any trailing positional arguments. */
4206 ADDOP_I(c, BUILD_TUPLE, nseen);
4207 nsubargs++;
4208 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004209 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004210 /* If we ended up with more than one stararg, we need
4211 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004212 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004213 }
4214 else if (nsubargs == 0) {
4215 ADDOP_I(c, BUILD_TUPLE, 0);
4216 }
4217 nseen = 0; /* the number of keyword arguments on the stack following */
4218 for (i = 0; i < nkwelts; i++) {
4219 keyword_ty kw = asdl_seq_GET(keywords, i);
4220 if (kw->arg == NULL) {
4221 /* A keyword argument unpacking. */
4222 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004223 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4224 return 0;
4225 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004226 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004227 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004228 VISIT(c, expr, kw->value);
4229 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004230 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004231 else {
4232 nseen++;
4233 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004234 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004235 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004236 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004237 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004238 return 0;
4239 nsubkwargs++;
4240 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004241 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004242 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004243 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004245 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4246 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004248 else if (nkwelts) {
4249 PyObject *names;
4250 VISIT_SEQ(c, keyword, keywords);
4251 names = PyTuple_New(nkwelts);
4252 if (names == NULL) {
4253 return 0;
4254 }
4255 for (i = 0; i < nkwelts; i++) {
4256 keyword_ty kw = asdl_seq_GET(keywords, i);
4257 Py_INCREF(kw->arg);
4258 PyTuple_SET_ITEM(names, i, kw->arg);
4259 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004260 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004261 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4262 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 else {
4265 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4266 return 1;
4267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268}
4269
Nick Coghlan650f0d02007-04-15 12:05:43 +00004270
4271/* List and set comprehensions and generator expressions work by creating a
4272 nested function to perform the actual iteration. This means that the
4273 iteration variables don't leak into the current scope.
4274 The defined function is called immediately following its definition, with the
4275 result of that call being the result of the expression.
4276 The LC/SC version returns the populated container, while the GE version is
4277 flagged in symtable.c as a generator, so it returns the generator object
4278 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004279
4280 Possible cleanups:
4281 - iterate over the generator sequence instead of using recursion
4282*/
4283
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286compiler_comprehension_generator(struct compiler *c,
4287 asdl_seq *generators, int gen_index,
4288 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004290 comprehension_ty gen;
4291 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4292 if (gen->is_async) {
4293 return compiler_async_comprehension_generator(
4294 c, generators, gen_index, elt, val, type);
4295 } else {
4296 return compiler_sync_comprehension_generator(
4297 c, generators, gen_index, elt, val, type);
4298 }
4299}
4300
4301static int
4302compiler_sync_comprehension_generator(struct compiler *c,
4303 asdl_seq *generators, int gen_index,
4304 expr_ty elt, expr_ty val, int type)
4305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 /* generate code for the iterator, then each of the ifs,
4307 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 comprehension_ty gen;
4310 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004311 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 start = compiler_new_block(c);
4314 skip = compiler_new_block(c);
4315 if_cleanup = compiler_new_block(c);
4316 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4319 anchor == NULL)
4320 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 if (gen_index == 0) {
4325 /* Receive outermost iter as an implicit argument */
4326 c->u->u_argcount = 1;
4327 ADDOP_I(c, LOAD_FAST, 0);
4328 }
4329 else {
4330 /* Sub-iter - calculate on the fly */
4331 VISIT(c, expr, gen->iter);
4332 ADDOP(c, GET_ITER);
4333 }
4334 compiler_use_next_block(c, start);
4335 ADDOP_JREL(c, FOR_ITER, anchor);
4336 NEXT_BLOCK(c);
4337 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 /* XXX this needs to be cleaned up...a lot! */
4340 n = asdl_seq_LEN(gen->ifs);
4341 for (i = 0; i < n; i++) {
4342 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004343 if (!compiler_jump_if(c, e, if_cleanup, 0))
4344 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 NEXT_BLOCK(c);
4346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 if (++gen_index < asdl_seq_LEN(generators))
4349 if (!compiler_comprehension_generator(c,
4350 generators, gen_index,
4351 elt, val, type))
4352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 /* only append after the last for generator */
4355 if (gen_index >= asdl_seq_LEN(generators)) {
4356 /* comprehension specific code */
4357 switch (type) {
4358 case COMP_GENEXP:
4359 VISIT(c, expr, elt);
4360 ADDOP(c, YIELD_VALUE);
4361 ADDOP(c, POP_TOP);
4362 break;
4363 case COMP_LISTCOMP:
4364 VISIT(c, expr, elt);
4365 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4366 break;
4367 case COMP_SETCOMP:
4368 VISIT(c, expr, elt);
4369 ADDOP_I(c, SET_ADD, gen_index + 1);
4370 break;
4371 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004372 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004375 VISIT(c, expr, val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 ADDOP_I(c, MAP_ADD, gen_index + 1);
4377 break;
4378 default:
4379 return 0;
4380 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 compiler_use_next_block(c, skip);
4383 }
4384 compiler_use_next_block(c, if_cleanup);
4385 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4386 compiler_use_next_block(c, anchor);
4387
4388 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389}
4390
4391static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004392compiler_async_comprehension_generator(struct compiler *c,
4393 asdl_seq *generators, int gen_index,
4394 expr_ty elt, expr_ty val, int type)
4395{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004397 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004398 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004399 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004400 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004401 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004402
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004403 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404 return 0;
4405 }
4406
4407 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4408
4409 if (gen_index == 0) {
4410 /* Receive outermost iter as an implicit argument */
4411 c->u->u_argcount = 1;
4412 ADDOP_I(c, LOAD_FAST, 0);
4413 }
4414 else {
4415 /* Sub-iter - calculate on the fly */
4416 VISIT(c, expr, gen->iter);
4417 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004418 }
4419
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004420 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004421
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004422 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004423 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004424 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004426 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004427 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004428
4429 n = asdl_seq_LEN(gen->ifs);
4430 for (i = 0; i < n; i++) {
4431 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004432 if (!compiler_jump_if(c, e, if_cleanup, 0))
4433 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004434 NEXT_BLOCK(c);
4435 }
4436
4437 if (++gen_index < asdl_seq_LEN(generators))
4438 if (!compiler_comprehension_generator(c,
4439 generators, gen_index,
4440 elt, val, type))
4441 return 0;
4442
4443 /* only append after the last for generator */
4444 if (gen_index >= asdl_seq_LEN(generators)) {
4445 /* comprehension specific code */
4446 switch (type) {
4447 case COMP_GENEXP:
4448 VISIT(c, expr, elt);
4449 ADDOP(c, YIELD_VALUE);
4450 ADDOP(c, POP_TOP);
4451 break;
4452 case COMP_LISTCOMP:
4453 VISIT(c, expr, elt);
4454 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4455 break;
4456 case COMP_SETCOMP:
4457 VISIT(c, expr, elt);
4458 ADDOP_I(c, SET_ADD, gen_index + 1);
4459 break;
4460 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004461 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004463 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004464 VISIT(c, expr, val);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004465 ADDOP_I(c, MAP_ADD, gen_index + 1);
4466 break;
4467 default:
4468 return 0;
4469 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004470 }
4471 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004472 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4473
4474 compiler_use_next_block(c, except);
4475 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004476
4477 return 1;
4478}
4479
4480static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004481compiler_comprehension(struct compiler *c, expr_ty e, int type,
4482 identifier name, asdl_seq *generators, expr_ty elt,
4483 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004487 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488 int is_async_function = c->u->u_ste->ste_coroutine;
4489 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004490
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004492
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004493 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4494 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 }
4498
4499 is_async_generator = c->u->u_ste->ste_coroutine;
4500
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004501 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 compiler_error(c, "asynchronous comprehension outside of "
4503 "an asynchronous function");
4504 goto error_in_scope;
4505 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 if (type != COMP_GENEXP) {
4508 int op;
4509 switch (type) {
4510 case COMP_LISTCOMP:
4511 op = BUILD_LIST;
4512 break;
4513 case COMP_SETCOMP:
4514 op = BUILD_SET;
4515 break;
4516 case COMP_DICTCOMP:
4517 op = BUILD_MAP;
4518 break;
4519 default:
4520 PyErr_Format(PyExc_SystemError,
4521 "unknown comprehension type %d", type);
4522 goto error_in_scope;
4523 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 ADDOP_I(c, op, 0);
4526 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (!compiler_comprehension_generator(c, generators, 0, elt,
4529 val, type))
4530 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (type != COMP_GENEXP) {
4533 ADDOP(c, RETURN_VALUE);
4534 }
4535
4536 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004537 qualname = c->u->u_qualname;
4538 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004540 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 goto error;
4542
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004543 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004545 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 Py_DECREF(co);
4547
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548 VISIT(c, expr, outermost->iter);
4549
4550 if (outermost->is_async) {
4551 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004552 } else {
4553 ADDOP(c, GET_ITER);
4554 }
4555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557
4558 if (is_async_generator && type != COMP_GENEXP) {
4559 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004560 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 ADDOP(c, YIELD_FROM);
4562 }
4563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004565error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004567error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004568 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 Py_XDECREF(co);
4570 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004571}
4572
4573static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004574compiler_genexp(struct compiler *c, expr_ty e)
4575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 static identifier name;
4577 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004578 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 if (!name)
4580 return 0;
4581 }
4582 assert(e->kind == GeneratorExp_kind);
4583 return compiler_comprehension(c, e, COMP_GENEXP, name,
4584 e->v.GeneratorExp.generators,
4585 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004586}
4587
4588static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004589compiler_listcomp(struct compiler *c, expr_ty e)
4590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 static identifier name;
4592 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004593 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 if (!name)
4595 return 0;
4596 }
4597 assert(e->kind == ListComp_kind);
4598 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4599 e->v.ListComp.generators,
4600 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004601}
4602
4603static int
4604compiler_setcomp(struct compiler *c, expr_ty e)
4605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 static identifier name;
4607 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004608 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004609 if (!name)
4610 return 0;
4611 }
4612 assert(e->kind == SetComp_kind);
4613 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4614 e->v.SetComp.generators,
4615 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004616}
4617
4618
4619static int
4620compiler_dictcomp(struct compiler *c, expr_ty e)
4621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 static identifier name;
4623 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004624 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 if (!name)
4626 return 0;
4627 }
4628 assert(e->kind == DictComp_kind);
4629 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4630 e->v.DictComp.generators,
4631 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004632}
4633
4634
4635static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004636compiler_visit_keyword(struct compiler *c, keyword_ty k)
4637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 VISIT(c, expr, k->value);
4639 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004640}
4641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004643 whether they are true or false.
4644
4645 Return values: 1 for true, 0 for false, -1 for non-constant.
4646 */
4647
4648static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004649expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004650{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004651 if (e->kind == Constant_kind) {
4652 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004653 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004654 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004655}
4656
Mark Shannonfee55262019-11-21 09:11:43 +00004657static int
4658compiler_with_except_finish(struct compiler *c) {
4659 basicblock *exit;
4660 exit = compiler_new_block(c);
4661 if (exit == NULL)
4662 return 0;
4663 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4664 ADDOP(c, RERAISE);
4665 compiler_use_next_block(c, exit);
4666 ADDOP(c, POP_TOP);
4667 ADDOP(c, POP_TOP);
4668 ADDOP(c, POP_TOP);
4669 ADDOP(c, POP_EXCEPT);
4670 ADDOP(c, POP_TOP);
4671 return 1;
4672}
Yury Selivanov75445082015-05-11 22:57:16 -04004673
4674/*
4675 Implements the async with statement.
4676
4677 The semantics outlined in that PEP are as follows:
4678
4679 async with EXPR as VAR:
4680 BLOCK
4681
4682 It is implemented roughly as:
4683
4684 context = EXPR
4685 exit = context.__aexit__ # not calling it
4686 value = await context.__aenter__()
4687 try:
4688 VAR = value # if VAR present in the syntax
4689 BLOCK
4690 finally:
4691 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004692 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004693 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004694 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004695 if not (await exit(*exc)):
4696 raise
4697 */
4698static int
4699compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4700{
Mark Shannonfee55262019-11-21 09:11:43 +00004701 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004702 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4703
4704 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004705 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4706 c->u->u_ste->ste_coroutine = 1;
4707 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004708 return compiler_error(c, "'async with' outside async function");
4709 }
Yury Selivanov75445082015-05-11 22:57:16 -04004710
4711 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004712 final = compiler_new_block(c);
4713 exit = compiler_new_block(c);
4714 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004715 return 0;
4716
4717 /* Evaluate EXPR */
4718 VISIT(c, expr, item->context_expr);
4719
4720 ADDOP(c, BEFORE_ASYNC_WITH);
4721 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004722 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004723 ADDOP(c, YIELD_FROM);
4724
Mark Shannonfee55262019-11-21 09:11:43 +00004725 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004726
4727 /* SETUP_ASYNC_WITH pushes a finally block. */
4728 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004729 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004730 return 0;
4731 }
4732
4733 if (item->optional_vars) {
4734 VISIT(c, expr, item->optional_vars);
4735 }
4736 else {
4737 /* Discard result from context.__aenter__() */
4738 ADDOP(c, POP_TOP);
4739 }
4740
4741 pos++;
4742 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4743 /* BLOCK code */
4744 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4745 else if (!compiler_async_with(c, s, pos))
4746 return 0;
4747
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004748 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004749 ADDOP(c, POP_BLOCK);
4750 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004751
Mark Shannonfee55262019-11-21 09:11:43 +00004752 /* For successful outcome:
4753 * call __exit__(None, None, None)
4754 */
4755 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004756 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004757 ADDOP(c, GET_AWAITABLE);
4758 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4759 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004760
Mark Shannonfee55262019-11-21 09:11:43 +00004761 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004762
Mark Shannonfee55262019-11-21 09:11:43 +00004763 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4764
4765 /* For exceptional outcome: */
4766 compiler_use_next_block(c, final);
4767
4768 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004769 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004770 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004771 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004772 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004773
Mark Shannonfee55262019-11-21 09:11:43 +00004774compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004775 return 1;
4776}
4777
4778
Guido van Rossumc2e20742006-02-27 22:32:47 +00004779/*
4780 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004781 with EXPR as VAR:
4782 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004783 is implemented as:
4784 <code for EXPR>
4785 SETUP_WITH E
4786 <code to store to VAR> or POP_TOP
4787 <code for BLOCK>
4788 LOAD_CONST (None, None, None)
4789 CALL_FUNCTION_EX 0
4790 JUMP_FORWARD EXIT
4791 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4792 POP_JUMP_IF_TRUE T:
4793 RERAISE
4794 T: POP_TOP * 3 (remove exception from stack)
4795 POP_EXCEPT
4796 POP_TOP
4797 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004798 */
Mark Shannonfee55262019-11-21 09:11:43 +00004799
Guido van Rossumc2e20742006-02-27 22:32:47 +00004800static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004801compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004802{
Mark Shannonfee55262019-11-21 09:11:43 +00004803 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004804 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004805
4806 assert(s->kind == With_kind);
4807
Guido van Rossumc2e20742006-02-27 22:32:47 +00004808 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004809 final = compiler_new_block(c);
4810 exit = compiler_new_block(c);
4811 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004812 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004813
Thomas Wouters477c8d52006-05-27 19:21:47 +00004814 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004815 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004816 /* Will push bound __exit__ */
4817 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004818
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004819 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004820 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004821 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004822 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004823 }
4824
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004825 if (item->optional_vars) {
4826 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004827 }
4828 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004830 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004831 }
4832
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004833 pos++;
4834 if (pos == asdl_seq_LEN(s->v.With.items))
4835 /* BLOCK code */
4836 VISIT_SEQ(c, stmt, s->v.With.body)
4837 else if (!compiler_with(c, s, pos))
4838 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004839
Guido van Rossumc2e20742006-02-27 22:32:47 +00004840 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004841 compiler_pop_fblock(c, WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004842
4843 /* End of body; start the cleanup. */
4844
4845 /* For successful outcome:
4846 * call __exit__(None, None, None)
4847 */
4848 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004849 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004850 ADDOP(c, POP_TOP);
4851 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004852
Mark Shannonfee55262019-11-21 09:11:43 +00004853 /* For exceptional outcome: */
4854 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004855
Mark Shannonfee55262019-11-21 09:11:43 +00004856 ADDOP(c, WITH_EXCEPT_START);
4857 compiler_with_except_finish(c);
4858
4859 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004860 return 1;
4861}
4862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004863static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004864compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004867 case NamedExpr_kind:
4868 VISIT(c, expr, e->v.NamedExpr.value);
4869 ADDOP(c, DUP_TOP);
4870 VISIT(c, expr, e->v.NamedExpr.target);
4871 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 case BoolOp_kind:
4873 return compiler_boolop(c, e);
4874 case BinOp_kind:
4875 VISIT(c, expr, e->v.BinOp.left);
4876 VISIT(c, expr, e->v.BinOp.right);
4877 ADDOP(c, binop(c, e->v.BinOp.op));
4878 break;
4879 case UnaryOp_kind:
4880 VISIT(c, expr, e->v.UnaryOp.operand);
4881 ADDOP(c, unaryop(e->v.UnaryOp.op));
4882 break;
4883 case Lambda_kind:
4884 return compiler_lambda(c, e);
4885 case IfExp_kind:
4886 return compiler_ifexp(c, e);
4887 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004888 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004890 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 case GeneratorExp_kind:
4892 return compiler_genexp(c, e);
4893 case ListComp_kind:
4894 return compiler_listcomp(c, e);
4895 case SetComp_kind:
4896 return compiler_setcomp(c, e);
4897 case DictComp_kind:
4898 return compiler_dictcomp(c, e);
4899 case Yield_kind:
4900 if (c->u->u_ste->ste_type != FunctionBlock)
4901 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004902 if (e->v.Yield.value) {
4903 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 }
4905 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004906 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004908 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004910 case YieldFrom_kind:
4911 if (c->u->u_ste->ste_type != FunctionBlock)
4912 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004913
4914 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4915 return compiler_error(c, "'yield from' inside async function");
4916
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004917 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004918 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004919 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004920 ADDOP(c, YIELD_FROM);
4921 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004922 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004923 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
4924 if (c->u->u_ste->ste_type != FunctionBlock){
4925 return compiler_error(c, "'await' outside function");
4926 }
Yury Selivanov75445082015-05-11 22:57:16 -04004927
Victor Stinner331a6a52019-05-27 16:39:22 +02004928 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004929 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4930 return compiler_error(c, "'await' outside async function");
4931 }
4932 }
Yury Selivanov75445082015-05-11 22:57:16 -04004933
4934 VISIT(c, expr, e->v.Await.value);
4935 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004936 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004937 ADDOP(c, YIELD_FROM);
4938 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 case Compare_kind:
4940 return compiler_compare(c, e);
4941 case Call_kind:
4942 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004943 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004944 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004945 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004946 case JoinedStr_kind:
4947 return compiler_joined_str(c, e);
4948 case FormattedValue_kind:
4949 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 /* The following exprs can be assignment targets. */
4951 case Attribute_kind:
4952 if (e->v.Attribute.ctx != AugStore)
4953 VISIT(c, expr, e->v.Attribute.value);
4954 switch (e->v.Attribute.ctx) {
4955 case AugLoad:
4956 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004957 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 case Load:
4959 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4960 break;
4961 case AugStore:
4962 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004963 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 case Store:
4965 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4966 break;
4967 case Del:
4968 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4969 break;
4970 case Param:
4971 default:
4972 PyErr_SetString(PyExc_SystemError,
4973 "param invalid in attribute expression");
4974 return 0;
4975 }
4976 break;
4977 case Subscript_kind:
4978 switch (e->v.Subscript.ctx) {
4979 case AugLoad:
4980 VISIT(c, expr, e->v.Subscript.value);
4981 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4982 break;
4983 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004984 if (!check_subscripter(c, e->v.Subscript.value)) {
4985 return 0;
4986 }
4987 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4988 return 0;
4989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 VISIT(c, expr, e->v.Subscript.value);
4991 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4992 break;
4993 case AugStore:
4994 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4995 break;
4996 case Store:
4997 VISIT(c, expr, e->v.Subscript.value);
4998 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4999 break;
5000 case Del:
5001 VISIT(c, expr, e->v.Subscript.value);
5002 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5003 break;
5004 case Param:
5005 default:
5006 PyErr_SetString(PyExc_SystemError,
5007 "param invalid in subscript expression");
5008 return 0;
5009 }
5010 break;
5011 case Starred_kind:
5012 switch (e->v.Starred.ctx) {
5013 case Store:
5014 /* In all legitimate cases, the Starred node was already replaced
5015 * by compiler_list/compiler_tuple. XXX: is that okay? */
5016 return compiler_error(c,
5017 "starred assignment target must be in a list or tuple");
5018 default:
5019 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005020 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 case Name_kind:
5023 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5024 /* child nodes of List and Tuple will have expr_context set */
5025 case List_kind:
5026 return compiler_list(c, e);
5027 case Tuple_kind:
5028 return compiler_tuple(c, e);
5029 }
5030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005031}
5032
5033static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005034compiler_visit_expr(struct compiler *c, expr_ty e)
5035{
5036 /* If expr e has a different line number than the last expr/stmt,
5037 set a new line number for the next instruction.
5038 */
5039 int old_lineno = c->u->u_lineno;
5040 int old_col_offset = c->u->u_col_offset;
5041 if (e->lineno != c->u->u_lineno) {
5042 c->u->u_lineno = e->lineno;
5043 c->u->u_lineno_set = 0;
5044 }
5045 /* Updating the column offset is always harmless. */
5046 c->u->u_col_offset = e->col_offset;
5047
5048 int res = compiler_visit_expr1(c, e);
5049
5050 if (old_lineno != c->u->u_lineno) {
5051 c->u->u_lineno = old_lineno;
5052 c->u->u_lineno_set = 0;
5053 }
5054 c->u->u_col_offset = old_col_offset;
5055 return res;
5056}
5057
5058static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005059compiler_augassign(struct compiler *c, stmt_ty s)
5060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 expr_ty e = s->v.AugAssign.target;
5062 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 switch (e->kind) {
5067 case Attribute_kind:
5068 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005069 AugLoad, e->lineno, e->col_offset,
5070 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 if (auge == NULL)
5072 return 0;
5073 VISIT(c, expr, auge);
5074 VISIT(c, expr, s->v.AugAssign.value);
5075 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5076 auge->v.Attribute.ctx = AugStore;
5077 VISIT(c, expr, auge);
5078 break;
5079 case Subscript_kind:
5080 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005081 AugLoad, e->lineno, e->col_offset,
5082 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 if (auge == NULL)
5084 return 0;
5085 VISIT(c, expr, auge);
5086 VISIT(c, expr, s->v.AugAssign.value);
5087 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5088 auge->v.Subscript.ctx = AugStore;
5089 VISIT(c, expr, auge);
5090 break;
5091 case Name_kind:
5092 if (!compiler_nameop(c, e->v.Name.id, Load))
5093 return 0;
5094 VISIT(c, expr, s->v.AugAssign.value);
5095 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5096 return compiler_nameop(c, e->v.Name.id, Store);
5097 default:
5098 PyErr_Format(PyExc_SystemError,
5099 "invalid node type (%d) for augmented assignment",
5100 e->kind);
5101 return 0;
5102 }
5103 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005104}
5105
5106static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005107check_ann_expr(struct compiler *c, expr_ty e)
5108{
5109 VISIT(c, expr, e);
5110 ADDOP(c, POP_TOP);
5111 return 1;
5112}
5113
5114static int
5115check_annotation(struct compiler *c, stmt_ty s)
5116{
5117 /* Annotations are only evaluated in a module or class. */
5118 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5119 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5120 return check_ann_expr(c, s->v.AnnAssign.annotation);
5121 }
5122 return 1;
5123}
5124
5125static int
5126check_ann_slice(struct compiler *c, slice_ty sl)
5127{
5128 switch(sl->kind) {
5129 case Index_kind:
5130 return check_ann_expr(c, sl->v.Index.value);
5131 case Slice_kind:
5132 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5133 return 0;
5134 }
5135 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5136 return 0;
5137 }
5138 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5139 return 0;
5140 }
5141 break;
5142 default:
5143 PyErr_SetString(PyExc_SystemError,
5144 "unexpected slice kind");
5145 return 0;
5146 }
5147 return 1;
5148}
5149
5150static int
5151check_ann_subscr(struct compiler *c, slice_ty sl)
5152{
5153 /* We check that everything in a subscript is defined at runtime. */
5154 Py_ssize_t i, n;
5155
5156 switch (sl->kind) {
5157 case Index_kind:
5158 case Slice_kind:
5159 if (!check_ann_slice(c, sl)) {
5160 return 0;
5161 }
5162 break;
5163 case ExtSlice_kind:
5164 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5165 for (i = 0; i < n; i++) {
5166 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5167 switch (subsl->kind) {
5168 case Index_kind:
5169 case Slice_kind:
5170 if (!check_ann_slice(c, subsl)) {
5171 return 0;
5172 }
5173 break;
5174 case ExtSlice_kind:
5175 default:
5176 PyErr_SetString(PyExc_SystemError,
5177 "extended slice invalid in nested slice");
5178 return 0;
5179 }
5180 }
5181 break;
5182 default:
5183 PyErr_Format(PyExc_SystemError,
5184 "invalid subscript kind %d", sl->kind);
5185 return 0;
5186 }
5187 return 1;
5188}
5189
5190static int
5191compiler_annassign(struct compiler *c, stmt_ty s)
5192{
5193 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005194 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005195
5196 assert(s->kind == AnnAssign_kind);
5197
5198 /* We perform the actual assignment first. */
5199 if (s->v.AnnAssign.value) {
5200 VISIT(c, expr, s->v.AnnAssign.value);
5201 VISIT(c, expr, targ);
5202 }
5203 switch (targ->kind) {
5204 case Name_kind:
5205 /* If we have a simple name in a module or class, store annotation. */
5206 if (s->v.AnnAssign.simple &&
5207 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5208 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005209 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5210 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5211 }
5212 else {
5213 VISIT(c, expr, s->v.AnnAssign.annotation);
5214 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005215 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005216 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005217 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005218 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005219 }
5220 break;
5221 case Attribute_kind:
5222 if (!s->v.AnnAssign.value &&
5223 !check_ann_expr(c, targ->v.Attribute.value)) {
5224 return 0;
5225 }
5226 break;
5227 case Subscript_kind:
5228 if (!s->v.AnnAssign.value &&
5229 (!check_ann_expr(c, targ->v.Subscript.value) ||
5230 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5231 return 0;
5232 }
5233 break;
5234 default:
5235 PyErr_Format(PyExc_SystemError,
5236 "invalid node type (%d) for annotated assignment",
5237 targ->kind);
5238 return 0;
5239 }
5240 /* Annotation is evaluated last. */
5241 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5242 return 0;
5243 }
5244 return 1;
5245}
5246
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005247/* Raises a SyntaxError and returns 0.
5248 If something goes wrong, a different exception may be raised.
5249*/
5250
5251static int
5252compiler_error(struct compiler *c, const char *errstr)
5253{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005254 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005256
Victor Stinner14e461d2013-08-26 22:28:21 +02005257 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 if (!loc) {
5259 Py_INCREF(Py_None);
5260 loc = Py_None;
5261 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005262 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005263 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 if (!u)
5265 goto exit;
5266 v = Py_BuildValue("(zO)", errstr, u);
5267 if (!v)
5268 goto exit;
5269 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005270 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 Py_DECREF(loc);
5272 Py_XDECREF(u);
5273 Py_XDECREF(v);
5274 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005275}
5276
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005277/* Emits a SyntaxWarning and returns 1 on success.
5278 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5279 and returns 0.
5280*/
5281static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005282compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005283{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005284 va_list vargs;
5285#ifdef HAVE_STDARG_PROTOTYPES
5286 va_start(vargs, format);
5287#else
5288 va_start(vargs);
5289#endif
5290 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5291 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005292 if (msg == NULL) {
5293 return 0;
5294 }
5295 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5296 c->u->u_lineno, NULL, NULL) < 0)
5297 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005298 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005299 /* Replace the SyntaxWarning exception with a SyntaxError
5300 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005301 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005302 assert(PyUnicode_AsUTF8(msg) != NULL);
5303 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005304 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005305 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005306 return 0;
5307 }
5308 Py_DECREF(msg);
5309 return 1;
5310}
5311
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313compiler_handle_subscr(struct compiler *c, const char *kind,
5314 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 /* XXX this code is duplicated */
5319 switch (ctx) {
5320 case AugLoad: /* fall through to Load */
5321 case Load: op = BINARY_SUBSCR; break;
5322 case AugStore:/* fall through to Store */
5323 case Store: op = STORE_SUBSCR; break;
5324 case Del: op = DELETE_SUBSCR; break;
5325 case Param:
5326 PyErr_Format(PyExc_SystemError,
5327 "invalid %s kind %d in subscript\n",
5328 kind, ctx);
5329 return 0;
5330 }
5331 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005332 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005333 }
5334 else if (ctx == AugStore) {
5335 ADDOP(c, ROT_THREE);
5336 }
5337 ADDOP(c, op);
5338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005339}
5340
5341static int
5342compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 int n = 2;
5345 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 /* only handles the cases where BUILD_SLICE is emitted */
5348 if (s->v.Slice.lower) {
5349 VISIT(c, expr, s->v.Slice.lower);
5350 }
5351 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005352 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 if (s->v.Slice.upper) {
5356 VISIT(c, expr, s->v.Slice.upper);
5357 }
5358 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005359 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 }
5361
5362 if (s->v.Slice.step) {
5363 n++;
5364 VISIT(c, expr, s->v.Slice.step);
5365 }
5366 ADDOP_I(c, BUILD_SLICE, n);
5367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368}
5369
5370static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5372 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 switch (s->kind) {
5375 case Slice_kind:
5376 return compiler_slice(c, s, ctx);
5377 case Index_kind:
5378 VISIT(c, expr, s->v.Index.value);
5379 break;
5380 case ExtSlice_kind:
5381 default:
5382 PyErr_SetString(PyExc_SystemError,
5383 "extended slice invalid in nested slice");
5384 return 0;
5385 }
5386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387}
5388
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005389static int
5390compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5391{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005392 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 switch (s->kind) {
5394 case Index_kind:
5395 kindname = "index";
5396 if (ctx != AugStore) {
5397 VISIT(c, expr, s->v.Index.value);
5398 }
5399 break;
5400 case Slice_kind:
5401 kindname = "slice";
5402 if (ctx != AugStore) {
5403 if (!compiler_slice(c, s, ctx))
5404 return 0;
5405 }
5406 break;
5407 case ExtSlice_kind:
5408 kindname = "extended slice";
5409 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005410 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 for (i = 0; i < n; i++) {
5412 slice_ty sub = (slice_ty)asdl_seq_GET(
5413 s->v.ExtSlice.dims, i);
5414 if (!compiler_visit_nested_slice(c, sub, ctx))
5415 return 0;
5416 }
5417 ADDOP_I(c, BUILD_TUPLE, n);
5418 }
5419 break;
5420 default:
5421 PyErr_Format(PyExc_SystemError,
5422 "invalid subscript kind %d", s->kind);
5423 return 0;
5424 }
5425 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005426}
5427
Thomas Wouters89f507f2006-12-13 04:49:30 +00005428/* End of the compiler section, beginning of the assembler section */
5429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005431 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005432
5433 XXX must handle implicit jumps from one block to next
5434*/
5435
Thomas Wouters89f507f2006-12-13 04:49:30 +00005436struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 PyObject *a_bytecode; /* string containing bytecode */
5438 int a_offset; /* offset into bytecode */
5439 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005440 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 PyObject *a_lnotab; /* string containing lnotab */
5442 int a_lnotab_off; /* offset into lnotab */
5443 int a_lineno; /* last lineno of emitted instruction */
5444 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005445};
5446
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447static void
T. Wouters99b54d62019-09-12 07:05:33 -07005448dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005449{
T. Wouters99b54d62019-09-12 07:05:33 -07005450 int i, j;
5451
5452 /* Get rid of recursion for normal control flow.
5453 Since the number of blocks is limited, unused space in a_postorder
5454 (from a_nblocks to end) can be used as a stack for still not ordered
5455 blocks. */
5456 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005457 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005458 assert(a->a_nblocks < j);
5459 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 }
T. Wouters99b54d62019-09-12 07:05:33 -07005461 while (j < end) {
5462 b = a->a_postorder[j++];
5463 for (i = 0; i < b->b_iused; i++) {
5464 struct instr *instr = &b->b_instr[i];
5465 if (instr->i_jrel || instr->i_jabs)
5466 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005467 }
T. Wouters99b54d62019-09-12 07:05:33 -07005468 assert(a->a_nblocks < j);
5469 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005470 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005471}
5472
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005473Py_LOCAL_INLINE(void)
5474stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005476 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005477 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 assert(b->b_startdepth < 0);
5479 b->b_startdepth = depth;
5480 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005481 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005482}
5483
5484/* Find the flow path that needs the largest stack. We assume that
5485 * cycles in the flow graph have no net effect on the stack depth.
5486 */
5487static int
5488stackdepth(struct compiler *c)
5489{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005490 basicblock *b, *entryblock = NULL;
5491 basicblock **stack, **sp;
5492 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 b->b_startdepth = INT_MIN;
5495 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005496 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005497 }
5498 if (!entryblock)
5499 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005500 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5501 if (!stack) {
5502 PyErr_NoMemory();
5503 return -1;
5504 }
5505
5506 sp = stack;
5507 stackdepth_push(&sp, entryblock, 0);
5508 while (sp != stack) {
5509 b = *--sp;
5510 int depth = b->b_startdepth;
5511 assert(depth >= 0);
5512 basicblock *next = b->b_next;
5513 for (int i = 0; i < b->b_iused; i++) {
5514 struct instr *instr = &b->b_instr[i];
5515 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5516 if (effect == PY_INVALID_STACK_EFFECT) {
5517 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5518 Py_FatalError("PyCompile_OpcodeStackEffect()");
5519 }
5520 int new_depth = depth + effect;
5521 if (new_depth > maxdepth) {
5522 maxdepth = new_depth;
5523 }
5524 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5525 if (instr->i_jrel || instr->i_jabs) {
5526 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5527 assert(effect != PY_INVALID_STACK_EFFECT);
5528 int target_depth = depth + effect;
5529 if (target_depth > maxdepth) {
5530 maxdepth = target_depth;
5531 }
5532 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005533 stackdepth_push(&sp, instr->i_target, target_depth);
5534 }
5535 depth = new_depth;
5536 if (instr->i_opcode == JUMP_ABSOLUTE ||
5537 instr->i_opcode == JUMP_FORWARD ||
5538 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005539 instr->i_opcode == RAISE_VARARGS ||
5540 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005541 {
5542 /* remaining code is dead */
5543 next = NULL;
5544 break;
5545 }
5546 }
5547 if (next != NULL) {
5548 stackdepth_push(&sp, next, depth);
5549 }
5550 }
5551 PyObject_Free(stack);
5552 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005553}
5554
5555static int
5556assemble_init(struct assembler *a, int nblocks, int firstlineno)
5557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 memset(a, 0, sizeof(struct assembler));
5559 a->a_lineno = firstlineno;
5560 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5561 if (!a->a_bytecode)
5562 return 0;
5563 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5564 if (!a->a_lnotab)
5565 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005566 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 PyErr_NoMemory();
5568 return 0;
5569 }
T. Wouters99b54d62019-09-12 07:05:33 -07005570 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005572 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 PyErr_NoMemory();
5574 return 0;
5575 }
5576 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005577}
5578
5579static void
5580assemble_free(struct assembler *a)
5581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 Py_XDECREF(a->a_bytecode);
5583 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005584 if (a->a_postorder)
5585 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005586}
5587
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005588static int
5589blocksize(basicblock *b)
5590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 int i;
5592 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005595 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005597}
5598
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005599/* Appends a pair to the end of the line number table, a_lnotab, representing
5600 the instruction's bytecode offset and line number. See
5601 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005602
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005603static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005604assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005607 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005608 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005609
Serhiy Storchakaab874002016-09-11 13:48:15 +03005610 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 if(d_bytecode == 0 && d_lineno == 0)
5616 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 if (d_bytecode > 255) {
5619 int j, nbytes, ncodes = d_bytecode / 255;
5620 nbytes = a->a_lnotab_off + 2 * ncodes;
5621 len = PyBytes_GET_SIZE(a->a_lnotab);
5622 if (nbytes >= len) {
5623 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5624 len = nbytes;
5625 else if (len <= INT_MAX / 2)
5626 len *= 2;
5627 else {
5628 PyErr_NoMemory();
5629 return 0;
5630 }
5631 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5632 return 0;
5633 }
5634 lnotab = (unsigned char *)
5635 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5636 for (j = 0; j < ncodes; j++) {
5637 *lnotab++ = 255;
5638 *lnotab++ = 0;
5639 }
5640 d_bytecode -= ncodes * 255;
5641 a->a_lnotab_off += ncodes * 2;
5642 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005643 assert(0 <= d_bytecode && d_bytecode <= 255);
5644
5645 if (d_lineno < -128 || 127 < d_lineno) {
5646 int j, nbytes, ncodes, k;
5647 if (d_lineno < 0) {
5648 k = -128;
5649 /* use division on positive numbers */
5650 ncodes = (-d_lineno) / 128;
5651 }
5652 else {
5653 k = 127;
5654 ncodes = d_lineno / 127;
5655 }
5656 d_lineno -= ncodes * k;
5657 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 nbytes = a->a_lnotab_off + 2 * ncodes;
5659 len = PyBytes_GET_SIZE(a->a_lnotab);
5660 if (nbytes >= len) {
5661 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5662 len = nbytes;
5663 else if (len <= INT_MAX / 2)
5664 len *= 2;
5665 else {
5666 PyErr_NoMemory();
5667 return 0;
5668 }
5669 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5670 return 0;
5671 }
5672 lnotab = (unsigned char *)
5673 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5674 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005675 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 d_bytecode = 0;
5677 for (j = 1; j < ncodes; j++) {
5678 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005679 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 a->a_lnotab_off += ncodes * 2;
5682 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005683 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 len = PyBytes_GET_SIZE(a->a_lnotab);
5686 if (a->a_lnotab_off + 2 >= len) {
5687 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5688 return 0;
5689 }
5690 lnotab = (unsigned char *)
5691 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 a->a_lnotab_off += 2;
5694 if (d_bytecode) {
5695 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005696 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 }
5698 else { /* First line of a block; def stmt, etc. */
5699 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005700 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 }
5702 a->a_lineno = i->i_lineno;
5703 a->a_lineno_off = a->a_offset;
5704 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005705}
5706
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005707/* assemble_emit()
5708 Extend the bytecode with a new instruction.
5709 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005710*/
5711
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005712static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005713assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005714{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005717 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005718
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005719 arg = i->i_oparg;
5720 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 if (i->i_lineno && !assemble_lnotab(a, i))
5722 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005723 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 if (len > PY_SSIZE_T_MAX / 2)
5725 return 0;
5726 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5727 return 0;
5728 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005729 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005730 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005731 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005732 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005733}
5734
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005735static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005736assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005739 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 /* Compute the size of each block and fixup jump args.
5743 Replace block pointer with position in bytecode. */
5744 do {
5745 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005746 for (i = a->a_nblocks - 1; i >= 0; i--) {
5747 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 bsize = blocksize(b);
5749 b->b_offset = totsize;
5750 totsize += bsize;
5751 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005752 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5754 bsize = b->b_offset;
5755 for (i = 0; i < b->b_iused; i++) {
5756 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005757 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 /* Relative jumps are computed relative to
5759 the instruction pointer after fetching
5760 the jump instruction.
5761 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005762 bsize += isize;
5763 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005765 if (instr->i_jrel) {
5766 instr->i_oparg -= bsize;
5767 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005768 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005769 if (instrsize(instr->i_oparg) != isize) {
5770 extended_arg_recompile = 1;
5771 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 }
5774 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 /* XXX: This is an awful hack that could hurt performance, but
5777 on the bright side it should work until we come up
5778 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 The issue is that in the first loop blocksize() is called
5781 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005782 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 So we loop until we stop seeing new EXTENDED_ARGs.
5786 The only EXTENDED_ARGs that could be popping up are
5787 ones in jump instructions. So this should converge
5788 fairly quickly.
5789 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005790 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005791}
5792
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005793static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005794dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005797 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 tuple = PyTuple_New(size);
5800 if (tuple == NULL)
5801 return NULL;
5802 while (PyDict_Next(dict, &pos, &k, &v)) {
5803 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005804 Py_INCREF(k);
5805 assert((i - offset) < size);
5806 assert((i - offset) >= 0);
5807 PyTuple_SET_ITEM(tuple, i - offset, k);
5808 }
5809 return tuple;
5810}
5811
5812static PyObject *
5813consts_dict_keys_inorder(PyObject *dict)
5814{
5815 PyObject *consts, *k, *v;
5816 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5817
5818 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5819 if (consts == NULL)
5820 return NULL;
5821 while (PyDict_Next(dict, &pos, &k, &v)) {
5822 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005823 /* The keys of the dictionary can be tuples wrapping a contant.
5824 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5825 * the object we want is always second. */
5826 if (PyTuple_CheckExact(k)) {
5827 k = PyTuple_GET_ITEM(k, 1);
5828 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005830 assert(i < size);
5831 assert(i >= 0);
5832 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005834 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005835}
5836
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005837static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005838compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005841 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005843 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 if (ste->ste_nested)
5845 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005846 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005848 if (!ste->ste_generator && ste->ste_coroutine)
5849 flags |= CO_COROUTINE;
5850 if (ste->ste_generator && ste->ste_coroutine)
5851 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 if (ste->ste_varargs)
5853 flags |= CO_VARARGS;
5854 if (ste->ste_varkeywords)
5855 flags |= CO_VARKEYWORDS;
5856 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 /* (Only) inherit compilerflags in PyCF_MASK */
5859 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005860
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005861 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5862 ste->ste_coroutine &&
5863 !ste->ste_generator) {
5864 flags |= CO_COROUTINE;
5865 }
5866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005868}
5869
INADA Naokic2e16072018-11-26 21:23:22 +09005870// Merge *tuple* with constant cache.
5871// Unlike merge_consts_recursive(), this function doesn't work recursively.
5872static int
5873merge_const_tuple(struct compiler *c, PyObject **tuple)
5874{
5875 assert(PyTuple_CheckExact(*tuple));
5876
5877 PyObject *key = _PyCode_ConstantKey(*tuple);
5878 if (key == NULL) {
5879 return 0;
5880 }
5881
5882 // t is borrowed reference
5883 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5884 Py_DECREF(key);
5885 if (t == NULL) {
5886 return 0;
5887 }
5888 if (t == key) { // tuple is new constant.
5889 return 1;
5890 }
5891
5892 PyObject *u = PyTuple_GET_ITEM(t, 1);
5893 Py_INCREF(u);
5894 Py_DECREF(*tuple);
5895 *tuple = u;
5896 return 1;
5897}
5898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005899static PyCodeObject *
5900makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 PyObject *tmp;
5903 PyCodeObject *co = NULL;
5904 PyObject *consts = NULL;
5905 PyObject *names = NULL;
5906 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 PyObject *name = NULL;
5908 PyObject *freevars = NULL;
5909 PyObject *cellvars = NULL;
5910 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005911 Py_ssize_t nlocals;
5912 int nlocals_int;
5913 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005914 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005915
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005916 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 names = dict_keys_inorder(c->u->u_names, 0);
5918 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5919 if (!consts || !names || !varnames)
5920 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5923 if (!cellvars)
5924 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005925 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 if (!freevars)
5927 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005928
INADA Naokic2e16072018-11-26 21:23:22 +09005929 if (!merge_const_tuple(c, &names) ||
5930 !merge_const_tuple(c, &varnames) ||
5931 !merge_const_tuple(c, &cellvars) ||
5932 !merge_const_tuple(c, &freevars))
5933 {
5934 goto error;
5935 }
5936
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005937 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005938 assert(nlocals < INT_MAX);
5939 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 flags = compute_code_flags(c);
5942 if (flags < 0)
5943 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5946 if (!bytecode)
5947 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5950 if (!tmp)
5951 goto error;
5952 Py_DECREF(consts);
5953 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005954 if (!merge_const_tuple(c, &consts)) {
5955 goto error;
5956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005958 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005959 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005960 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005961 maxdepth = stackdepth(c);
5962 if (maxdepth < 0) {
5963 goto error;
5964 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005965 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
5966 posonlyargcount, kwonlyargcount, nlocals_int,
5967 maxdepth, flags, bytecode, consts, names,
5968 varnames, freevars, cellvars, c->c_filename,
5969 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005970 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 Py_XDECREF(consts);
5972 Py_XDECREF(names);
5973 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 Py_XDECREF(name);
5975 Py_XDECREF(freevars);
5976 Py_XDECREF(cellvars);
5977 Py_XDECREF(bytecode);
5978 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005979}
5980
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005981
5982/* For debugging purposes only */
5983#if 0
5984static void
5985dump_instr(const struct instr *i)
5986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 const char *jrel = i->i_jrel ? "jrel " : "";
5988 const char *jabs = i->i_jabs ? "jabs " : "";
5989 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005991 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005992 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5996 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005997}
5998
5999static void
6000dump_basicblock(const basicblock *b)
6001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 const char *seen = b->b_seen ? "seen " : "";
6003 const char *b_return = b->b_return ? "return " : "";
6004 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6005 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6006 if (b->b_instr) {
6007 int i;
6008 for (i = 0; i < b->b_iused; i++) {
6009 fprintf(stderr, " [%02d] ", i);
6010 dump_instr(b->b_instr + i);
6011 }
6012 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006013}
6014#endif
6015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006016static PyCodeObject *
6017assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 basicblock *b, *entryblock;
6020 struct assembler a;
6021 int i, j, nblocks;
6022 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006024 /* Make sure every block that falls off the end returns None.
6025 XXX NEXT_BLOCK() isn't quite right, because if the last
6026 block ends with a jump or return b_next shouldn't set.
6027 */
6028 if (!c->u->u_curblock->b_return) {
6029 NEXT_BLOCK(c);
6030 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006031 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006032 ADDOP(c, RETURN_VALUE);
6033 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006035 nblocks = 0;
6036 entryblock = NULL;
6037 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6038 nblocks++;
6039 entryblock = b;
6040 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 /* Set firstlineno if it wasn't explicitly set. */
6043 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006044 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6046 else
6047 c->u->u_firstlineno = 1;
6048 }
6049 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6050 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006051 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006053 /* Can't modify the bytecode after computing jump offsets. */
6054 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006055
T. Wouters99b54d62019-09-12 07:05:33 -07006056 /* Emit code in reverse postorder from dfs. */
6057 for (i = a.a_nblocks - 1; i >= 0; i--) {
6058 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006059 for (j = 0; j < b->b_iused; j++)
6060 if (!assemble_emit(&a, &b->b_instr[j]))
6061 goto error;
6062 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6065 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006066 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006067 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006069 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006070 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006071 assemble_free(&a);
6072 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006073}
Georg Brandl8334fd92010-12-04 10:26:46 +00006074
6075#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006076PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006077PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6078 PyArena *arena)
6079{
6080 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6081}