blob: bf8c8109d0758381750a9ffd698f89a63375dbcb [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
Mark Shannonfee55262019-11-21 09:11:43 +000084enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
85 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086
87struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 enum fblocktype fb_type;
89 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020090 /* (optional) type-specific exit or cleanup block */
91 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000092 /* (optional) additional information required for unwinding */
93 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094};
95
Antoine Pitrou86a36b52011-11-25 18:56:07 +010096enum {
97 COMPILER_SCOPE_MODULE,
98 COMPILER_SCOPE_CLASS,
99 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400100 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400101 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100102 COMPILER_SCOPE_COMPREHENSION,
103};
104
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105/* The following items change on entry and exit of code blocks.
106 They must be saved and restored when returning to a block.
107*/
108struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400112 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 int u_scope_type;
114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 /* The following fields are dicts that map objects to
116 the index of them in co_XXX. The index is used as
117 the argument for opcodes that refer to those collections.
118 */
119 PyObject *u_consts; /* all constants */
120 PyObject *u_names; /* all names */
121 PyObject *u_varnames; /* local variables */
122 PyObject *u_cellvars; /* cell variables */
123 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126
Victor Stinnerf8e32212013-11-19 23:56:34 +0100127 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100128 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100129 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 /* Pointer to the most recently allocated block. By following b_list
131 members, you can reach all early allocated blocks. */
132 basicblock *u_blocks;
133 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_nfblocks;
136 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_firstlineno; /* the first lineno of the block */
139 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000140 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_lineno_set; /* boolean to indicate whether instr
142 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143};
144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000150
151Note that we don't track recursion levels during compilation - the
152task of detecting and rejecting excessive levels of nesting is
153handled by the symbol analysis pass.
154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155*/
156
157struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200158 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 struct symtable *c_st;
160 PyFutureFeatures *c_future; /* pointer to module's __future__ */
161 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
Georg Brandl8334fd92010-12-04 10:26:46 +0000163 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 int c_interactive; /* true if in interactive mode */
165 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100166 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
167 if this value is different from zero.
168 This can be used to temporarily visit
169 nodes without emitting bytecode to
170 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
INADA Naokic2e16072018-11-26 21:23:22 +0900172 PyObject *c_const_cache; /* Python dict holding all constants,
173 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 struct compiler_unit *u; /* compiler state for current block */
175 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
176 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177};
178
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100179static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static void compiler_free(struct compiler *);
181static basicblock *compiler_new_block(struct compiler *);
182static int compiler_next_instr(struct compiler *, basicblock *);
183static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100184static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200187static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
189
190static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
191static int compiler_visit_stmt(struct compiler *, stmt_ty);
192static int compiler_visit_keyword(struct compiler *, keyword_ty);
193static int compiler_visit_expr(struct compiler *, expr_ty);
194static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700195static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199static int inplace_binop(struct compiler *, operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800200static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200201static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500203static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400204static int compiler_async_with(struct compiler *, stmt_ty, int);
205static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100206static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400208 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500209static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400210static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000211
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700212static int compiler_sync_comprehension_generator(
213 struct compiler *c,
214 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200215 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700216 expr_ty elt, expr_ty val, int type);
217
218static int compiler_async_comprehension_generator(
219 struct compiler *c,
220 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200221 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700222 expr_ty elt, expr_ty val, int type);
223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000225static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400227#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 /* Name mangling: __private becomes _classname__private.
233 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 PyObject *result;
235 size_t nlen, plen, ipriv;
236 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 PyUnicode_READ_CHAR(ident, 0) != '_' ||
239 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 Py_INCREF(ident);
241 return ident;
242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 nlen = PyUnicode_GET_LENGTH(ident);
244 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 The only time a name with a dot can occur is when
248 we are compiling an import statement that has a
249 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 TODO(jhylton): Decide whether we want to support
252 mangling of the module name, e.g. __M.X.
253 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200254 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
255 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
256 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 Py_INCREF(ident);
258 return ident; /* Don't mangle __whatever__ */
259 }
260 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200261 ipriv = 0;
262 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
263 ipriv++;
264 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 Py_INCREF(ident);
266 return ident; /* Don't mangle if class is just underscores */
267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000269
Antoine Pitrou55bff892013-04-06 21:21:04 +0200270 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
271 PyErr_SetString(PyExc_OverflowError,
272 "private identifier too large to be mangled");
273 return NULL;
274 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
277 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
278 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
279
280 result = PyUnicode_New(1 + nlen + plen, maxchar);
281 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200283 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
284 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200285 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
286 Py_DECREF(result);
287 return NULL;
288 }
289 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
290 Py_DECREF(result);
291 return NULL;
292 }
Victor Stinner8f825062012-04-27 13:55:39 +0200293 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200294 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000295}
296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297static int
298compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000301
INADA Naokic2e16072018-11-26 21:23:22 +0900302 c->c_const_cache = PyDict_New();
303 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900305 }
306
307 c->c_stack = PyList_New(0);
308 if (!c->c_stack) {
309 Py_CLEAR(c->c_const_cache);
310 return 0;
311 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314}
315
316PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200317PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
318 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 struct compiler c;
321 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200322 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200324 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!__doc__) {
327 __doc__ = PyUnicode_InternFromString("__doc__");
328 if (!__doc__)
329 return NULL;
330 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000331 if (!__annotations__) {
332 __annotations__ = PyUnicode_InternFromString("__annotations__");
333 if (!__annotations__)
334 return NULL;
335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (!compiler_init(&c))
337 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 c.c_filename = filename;
340 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200341 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (c.c_future == NULL)
343 goto finally;
344 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 flags = &local_flags;
346 }
347 merged = c.c_future->ff_features | flags->cf_flags;
348 c.c_future->ff_features = merged;
349 flags->cf_flags = merged;
350 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200351 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100353 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200355 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900356 goto finally;
357 }
358
Victor Stinner14e461d2013-08-26 22:28:21 +0200359 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (c.c_st == NULL) {
361 if (!PyErr_Occurred())
362 PyErr_SetString(PyExc_SystemError, "no symtable");
363 goto finally;
364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Thomas Wouters1175c432006-02-27 22:49:54 +0000368 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 compiler_free(&c);
370 assert(co || PyErr_Occurred());
371 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372}
373
374PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200375PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
376 int optimize, PyArena *arena)
377{
378 PyObject *filename;
379 PyCodeObject *co;
380 filename = PyUnicode_DecodeFSDefault(filename_str);
381 if (filename == NULL)
382 return NULL;
383 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
384 Py_DECREF(filename);
385 return co;
386
387}
388
389PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390PyNode_Compile(struct _node *n, const char *filename)
391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyCodeObject *co = NULL;
393 mod_ty mod;
394 PyArena *arena = PyArena_New();
395 if (!arena)
396 return NULL;
397 mod = PyAST_FromNode(n, NULL, filename, arena);
398 if (mod)
399 co = PyAST_Compile(mod, filename, NULL, arena);
400 PyArena_Free(arena);
401 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000402}
403
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000404static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (c->c_st)
408 PySymtable_Free(c->c_st);
409 if (c->c_future)
410 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200411 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900412 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000414}
415
Guido van Rossum79f25d91997-04-29 20:08:16 +0000416static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_ssize_t i, n;
420 PyObject *v, *k;
421 PyObject *dict = PyDict_New();
422 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 n = PyList_Size(list);
425 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100426 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (!v) {
428 Py_DECREF(dict);
429 return NULL;
430 }
431 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300432 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_DECREF(v);
434 Py_DECREF(dict);
435 return NULL;
436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_DECREF(v);
438 }
439 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000440}
441
442/* Return new dict containing names from src that match scope(s).
443
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000446values are integers, starting at offset and increasing by one for
447each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448*/
449
450static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100451dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700453 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500455 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(offset >= 0);
458 if (dest == NULL)
459 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Meador Inge2ca63152012-07-18 14:20:11 -0500461 /* Sort the keys so that we have a deterministic order on the indexes
462 saved in the returned dictionary. These indexes are used as indexes
463 into the free and cell var storage. Therefore if they aren't
464 deterministic, then the generated bytecode is not deterministic.
465 */
466 sorted_keys = PyDict_Keys(src);
467 if (sorted_keys == NULL)
468 return NULL;
469 if (PyList_Sort(sorted_keys) != 0) {
470 Py_DECREF(sorted_keys);
471 return NULL;
472 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500473 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500474
475 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* XXX this should probably be a macro in symtable.h */
477 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500478 k = PyList_GET_ITEM(sorted_keys, key_i);
479 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 assert(PyLong_Check(v));
481 vi = PyLong_AS_LONG(v);
482 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300485 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500487 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_DECREF(dest);
489 return NULL;
490 }
491 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300492 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500493 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 Py_DECREF(item);
495 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return NULL;
497 }
498 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 }
500 }
Meador Inge2ca63152012-07-18 14:20:11 -0500501 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000503}
504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505static void
506compiler_unit_check(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *block;
509 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700510 assert((uintptr_t)block != 0xcbcbcbcbU);
511 assert((uintptr_t)block != 0xfbfbfbfbU);
512 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (block->b_instr != NULL) {
514 assert(block->b_ialloc > 0);
515 assert(block->b_iused > 0);
516 assert(block->b_ialloc >= block->b_iused);
517 }
518 else {
519 assert (block->b_iused == 0);
520 assert (block->b_ialloc == 0);
521 }
522 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523}
524
525static void
526compiler_unit_free(struct compiler_unit *u)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 compiler_unit_check(u);
531 b = u->u_blocks;
532 while (b != NULL) {
533 if (b->b_instr)
534 PyObject_Free((void *)b->b_instr);
535 next = b->b_list;
536 PyObject_Free((void *)b);
537 b = next;
538 }
539 Py_CLEAR(u->u_ste);
540 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400541 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 Py_CLEAR(u->u_consts);
543 Py_CLEAR(u->u_names);
544 Py_CLEAR(u->u_varnames);
545 Py_CLEAR(u->u_freevars);
546 Py_CLEAR(u->u_cellvars);
547 Py_CLEAR(u->u_private);
548 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000549}
550
551static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100552compiler_enter_scope(struct compiler *c, identifier name,
553 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100556 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
559 struct compiler_unit));
560 if (!u) {
561 PyErr_NoMemory();
562 return 0;
563 }
564 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100565 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100567 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 u->u_kwonlyargcount = 0;
569 u->u_ste = PySymtable_Lookup(c->c_st, key);
570 if (!u->u_ste) {
571 compiler_unit_free(u);
572 return 0;
573 }
574 Py_INCREF(name);
575 u->u_name = name;
576 u->u_varnames = list2dict(u->u_ste->ste_varnames);
577 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
578 if (!u->u_varnames || !u->u_cellvars) {
579 compiler_unit_free(u);
580 return 0;
581 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000583 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300585 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500586 int res;
587 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200588 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500589 name = _PyUnicode_FromId(&PyId___class__);
590 if (!name) {
591 compiler_unit_free(u);
592 return 0;
593 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300594 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500595 if (res < 0) {
596 compiler_unit_free(u);
597 return 0;
598 }
599 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200602 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (!u->u_freevars) {
604 compiler_unit_free(u);
605 return 0;
606 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 u->u_blocks = NULL;
609 u->u_nfblocks = 0;
610 u->u_firstlineno = lineno;
611 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000612 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 u->u_lineno_set = 0;
614 u->u_consts = PyDict_New();
615 if (!u->u_consts) {
616 compiler_unit_free(u);
617 return 0;
618 }
619 u->u_names = PyDict_New();
620 if (!u->u_names) {
621 compiler_unit_free(u);
622 return 0;
623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* Push the old compiler_unit on the stack. */
628 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400629 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
631 Py_XDECREF(capsule);
632 compiler_unit_free(u);
633 return 0;
634 }
635 Py_DECREF(capsule);
636 u->u_private = c->u->u_private;
637 Py_XINCREF(u->u_private);
638 }
639 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100642
643 block = compiler_new_block(c);
644 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100646 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400648 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
649 if (!compiler_set_qualname(c))
650 return 0;
651 }
652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000654}
655
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000656static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657compiler_exit_scope(struct compiler *c)
658{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100659 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 c->c_nestlevel--;
663 compiler_unit_free(c->u);
664 /* Restore c->u to the parent unit. */
665 n = PyList_GET_SIZE(c->c_stack) - 1;
666 if (n >= 0) {
667 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400668 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 assert(c->u);
670 /* we are deleting from a list so this really shouldn't fail */
671 if (PySequence_DelItem(c->c_stack, n) < 0)
672 Py_FatalError("compiler_exit_scope()");
673 compiler_unit_check(c->u);
674 }
675 else
676 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000678}
679
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400680static int
681compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100682{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 _Py_static_string(dot_locals, ".<locals>");
685 Py_ssize_t stack_size;
686 struct compiler_unit *u = c->u;
687 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100690 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400691 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400692 if (stack_size > 1) {
693 int scope, force_global = 0;
694 struct compiler_unit *parent;
695 PyObject *mangled, *capsule;
696
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400697 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400698 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 assert(parent);
700
Yury Selivanov75445082015-05-11 22:57:16 -0400701 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
702 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
703 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 assert(u->u_name);
705 mangled = _Py_Mangle(parent->u_private, u->u_name);
706 if (!mangled)
707 return 0;
708 scope = PyST_GetScope(parent->u_ste, mangled);
709 Py_DECREF(mangled);
710 assert(scope != GLOBAL_IMPLICIT);
711 if (scope == GLOBAL_EXPLICIT)
712 force_global = 1;
713 }
714
715 if (!force_global) {
716 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400717 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
719 dot_locals_str = _PyUnicode_FromId(&dot_locals);
720 if (dot_locals_str == NULL)
721 return 0;
722 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
723 if (base == NULL)
724 return 0;
725 }
726 else {
727 Py_INCREF(parent->u_qualname);
728 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400729 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730 }
731 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400732
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400733 if (base != NULL) {
734 dot_str = _PyUnicode_FromId(&dot);
735 if (dot_str == NULL) {
736 Py_DECREF(base);
737 return 0;
738 }
739 name = PyUnicode_Concat(base, dot_str);
740 Py_DECREF(base);
741 if (name == NULL)
742 return 0;
743 PyUnicode_Append(&name, u->u_name);
744 if (name == NULL)
745 return 0;
746 }
747 else {
748 Py_INCREF(u->u_name);
749 name = u->u_name;
750 }
751 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100752
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400753 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100754}
755
Eric V. Smith235a6f02015-09-19 14:51:32 -0400756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757/* Allocate a new block and return a pointer to it.
758 Returns NULL on error.
759*/
760
761static basicblock *
762compiler_new_block(struct compiler *c)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 basicblock *b;
765 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 u = c->u;
768 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
769 if (b == NULL) {
770 PyErr_NoMemory();
771 return NULL;
772 }
773 memset((void *)b, 0, sizeof(basicblock));
774 /* Extend the singly linked list of blocks with new block. */
775 b->b_list = u->u_blocks;
776 u->u_blocks = b;
777 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778}
779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781compiler_next_block(struct compiler *c)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 basicblock *block = compiler_new_block(c);
784 if (block == NULL)
785 return NULL;
786 c->u->u_curblock->b_next = block;
787 c->u->u_curblock = block;
788 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789}
790
791static basicblock *
792compiler_use_next_block(struct compiler *c, basicblock *block)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(block != NULL);
795 c->u->u_curblock->b_next = block;
796 c->u->u_curblock = block;
797 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798}
799
800/* Returns the offset of the next instruction in the current block's
801 b_instr array. Resizes the b_instr as necessary.
802 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000803*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804
805static int
806compiler_next_instr(struct compiler *c, basicblock *b)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(b != NULL);
809 if (b->b_instr == NULL) {
810 b->b_instr = (struct instr *)PyObject_Malloc(
811 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
812 if (b->b_instr == NULL) {
813 PyErr_NoMemory();
814 return -1;
815 }
816 b->b_ialloc = DEFAULT_BLOCK_SIZE;
817 memset((char *)b->b_instr, 0,
818 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
819 }
820 else if (b->b_iused == b->b_ialloc) {
821 struct instr *tmp;
822 size_t oldsize, newsize;
823 oldsize = b->b_ialloc * sizeof(struct instr);
824 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000825
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700826 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyErr_NoMemory();
828 return -1;
829 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (newsize == 0) {
832 PyErr_NoMemory();
833 return -1;
834 }
835 b->b_ialloc <<= 1;
836 tmp = (struct instr *)PyObject_Realloc(
837 (void *)b->b_instr, newsize);
838 if (tmp == NULL) {
839 PyErr_NoMemory();
840 return -1;
841 }
842 b->b_instr = tmp;
843 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
844 }
845 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000846}
847
Christian Heimes2202f872008-02-06 14:31:34 +0000848/* Set the i_lineno member of the instruction at offset off if the
849 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850 already been set. If it has been set, the call has no effect.
851
Christian Heimes2202f872008-02-06 14:31:34 +0000852 The line number is reset in the following cases:
853 - when entering a new scope
854 - on each statement
855 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200856 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000857 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000858*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000860static void
861compiler_set_lineno(struct compiler *c, int off)
862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 basicblock *b;
864 if (c->u->u_lineno_set)
865 return;
866 c->u->u_lineno_set = 1;
867 b = c->u->u_curblock;
868 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869}
870
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200871/* Return the stack effect of opcode with argument oparg.
872
873 Some opcodes have different stack effect when jump to the target and
874 when not jump. The 'jump' parameter specifies the case:
875
876 * 0 -- when not jump
877 * 1 -- when jump
878 * -1 -- maximal
879 */
880/* XXX Make the stack effect of WITH_CLEANUP_START and
881 WITH_CLEANUP_FINISH deterministic. */
882static int
883stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300886 case NOP:
887 case EXTENDED_ARG:
888 return 0;
889
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200890 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case POP_TOP:
892 return -1;
893 case ROT_TWO:
894 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200895 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 return 0;
897 case DUP_TOP:
898 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000899 case DUP_TOP_TWO:
900 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200902 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case UNARY_POSITIVE:
904 case UNARY_NEGATIVE:
905 case UNARY_NOT:
906 case UNARY_INVERT:
907 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 case SET_ADD:
910 case LIST_APPEND:
911 return -1;
912 case MAP_ADD:
913 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000914
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200915 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case BINARY_POWER:
917 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400918 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case BINARY_MODULO:
920 case BINARY_ADD:
921 case BINARY_SUBTRACT:
922 case BINARY_SUBSCR:
923 case BINARY_FLOOR_DIVIDE:
924 case BINARY_TRUE_DIVIDE:
925 return -1;
926 case INPLACE_FLOOR_DIVIDE:
927 case INPLACE_TRUE_DIVIDE:
928 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 case INPLACE_ADD:
931 case INPLACE_SUBTRACT:
932 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400933 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case INPLACE_MODULO:
935 return -1;
936 case STORE_SUBSCR:
937 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case DELETE_SUBSCR:
939 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case BINARY_LSHIFT:
942 case BINARY_RSHIFT:
943 case BINARY_AND:
944 case BINARY_XOR:
945 case BINARY_OR:
946 return -1;
947 case INPLACE_POWER:
948 return -1;
949 case GET_ITER:
950 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case PRINT_EXPR:
953 return -1;
954 case LOAD_BUILD_CLASS:
955 return 1;
956 case INPLACE_LSHIFT:
957 case INPLACE_RSHIFT:
958 case INPLACE_AND:
959 case INPLACE_XOR:
960 case INPLACE_OR:
961 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 /* 1 in the normal flow.
965 * Restore the stack position and push 6 values before jumping to
966 * the handler if an exception be raised. */
967 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case RETURN_VALUE:
969 return -1;
970 case IMPORT_STAR:
971 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700972 case SETUP_ANNOTATIONS:
973 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 case YIELD_VALUE:
975 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500976 case YIELD_FROM:
977 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case POP_BLOCK:
979 return 0;
980 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200981 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 case STORE_NAME:
984 return -1;
985 case DELETE_NAME:
986 return 0;
987 case UNPACK_SEQUENCE:
988 return oparg-1;
989 case UNPACK_EX:
990 return (oparg&0xFF) + (oparg>>8);
991 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200992 /* -1 at end of iterator, 1 if continue iterating. */
993 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case STORE_ATTR:
996 return -2;
997 case DELETE_ATTR:
998 return -1;
999 case STORE_GLOBAL:
1000 return -1;
1001 case DELETE_GLOBAL:
1002 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case LOAD_CONST:
1004 return 1;
1005 case LOAD_NAME:
1006 return 1;
1007 case BUILD_TUPLE:
1008 case BUILD_LIST:
1009 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001010 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return 1-oparg;
1012 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001013 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001014 case BUILD_CONST_KEY_MAP:
1015 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case LOAD_ATTR:
1017 return 0;
1018 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001019 case IS_OP:
1020 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001022 case JUMP_IF_NOT_EXC_MATCH:
1023 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 case IMPORT_NAME:
1025 return -1;
1026 case IMPORT_FROM:
1027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001029 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_ABSOLUTE:
1032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001034 case JUMP_IF_TRUE_OR_POP:
1035 case JUMP_IF_FALSE_OR_POP:
1036 return jump ? 0 : -1;
1037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case POP_JUMP_IF_FALSE:
1039 case POP_JUMP_IF_TRUE:
1040 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_GLOBAL:
1043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001045 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001047 /* 0 in the normal flow.
1048 * Restore the stack position and push 6 values before jumping to
1049 * the handler if an exception be raised. */
1050 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001051 case RERAISE:
1052 return -3;
1053
1054 case WITH_EXCEPT_START:
1055 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case LOAD_FAST:
1058 return 1;
1059 case STORE_FAST:
1060 return -1;
1061 case DELETE_FAST:
1062 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case RAISE_VARARGS:
1065 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066
1067 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001069 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001070 case CALL_METHOD:
1071 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001073 return -oparg-1;
1074 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001075 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001076 case MAKE_FUNCTION:
1077 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1078 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 case BUILD_SLICE:
1080 if (oparg == 3)
1081 return -2;
1082 else
1083 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001084
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 case LOAD_CLOSURE:
1087 return 1;
1088 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001089 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return 1;
1091 case STORE_DEREF:
1092 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001093 case DELETE_DEREF:
1094 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001095
1096 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001097 case GET_AWAITABLE:
1098 return 0;
1099 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100 /* 0 in the normal flow.
1101 * Restore the stack position to the position before the result
1102 * of __aenter__ and push 6 values before jumping to the handler
1103 * if an exception be raised. */
1104 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001105 case BEFORE_ASYNC_WITH:
1106 return 1;
1107 case GET_AITER:
1108 return 0;
1109 case GET_ANEXT:
1110 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001111 case GET_YIELD_FROM_ITER:
1112 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001113 case END_ASYNC_FOR:
1114 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001115 case FORMAT_VALUE:
1116 /* If there's a fmt_spec on the stack, we go from 2->1,
1117 else 1->1. */
1118 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001119 case LOAD_METHOD:
1120 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001121 case LOAD_ASSERTION_ERROR:
1122 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001123 case LIST_TO_TUPLE:
1124 return 0;
1125 case LIST_EXTEND:
1126 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001127 case DICT_MERGE:
1128 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001129 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001131 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
Larry Hastings3a907972013-11-23 14:49:22 -08001133 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134}
1135
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001136int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001137PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1138{
1139 return stack_effect(opcode, oparg, jump);
1140}
1141
1142int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001143PyCompile_OpcodeStackEffect(int opcode, int oparg)
1144{
1145 return stack_effect(opcode, oparg, -1);
1146}
1147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148/* Add an opcode with no argument.
1149 Returns 0 on failure, 1 on success.
1150*/
1151
1152static int
1153compiler_addop(struct compiler *c, int opcode)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 basicblock *b;
1156 struct instr *i;
1157 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001158 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001159 if (c->c_do_not_emit_bytecode) {
1160 return 1;
1161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 off = compiler_next_instr(c, c->u->u_curblock);
1163 if (off < 0)
1164 return 0;
1165 b = c->u->u_curblock;
1166 i = &b->b_instr[off];
1167 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001168 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (opcode == RETURN_VALUE)
1170 b->b_return = 1;
1171 compiler_set_lineno(c, off);
1172 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173}
1174
Victor Stinnerf8e32212013-11-19 23:56:34 +01001175static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1177{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001178 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001183 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001185 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001186 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001187 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return -1;
1190 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001191 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_DECREF(v);
1193 return -1;
1194 }
1195 Py_DECREF(v);
1196 }
1197 else
1198 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001199 return arg;
1200}
1201
INADA Naokic2e16072018-11-26 21:23:22 +09001202// Merge const *o* recursively and return constant key object.
1203static PyObject*
1204merge_consts_recursive(struct compiler *c, PyObject *o)
1205{
1206 // None and Ellipsis are singleton, and key is the singleton.
1207 // No need to merge object and key.
1208 if (o == Py_None || o == Py_Ellipsis) {
1209 Py_INCREF(o);
1210 return o;
1211 }
1212
1213 PyObject *key = _PyCode_ConstantKey(o);
1214 if (key == NULL) {
1215 return NULL;
1216 }
1217
1218 // t is borrowed reference
1219 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1220 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001221 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001222 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001223 Py_DECREF(key);
1224 return t;
1225 }
1226
INADA Naokif7e4d362018-11-29 00:58:46 +09001227 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001228 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001230 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 Py_ssize_t len = PyTuple_GET_SIZE(o);
1232 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001233 PyObject *item = PyTuple_GET_ITEM(o, i);
1234 PyObject *u = merge_consts_recursive(c, item);
1235 if (u == NULL) {
1236 Py_DECREF(key);
1237 return NULL;
1238 }
1239
1240 // See _PyCode_ConstantKey()
1241 PyObject *v; // borrowed
1242 if (PyTuple_CheckExact(u)) {
1243 v = PyTuple_GET_ITEM(u, 1);
1244 }
1245 else {
1246 v = u;
1247 }
1248 if (v != item) {
1249 Py_INCREF(v);
1250 PyTuple_SET_ITEM(o, i, v);
1251 Py_DECREF(item);
1252 }
1253
1254 Py_DECREF(u);
1255 }
1256 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001257 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001258 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001259 // constant keys.
1260 // See _PyCode_ConstantKey() for detail.
1261 assert(PyTuple_CheckExact(key));
1262 assert(PyTuple_GET_SIZE(key) == 2);
1263
1264 Py_ssize_t len = PySet_GET_SIZE(o);
1265 if (len == 0) { // empty frozenset should not be re-created.
1266 return key;
1267 }
1268 PyObject *tuple = PyTuple_New(len);
1269 if (tuple == NULL) {
1270 Py_DECREF(key);
1271 return NULL;
1272 }
1273 Py_ssize_t i = 0, pos = 0;
1274 PyObject *item;
1275 Py_hash_t hash;
1276 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1277 PyObject *k = merge_consts_recursive(c, item);
1278 if (k == NULL) {
1279 Py_DECREF(tuple);
1280 Py_DECREF(key);
1281 return NULL;
1282 }
1283 PyObject *u;
1284 if (PyTuple_CheckExact(k)) {
1285 u = PyTuple_GET_ITEM(k, 1);
1286 Py_INCREF(u);
1287 Py_DECREF(k);
1288 }
1289 else {
1290 u = k;
1291 }
1292 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1293 i++;
1294 }
1295
1296 // Instead of rewriting o, we create new frozenset and embed in the
1297 // key tuple. Caller should get merged frozenset from the key tuple.
1298 PyObject *new = PyFrozenSet_New(tuple);
1299 Py_DECREF(tuple);
1300 if (new == NULL) {
1301 Py_DECREF(key);
1302 return NULL;
1303 }
1304 assert(PyTuple_GET_ITEM(key, 1) == o);
1305 Py_DECREF(o);
1306 PyTuple_SET_ITEM(key, 1, new);
1307 }
INADA Naokic2e16072018-11-26 21:23:22 +09001308
1309 return key;
1310}
1311
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001312static Py_ssize_t
1313compiler_add_const(struct compiler *c, PyObject *o)
1314{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001315 if (c->c_do_not_emit_bytecode) {
1316 return 0;
1317 }
1318
INADA Naokic2e16072018-11-26 21:23:22 +09001319 PyObject *key = merge_consts_recursive(c, o);
1320 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001321 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001322 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001323
INADA Naokic2e16072018-11-26 21:23:22 +09001324 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1325 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327}
1328
1329static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001330compiler_addop_load_const(struct compiler *c, PyObject *o)
1331{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001332 if (c->c_do_not_emit_bytecode) {
1333 return 1;
1334 }
1335
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001336 Py_ssize_t arg = compiler_add_const(c, o);
1337 if (arg < 0)
1338 return 0;
1339 return compiler_addop_i(c, LOAD_CONST, arg);
1340}
1341
1342static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001346 if (c->c_do_not_emit_bytecode) {
1347 return 1;
1348 }
1349
Victor Stinnerad9a0662013-11-19 22:23:20 +01001350 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353 return compiler_addop_i(c, opcode, arg);
1354}
1355
1356static int
1357compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001360 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001361
1362 if (c->c_do_not_emit_bytecode) {
1363 return 1;
1364 }
1365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1367 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001368 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 arg = compiler_add_o(c, dict, mangled);
1370 Py_DECREF(mangled);
1371 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001372 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 return compiler_addop_i(c, opcode, arg);
1374}
1375
1376/* Add an opcode with an integer argument.
1377 Returns 0 on failure, 1 on success.
1378*/
1379
1380static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001381compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 struct instr *i;
1384 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001385
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001386 if (c->c_do_not_emit_bytecode) {
1387 return 1;
1388 }
1389
Victor Stinner2ad474b2016-03-01 23:34:47 +01001390 /* oparg value is unsigned, but a signed C int is usually used to store
1391 it in the C code (like Python/ceval.c).
1392
1393 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1394
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001395 The argument of a concrete bytecode instruction is limited to 8-bit.
1396 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1397 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001398 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 off = compiler_next_instr(c, c->u->u_curblock);
1401 if (off < 0)
1402 return 0;
1403 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001404 i->i_opcode = opcode;
1405 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 compiler_set_lineno(c, off);
1407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408}
1409
1410static int
1411compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 struct instr *i;
1414 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001416 if (c->c_do_not_emit_bytecode) {
1417 return 1;
1418 }
1419
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001420 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 assert(b != NULL);
1422 off = compiler_next_instr(c, c->u->u_curblock);
1423 if (off < 0)
1424 return 0;
1425 i = &c->u->u_curblock->b_instr[off];
1426 i->i_opcode = opcode;
1427 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (absolute)
1429 i->i_jabs = 1;
1430 else
1431 i->i_jrel = 1;
1432 compiler_set_lineno(c, off);
1433 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434}
1435
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001436/* NEXT_BLOCK() creates an implicit jump from the current block
1437 to the new block.
1438
1439 The returns inside this macro make it impossible to decref objects
1440 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (compiler_next_block((C)) == NULL) \
1444 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
1447#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (!compiler_addop((C), (OP))) \
1449 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450}
1451
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001452#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (!compiler_addop((C), (OP))) { \
1454 compiler_exit_scope(c); \
1455 return 0; \
1456 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001457}
1458
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001459#define ADDOP_LOAD_CONST(C, O) { \
1460 if (!compiler_addop_load_const((C), (O))) \
1461 return 0; \
1462}
1463
1464/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1465#define ADDOP_LOAD_CONST_NEW(C, O) { \
1466 PyObject *__new_const = (O); \
1467 if (__new_const == NULL) { \
1468 return 0; \
1469 } \
1470 if (!compiler_addop_load_const((C), __new_const)) { \
1471 Py_DECREF(__new_const); \
1472 return 0; \
1473 } \
1474 Py_DECREF(__new_const); \
1475}
1476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1479 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480}
1481
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001482/* Same as ADDOP_O, but steals a reference. */
1483#define ADDOP_N(C, OP, O, TYPE) { \
1484 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1485 Py_DECREF((O)); \
1486 return 0; \
1487 } \
1488 Py_DECREF((O)); \
1489}
1490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1493 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494}
1495
1496#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (!compiler_addop_i((C), (OP), (O))) \
1498 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499}
1500
1501#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (!compiler_addop_j((C), (OP), (O), 1)) \
1503 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504}
1505
1506#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (!compiler_addop_j((C), (OP), (O), 0)) \
1508 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509}
1510
Mark Shannon9af0e472020-01-14 10:12:45 +00001511
1512#define ADDOP_COMPARE(C, CMP) { \
1513 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1514 return 0; \
1515}
1516
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1518 the ASDL name to synthesize the name of the C type and the visit function.
1519*/
1520
1521#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_visit_ ## TYPE((C), (V))) \
1523 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001526#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (!compiler_visit_ ## TYPE((C), (V))) { \
1528 compiler_exit_scope(c); \
1529 return 0; \
1530 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001531}
1532
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (!compiler_visit_slice((C), (V), (CTX))) \
1535 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536}
1537
1538#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 int _i; \
1540 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1541 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1542 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1543 if (!compiler_visit_ ## TYPE((C), elt)) \
1544 return 0; \
1545 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546}
1547
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001548#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 int _i; \
1550 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1551 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1552 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1553 if (!compiler_visit_ ## TYPE((C), elt)) { \
1554 compiler_exit_scope(c); \
1555 return 0; \
1556 } \
1557 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001558}
1559
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001560/* These macros allows to check only for errors and not emmit bytecode
1561 * while visiting nodes.
1562*/
1563
1564#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1565 c->c_do_not_emit_bytecode++;
1566
1567#define END_DO_NOT_EMIT_BYTECODE \
1568 c->c_do_not_emit_bytecode--; \
1569}
1570
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001571/* Search if variable annotations are present statically in a block. */
1572
1573static int
1574find_ann(asdl_seq *stmts)
1575{
1576 int i, j, res = 0;
1577 stmt_ty st;
1578
1579 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1580 st = (stmt_ty)asdl_seq_GET(stmts, i);
1581 switch (st->kind) {
1582 case AnnAssign_kind:
1583 return 1;
1584 case For_kind:
1585 res = find_ann(st->v.For.body) ||
1586 find_ann(st->v.For.orelse);
1587 break;
1588 case AsyncFor_kind:
1589 res = find_ann(st->v.AsyncFor.body) ||
1590 find_ann(st->v.AsyncFor.orelse);
1591 break;
1592 case While_kind:
1593 res = find_ann(st->v.While.body) ||
1594 find_ann(st->v.While.orelse);
1595 break;
1596 case If_kind:
1597 res = find_ann(st->v.If.body) ||
1598 find_ann(st->v.If.orelse);
1599 break;
1600 case With_kind:
1601 res = find_ann(st->v.With.body);
1602 break;
1603 case AsyncWith_kind:
1604 res = find_ann(st->v.AsyncWith.body);
1605 break;
1606 case Try_kind:
1607 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1608 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1609 st->v.Try.handlers, j);
1610 if (find_ann(handler->v.ExceptHandler.body)) {
1611 return 1;
1612 }
1613 }
1614 res = find_ann(st->v.Try.body) ||
1615 find_ann(st->v.Try.finalbody) ||
1616 find_ann(st->v.Try.orelse);
1617 break;
1618 default:
1619 res = 0;
1620 }
1621 if (res) {
1622 break;
1623 }
1624 }
1625 return res;
1626}
1627
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001628/*
1629 * Frame block handling functions
1630 */
1631
1632static int
1633compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001634 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001635{
1636 struct fblockinfo *f;
1637 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1638 PyErr_SetString(PyExc_SyntaxError,
1639 "too many statically nested blocks");
1640 return 0;
1641 }
1642 f = &c->u->u_fblock[c->u->u_nfblocks++];
1643 f->fb_type = t;
1644 f->fb_block = b;
1645 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001646 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001647 return 1;
1648}
1649
1650static void
1651compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1652{
1653 struct compiler_unit *u = c->u;
1654 assert(u->u_nfblocks > 0);
1655 u->u_nfblocks--;
1656 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1657 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1658}
1659
Mark Shannonfee55262019-11-21 09:11:43 +00001660static int
1661compiler_call_exit_with_nones(struct compiler *c) {
1662 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1663 ADDOP(c, DUP_TOP);
1664 ADDOP(c, DUP_TOP);
1665 ADDOP_I(c, CALL_FUNCTION, 3);
1666 return 1;
1667}
1668
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001669/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001670 * popping the blocks will be restored afterwards, unless another
1671 * return, break or continue is found. In which case, the TOS will
1672 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001673 */
1674static int
1675compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1676 int preserve_tos)
1677{
1678 switch (info->fb_type) {
1679 case WHILE_LOOP:
1680 return 1;
1681
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001682 case FOR_LOOP:
1683 /* Pop the iterator */
1684 if (preserve_tos) {
1685 ADDOP(c, ROT_TWO);
1686 }
1687 ADDOP(c, POP_TOP);
1688 return 1;
1689
1690 case EXCEPT:
1691 ADDOP(c, POP_BLOCK);
1692 return 1;
1693
1694 case FINALLY_TRY:
1695 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001696 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001697 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1698 return 0;
1699 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001700 }
Mark Shannon88dce262019-12-30 09:53:36 +00001701 /* Emit the finally block, restoring the line number when done */
1702 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001703 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001704 c->u->u_lineno = saved_lineno;
1705 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001706 if (preserve_tos) {
1707 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001708 }
1709 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001710
Mark Shannonfee55262019-11-21 09:11:43 +00001711 case FINALLY_END:
1712 if (preserve_tos) {
1713 ADDOP(c, ROT_FOUR);
1714 }
1715 ADDOP(c, POP_TOP);
1716 ADDOP(c, POP_TOP);
1717 ADDOP(c, POP_TOP);
1718 if (preserve_tos) {
1719 ADDOP(c, ROT_FOUR);
1720 }
1721 ADDOP(c, POP_EXCEPT);
1722 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001723
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 case WITH:
1725 case ASYNC_WITH:
1726 ADDOP(c, POP_BLOCK);
1727 if (preserve_tos) {
1728 ADDOP(c, ROT_TWO);
1729 }
Mark Shannonfee55262019-11-21 09:11:43 +00001730 if(!compiler_call_exit_with_nones(c)) {
1731 return 0;
1732 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 if (info->fb_type == ASYNC_WITH) {
1734 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001735 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001736 ADDOP(c, YIELD_FROM);
1737 }
Mark Shannonfee55262019-11-21 09:11:43 +00001738 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001739 return 1;
1740
1741 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001742 if (info->fb_datum) {
1743 ADDOP(c, POP_BLOCK);
1744 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001745 if (preserve_tos) {
1746 ADDOP(c, ROT_FOUR);
1747 }
Mark Shannonfee55262019-11-21 09:11:43 +00001748 ADDOP(c, POP_EXCEPT);
1749 if (info->fb_datum) {
1750 ADDOP_LOAD_CONST(c, Py_None);
1751 compiler_nameop(c, info->fb_datum, Store);
1752 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001753 }
Mark Shannonfee55262019-11-21 09:11:43 +00001754 return 1;
1755
1756 case POP_VALUE:
1757 if (preserve_tos) {
1758 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001759 }
Mark Shannonfee55262019-11-21 09:11:43 +00001760 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001761 return 1;
1762 }
1763 Py_UNREACHABLE();
1764}
1765
Mark Shannonfee55262019-11-21 09:11:43 +00001766/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1767static int
1768compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1769 if (c->u->u_nfblocks == 0) {
1770 return 1;
1771 }
1772 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1773 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1774 *loop = top;
1775 return 1;
1776 }
1777 struct fblockinfo copy = *top;
1778 c->u->u_nfblocks--;
1779 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1780 return 0;
1781 }
1782 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1783 return 0;
1784 }
1785 c->u->u_fblock[c->u->u_nfblocks] = copy;
1786 c->u->u_nfblocks++;
1787 return 1;
1788}
1789
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001790/* Compile a sequence of statements, checking for a docstring
1791 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792
1793static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001794compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001796 int i = 0;
1797 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001798 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001799
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001800 /* Set current line number to the line number of first statement.
1801 This way line number for SETUP_ANNOTATIONS will always
1802 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301803 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001804 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1805 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001806 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001807 c->u->u_lineno = st->lineno;
1808 }
1809 /* Every annotated class and module should have __annotations__. */
1810 if (find_ann(stmts)) {
1811 ADDOP(c, SETUP_ANNOTATIONS);
1812 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001813 if (!asdl_seq_LEN(stmts))
1814 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001815 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001816 if (c->c_optimize < 2) {
1817 docstring = _PyAST_GetDocString(stmts);
1818 if (docstring) {
1819 i = 1;
1820 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1821 assert(st->kind == Expr_kind);
1822 VISIT(c, expr, st->v.Expr.value);
1823 if (!compiler_nameop(c, __doc__, Store))
1824 return 0;
1825 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001827 for (; i < asdl_seq_LEN(stmts); i++)
1828 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830}
1831
1832static PyCodeObject *
1833compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyCodeObject *co;
1836 int addNone = 1;
1837 static PyObject *module;
1838 if (!module) {
1839 module = PyUnicode_InternFromString("<module>");
1840 if (!module)
1841 return NULL;
1842 }
1843 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001844 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return NULL;
1846 switch (mod->kind) {
1847 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001848 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 compiler_exit_scope(c);
1850 return 0;
1851 }
1852 break;
1853 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001854 if (find_ann(mod->v.Interactive.body)) {
1855 ADDOP(c, SETUP_ANNOTATIONS);
1856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 c->c_interactive = 1;
1858 VISIT_SEQ_IN_SCOPE(c, stmt,
1859 mod->v.Interactive.body);
1860 break;
1861 case Expression_kind:
1862 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1863 addNone = 0;
1864 break;
1865 case Suite_kind:
1866 PyErr_SetString(PyExc_SystemError,
1867 "suite should not be possible");
1868 return 0;
1869 default:
1870 PyErr_Format(PyExc_SystemError,
1871 "module kind %d should not be possible",
1872 mod->kind);
1873 return 0;
1874 }
1875 co = assemble(c, addNone);
1876 compiler_exit_scope(c);
1877 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001878}
1879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880/* The test for LOCAL must come before the test for FREE in order to
1881 handle classes where name is both local and free. The local var is
1882 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001883*/
1884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885static int
1886get_ref_type(struct compiler *c, PyObject *name)
1887{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001888 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001889 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001890 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001891 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001892 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (scope == 0) {
1894 char buf[350];
1895 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001896 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001898 PyUnicode_AsUTF8(name),
1899 PyUnicode_AsUTF8(c->u->u_name),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1902 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1903 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 );
1905 Py_FatalError(buf);
1906 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_lookup_arg(PyObject *dict, PyObject *name)
1913{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 PyObject *v;
1915 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001917 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001918 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001924 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 if (qualname == NULL)
1926 qualname = co->co_name;
1927
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 if (free) {
1929 for (i = 0; i < free; ++i) {
1930 /* Bypass com_addop_varname because it will generate
1931 LOAD_DEREF but LOAD_CLOSURE is needed.
1932 */
1933 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1934 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001936 /* Special case: If a class contains a method with a
1937 free variable that has the same name as a method,
1938 the name will be considered free *and* local in the
1939 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001940 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 */
1942 reftype = get_ref_type(c, name);
1943 if (reftype == CELL)
1944 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1945 else /* (reftype == FREE) */
1946 arg = compiler_lookup_arg(c->u->u_freevars, name);
1947 if (arg == -1) {
1948 fprintf(stderr,
1949 "lookup %s in %s %d %d\n"
1950 "freevars of %s: %s\n",
1951 PyUnicode_AsUTF8(PyObject_Repr(name)),
1952 PyUnicode_AsUTF8(c->u->u_name),
1953 reftype, arg,
1954 PyUnicode_AsUTF8(co->co_name),
1955 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1956 Py_FatalError("compiler_make_closure()");
1957 }
1958 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 flags |= 0x08;
1961 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001963 ADDOP_LOAD_CONST(c, (PyObject*)co);
1964 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967}
1968
1969static int
1970compiler_decorators(struct compiler *c, asdl_seq* decos)
1971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (!decos)
1975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1978 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1979 }
1980 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981}
1982
1983static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001984compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001986{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001987 /* Push a dict of keyword-only default values.
1988
1989 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1990 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 int i;
1992 PyObject *keys = NULL;
1993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1995 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1996 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1997 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001998 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001999 if (!mangled) {
2000 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 if (keys == NULL) {
2003 keys = PyList_New(1);
2004 if (keys == NULL) {
2005 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002006 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002007 }
2008 PyList_SET_ITEM(keys, 0, mangled);
2009 }
2010 else {
2011 int res = PyList_Append(keys, mangled);
2012 Py_DECREF(mangled);
2013 if (res == -1) {
2014 goto error;
2015 }
2016 }
2017 if (!compiler_visit_expr(c, default_)) {
2018 goto error;
2019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
2021 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 if (keys != NULL) {
2023 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2024 PyObject *keys_tuple = PyList_AsTuple(keys);
2025 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002026 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002027 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028 assert(default_count > 0);
2029 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 }
2031 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002032 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002033 }
2034
2035error:
2036 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002037 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002038}
2039
2040static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002041compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2042{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002043 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002044 return 1;
2045}
2046
2047static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002048compiler_visit_argannotation(struct compiler *c, identifier id,
2049 expr_ty annotation, PyObject *names)
2050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002052 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002053 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2054 VISIT(c, annexpr, annotation)
2055 }
2056 else {
2057 VISIT(c, expr, annotation);
2058 }
Victor Stinner065efc32014-02-18 22:07:56 +01002059 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002062 if (PyList_Append(names, mangled) < 0) {
2063 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002065 }
2066 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002068 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002069}
2070
2071static int
2072compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2073 PyObject *names)
2074{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 for (i = 0; i < asdl_seq_LEN(args); i++) {
2077 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002078 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 c,
2080 arg->arg,
2081 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002082 names))
2083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002086}
2087
2088static int
2089compiler_visit_annotations(struct compiler *c, arguments_ty args,
2090 expr_ty returns)
2091{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002092 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002093 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002094
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002095 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 */
2097 static identifier return_str;
2098 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002099 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 names = PyList_New(0);
2101 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002102 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002103
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002104 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002106 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2107 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002108 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002109 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002110 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002112 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002114 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002115 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002116 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (!return_str) {
2120 return_str = PyUnicode_InternFromString("return");
2121 if (!return_str)
2122 goto error;
2123 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002124 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 goto error;
2126 }
2127
2128 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002130 PyObject *keytuple = PyList_AsTuple(names);
2131 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002132 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002133 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002134 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002136 else {
2137 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002140
2141error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002143 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002144}
2145
2146static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002147compiler_visit_defaults(struct compiler *c, arguments_ty args)
2148{
2149 VISIT_SEQ(c, expr, args->defaults);
2150 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2151 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152}
2153
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154static Py_ssize_t
2155compiler_default_arguments(struct compiler *c, arguments_ty args)
2156{
2157 Py_ssize_t funcflags = 0;
2158 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002159 if (!compiler_visit_defaults(c, args))
2160 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002161 funcflags |= 0x01;
2162 }
2163 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002164 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002166 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002167 return -1;
2168 }
2169 else if (res > 0) {
2170 funcflags |= 0x02;
2171 }
2172 }
2173 return funcflags;
2174}
2175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176static int
Yury Selivanov75445082015-05-11 22:57:16 -04002177compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002180 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002181 arguments_ty args;
2182 expr_ty returns;
2183 identifier name;
2184 asdl_seq* decos;
2185 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002186 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002187 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002188 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002189 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190
Yury Selivanov75445082015-05-11 22:57:16 -04002191 if (is_async) {
2192 assert(s->kind == AsyncFunctionDef_kind);
2193
2194 args = s->v.AsyncFunctionDef.args;
2195 returns = s->v.AsyncFunctionDef.returns;
2196 decos = s->v.AsyncFunctionDef.decorator_list;
2197 name = s->v.AsyncFunctionDef.name;
2198 body = s->v.AsyncFunctionDef.body;
2199
2200 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2201 } else {
2202 assert(s->kind == FunctionDef_kind);
2203
2204 args = s->v.FunctionDef.args;
2205 returns = s->v.FunctionDef.returns;
2206 decos = s->v.FunctionDef.decorator_list;
2207 name = s->v.FunctionDef.name;
2208 body = s->v.FunctionDef.body;
2209
2210 scope_type = COMPILER_SCOPE_FUNCTION;
2211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (!compiler_decorators(c, decos))
2214 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002215
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002216 firstlineno = s->lineno;
2217 if (asdl_seq_LEN(decos)) {
2218 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2219 }
2220
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002221 funcflags = compiler_default_arguments(c, args);
2222 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002224 }
2225
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002226 annotations = compiler_visit_annotations(c, args, returns);
2227 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002228 return 0;
2229 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002230 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002231 funcflags |= 0x04;
2232 }
2233
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002234 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002235 return 0;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237
INADA Naokicb41b272017-02-23 00:31:59 +09002238 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002239 if (c->c_optimize < 2) {
2240 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002241 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002242 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 compiler_exit_scope(c);
2244 return 0;
2245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002248 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002250 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002252 qualname = c->u->u_qualname;
2253 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002255 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002256 Py_XDECREF(qualname);
2257 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002261 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002262 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 /* decorators */
2266 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2267 ADDOP_I(c, CALL_FUNCTION, 1);
2268 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269
Yury Selivanov75445082015-05-11 22:57:16 -04002270 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271}
2272
2273static int
2274compiler_class(struct compiler *c, stmt_ty s)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyCodeObject *co;
2277 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002278 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (!compiler_decorators(c, decos))
2282 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002283
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002284 firstlineno = s->lineno;
2285 if (asdl_seq_LEN(decos)) {
2286 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2287 }
2288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* ultimately generate code for:
2290 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2291 where:
2292 <func> is a function/closure created from the class body;
2293 it has a single argument (__locals__) where the dict
2294 (or MutableSequence) representing the locals is passed
2295 <name> is the class name
2296 <bases> is the positional arguments and *varargs argument
2297 <keywords> is the keyword arguments and **kwds argument
2298 This borrows from compiler_call.
2299 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002302 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002303 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return 0;
2305 /* this block represents what we do in the new scope */
2306 {
2307 /* use the class name for name mangling */
2308 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002309 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* load (global) __name__ ... */
2311 str = PyUnicode_InternFromString("__name__");
2312 if (!str || !compiler_nameop(c, str, Load)) {
2313 Py_XDECREF(str);
2314 compiler_exit_scope(c);
2315 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 Py_DECREF(str);
2318 /* ... and store it as __module__ */
2319 str = PyUnicode_InternFromString("__module__");
2320 if (!str || !compiler_nameop(c, str, Store)) {
2321 Py_XDECREF(str);
2322 compiler_exit_scope(c);
2323 return 0;
2324 }
2325 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002326 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002327 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002328 str = PyUnicode_InternFromString("__qualname__");
2329 if (!str || !compiler_nameop(c, str, Store)) {
2330 Py_XDECREF(str);
2331 compiler_exit_scope(c);
2332 return 0;
2333 }
2334 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002336 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 compiler_exit_scope(c);
2338 return 0;
2339 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002340 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002341 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002342 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002343 str = PyUnicode_InternFromString("__class__");
2344 if (str == NULL) {
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 i = compiler_lookup_arg(c->u->u_cellvars, str);
2349 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002350 if (i < 0) {
2351 compiler_exit_scope(c);
2352 return 0;
2353 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002354 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002357 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002358 str = PyUnicode_InternFromString("__classcell__");
2359 if (!str || !compiler_nameop(c, str, Store)) {
2360 Py_XDECREF(str);
2361 compiler_exit_scope(c);
2362 return 0;
2363 }
2364 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002366 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002367 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002368 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002369 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002370 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002371 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* create the code object */
2373 co = assemble(c, 1);
2374 }
2375 /* leave the new scope */
2376 compiler_exit_scope(c);
2377 if (co == NULL)
2378 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* 2. load the 'build_class' function */
2381 ADDOP(c, LOAD_BUILD_CLASS);
2382
2383 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002384 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 Py_DECREF(co);
2386
2387 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002388 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389
2390 /* 5. generate the rest of the code for the call */
2391 if (!compiler_call_helper(c, 2,
2392 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002393 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return 0;
2395
2396 /* 6. apply decorators */
2397 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2398 ADDOP_I(c, CALL_FUNCTION, 1);
2399 }
2400
2401 /* 7. store into <name> */
2402 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2403 return 0;
2404 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405}
2406
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002407/* Return 0 if the expression is a constant value except named singletons.
2408 Return 1 otherwise. */
2409static int
2410check_is_arg(expr_ty e)
2411{
2412 if (e->kind != Constant_kind) {
2413 return 1;
2414 }
2415 PyObject *value = e->v.Constant.value;
2416 return (value == Py_None
2417 || value == Py_False
2418 || value == Py_True
2419 || value == Py_Ellipsis);
2420}
2421
2422/* Check operands of identity chacks ("is" and "is not").
2423 Emit a warning if any operand is a constant except named singletons.
2424 Return 0 on error.
2425 */
2426static int
2427check_compare(struct compiler *c, expr_ty e)
2428{
2429 Py_ssize_t i, n;
2430 int left = check_is_arg(e->v.Compare.left);
2431 n = asdl_seq_LEN(e->v.Compare.ops);
2432 for (i = 0; i < n; i++) {
2433 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2434 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2435 if (op == Is || op == IsNot) {
2436 if (!right || !left) {
2437 const char *msg = (op == Is)
2438 ? "\"is\" with a literal. Did you mean \"==\"?"
2439 : "\"is not\" with a literal. Did you mean \"!=\"?";
2440 return compiler_warn(c, msg);
2441 }
2442 }
2443 left = right;
2444 }
2445 return 1;
2446}
2447
Mark Shannon9af0e472020-01-14 10:12:45 +00002448static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449{
Mark Shannon9af0e472020-01-14 10:12:45 +00002450 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002451 switch (op) {
2452 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002453 cmp = Py_EQ;
2454 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002455 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002456 cmp = Py_NE;
2457 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002458 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002459 cmp = Py_LT;
2460 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 cmp = Py_LE;
2463 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002464 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 cmp = Py_GT;
2466 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 cmp = Py_GE;
2469 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002471 ADDOP_I(c, IS_OP, 0);
2472 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 ADDOP_I(c, IS_OP, 1);
2475 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002477 ADDOP_I(c, CONTAINS_OP, 0);
2478 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 ADDOP_I(c, CONTAINS_OP, 1);
2481 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002484 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002485 ADDOP_I(c, COMPARE_OP, cmp);
2486 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487}
2488
Mark Shannon9af0e472020-01-14 10:12:45 +00002489
2490
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491static int
2492compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2493{
2494 switch (e->kind) {
2495 case UnaryOp_kind:
2496 if (e->v.UnaryOp.op == Not)
2497 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2498 /* fallback to general implementation */
2499 break;
2500 case BoolOp_kind: {
2501 asdl_seq *s = e->v.BoolOp.values;
2502 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2503 assert(n >= 0);
2504 int cond2 = e->v.BoolOp.op == Or;
2505 basicblock *next2 = next;
2506 if (!cond2 != !cond) {
2507 next2 = compiler_new_block(c);
2508 if (next2 == NULL)
2509 return 0;
2510 }
2511 for (i = 0; i < n; ++i) {
2512 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2513 return 0;
2514 }
2515 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2516 return 0;
2517 if (next2 != next)
2518 compiler_use_next_block(c, next2);
2519 return 1;
2520 }
2521 case IfExp_kind: {
2522 basicblock *end, *next2;
2523 end = compiler_new_block(c);
2524 if (end == NULL)
2525 return 0;
2526 next2 = compiler_new_block(c);
2527 if (next2 == NULL)
2528 return 0;
2529 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2530 return 0;
2531 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2532 return 0;
2533 ADDOP_JREL(c, JUMP_FORWARD, end);
2534 compiler_use_next_block(c, next2);
2535 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2536 return 0;
2537 compiler_use_next_block(c, end);
2538 return 1;
2539 }
2540 case Compare_kind: {
2541 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2542 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002543 if (!check_compare(c, e)) {
2544 return 0;
2545 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 basicblock *cleanup = compiler_new_block(c);
2547 if (cleanup == NULL)
2548 return 0;
2549 VISIT(c, expr, e->v.Compare.left);
2550 for (i = 0; i < n; i++) {
2551 VISIT(c, expr,
2552 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2553 ADDOP(c, DUP_TOP);
2554 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002555 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002556 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2557 NEXT_BLOCK(c);
2558 }
2559 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002560 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002561 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2562 basicblock *end = compiler_new_block(c);
2563 if (end == NULL)
2564 return 0;
2565 ADDOP_JREL(c, JUMP_FORWARD, end);
2566 compiler_use_next_block(c, cleanup);
2567 ADDOP(c, POP_TOP);
2568 if (!cond) {
2569 ADDOP_JREL(c, JUMP_FORWARD, next);
2570 }
2571 compiler_use_next_block(c, end);
2572 return 1;
2573 }
2574 /* fallback to general implementation */
2575 break;
2576 }
2577 default:
2578 /* fallback to general implementation */
2579 break;
2580 }
2581
2582 /* general implementation */
2583 VISIT(c, expr, e);
2584 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2585 return 1;
2586}
2587
2588static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002589compiler_ifexp(struct compiler *c, expr_ty e)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 basicblock *end, *next;
2592
2593 assert(e->kind == IfExp_kind);
2594 end = compiler_new_block(c);
2595 if (end == NULL)
2596 return 0;
2597 next = compiler_new_block(c);
2598 if (next == NULL)
2599 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002600 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2601 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 VISIT(c, expr, e->v.IfExp.body);
2603 ADDOP_JREL(c, JUMP_FORWARD, end);
2604 compiler_use_next_block(c, next);
2605 VISIT(c, expr, e->v.IfExp.orelse);
2606 compiler_use_next_block(c, end);
2607 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002608}
2609
2610static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611compiler_lambda(struct compiler *c, expr_ty e)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002614 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002616 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 arguments_ty args = e->v.Lambda.args;
2618 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 if (!name) {
2621 name = PyUnicode_InternFromString("<lambda>");
2622 if (!name)
2623 return 0;
2624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002626 funcflags = compiler_default_arguments(c, args);
2627 if (funcflags == -1) {
2628 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002630
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002631 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002632 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* Make None the first constant, so the lambda can't have a
2636 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002637 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002641 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2643 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2644 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002645 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
2647 else {
2648 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002649 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002651 qualname = c->u->u_qualname;
2652 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002654 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002657 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002658 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 Py_DECREF(co);
2660
2661 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662}
2663
2664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665compiler_if(struct compiler *c, stmt_ty s)
2666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 basicblock *end, *next;
2668 int constant;
2669 assert(s->kind == If_kind);
2670 end = compiler_new_block(c);
2671 if (end == NULL)
2672 return 0;
2673
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002674 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002675 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 * constant = 1: "if 1", "if 2", ...
2677 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002678 if (constant == 0) {
2679 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002681 END_DO_NOT_EMIT_BYTECODE
2682 if (s->v.If.orelse) {
2683 VISIT_SEQ(c, stmt, s->v.If.orelse);
2684 }
2685 } else if (constant == 1) {
2686 VISIT_SEQ(c, stmt, s->v.If.body);
2687 if (s->v.If.orelse) {
2688 BEGIN_DO_NOT_EMIT_BYTECODE
2689 VISIT_SEQ(c, stmt, s->v.If.orelse);
2690 END_DO_NOT_EMIT_BYTECODE
2691 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002693 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 next = compiler_new_block(c);
2695 if (next == NULL)
2696 return 0;
2697 }
Mark Shannonfee55262019-11-21 09:11:43 +00002698 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002700 }
2701 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002702 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002705 if (asdl_seq_LEN(s->v.If.orelse)) {
2706 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 compiler_use_next_block(c, next);
2708 VISIT_SEQ(c, stmt, s->v.If.orelse);
2709 }
2710 }
2711 compiler_use_next_block(c, end);
2712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713}
2714
2715static int
2716compiler_for(struct compiler *c, stmt_ty s)
2717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 start = compiler_new_block(c);
2721 cleanup = compiler_new_block(c);
2722 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002723 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002725 }
2726 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 VISIT(c, expr, s->v.For.iter);
2730 ADDOP(c, GET_ITER);
2731 compiler_use_next_block(c, start);
2732 ADDOP_JREL(c, FOR_ITER, cleanup);
2733 VISIT(c, expr, s->v.For.target);
2734 VISIT_SEQ(c, stmt, s->v.For.body);
2735 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2736 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002737
2738 compiler_pop_fblock(c, FOR_LOOP, start);
2739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 VISIT_SEQ(c, stmt, s->v.For.orelse);
2741 compiler_use_next_block(c, end);
2742 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743}
2744
Yury Selivanov75445082015-05-11 22:57:16 -04002745
2746static int
2747compiler_async_for(struct compiler *c, stmt_ty s)
2748{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002749 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002750 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2751 c->u->u_ste->ste_coroutine = 1;
2752 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002753 return compiler_error(c, "'async for' outside async function");
2754 }
2755
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002756 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002757 except = compiler_new_block(c);
2758 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002759
Mark Shannonfee55262019-11-21 09:11:43 +00002760 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002761 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002762 }
Yury Selivanov75445082015-05-11 22:57:16 -04002763 VISIT(c, expr, s->v.AsyncFor.iter);
2764 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002765
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002767 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002768 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002769 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002770 /* SETUP_FINALLY to guard the __anext__ call */
2771 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002772 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002773 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002774 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002776
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002777 /* Success block for __anext__ */
2778 VISIT(c, expr, s->v.AsyncFor.target);
2779 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2780 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2781
2782 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002783
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002785 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002786 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002787
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002789 VISIT_SEQ(c, stmt, s->v.For.orelse);
2790
2791 compiler_use_next_block(c, end);
2792
2793 return 1;
2794}
2795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796static int
2797compiler_while(struct compiler *c, stmt_ty s)
2798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002800 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002803 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002804 // Push a dummy block so the VISIT_SEQ knows that we are
2805 // inside a while loop so it can correctly evaluate syntax
2806 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002807 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002808 return 0;
2809 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002810 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002811 // Remove the dummy block now that is not needed.
2812 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002813 END_DO_NOT_EMIT_BYTECODE
2814 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return 1;
2818 }
2819 loop = compiler_new_block(c);
2820 end = compiler_new_block(c);
2821 if (constant == -1) {
2822 anchor = compiler_new_block(c);
2823 if (anchor == NULL)
2824 return 0;
2825 }
2826 if (loop == NULL || end == NULL)
2827 return 0;
2828 if (s->v.While.orelse) {
2829 orelse = compiler_new_block(c);
2830 if (orelse == NULL)
2831 return 0;
2832 }
2833 else
2834 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002837 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 return 0;
2839 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002840 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2841 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 }
2843 VISIT_SEQ(c, stmt, s->v.While.body);
2844 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* XXX should the two POP instructions be in a separate block
2847 if there is no else clause ?
2848 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002850 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002852 compiler_pop_fblock(c, WHILE_LOOP, loop);
2853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (orelse != NULL) /* what if orelse is just pass? */
2855 VISIT_SEQ(c, stmt, s->v.While.orelse);
2856 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
2860
2861static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002864 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002865 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002866 if (c->u->u_ste->ste_type != FunctionBlock)
2867 return compiler_error(c, "'return' outside function");
2868 if (s->v.Return.value != NULL &&
2869 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2870 {
2871 return compiler_error(
2872 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002874 if (preserve_tos) {
2875 VISIT(c, expr, s->v.Return.value);
2876 }
Mark Shannonfee55262019-11-21 09:11:43 +00002877 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2878 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002880 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 }
2882 else if (!preserve_tos) {
2883 VISIT(c, expr, s->v.Return.value);
2884 }
2885 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888}
2889
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890static int
2891compiler_break(struct compiler *c)
2892{
Mark Shannonfee55262019-11-21 09:11:43 +00002893 struct fblockinfo *loop = NULL;
2894 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2895 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896 }
Mark Shannonfee55262019-11-21 09:11:43 +00002897 if (loop == NULL) {
2898 return compiler_error(c, "'break' outside loop");
2899 }
2900 if (!compiler_unwind_fblock(c, loop, 0)) {
2901 return 0;
2902 }
2903 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2904 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002905}
2906
2907static int
2908compiler_continue(struct compiler *c)
2909{
Mark Shannonfee55262019-11-21 09:11:43 +00002910 struct fblockinfo *loop = NULL;
2911 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2912 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002913 }
Mark Shannonfee55262019-11-21 09:11:43 +00002914 if (loop == NULL) {
2915 return compiler_error(c, "'continue' not properly in loop");
2916 }
2917 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2918 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002919}
2920
2921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923
2924 SETUP_FINALLY L
2925 <code for body>
2926 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002927 <code for finalbody>
2928 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002929 L:
2930 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002931 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 The special instructions use the block stack. Each block
2934 stack entry contains the instruction that created it (here
2935 SETUP_FINALLY), the level of the value stack at the time the
2936 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Pushes the current value stack level and the label
2940 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002945 when a SETUP_FINALLY entry is found, the raised and the caught
2946 exceptions are pushed onto the value stack (and the exception
2947 condition is cleared), and the interpreter jumps to the label
2948 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949*/
2950
2951static int
2952compiler_try_finally(struct compiler *c, stmt_ty s)
2953{
Mark Shannonfee55262019-11-21 09:11:43 +00002954 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 body = compiler_new_block(c);
2957 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002958 exit = compiler_new_block(c);
2959 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002962 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 ADDOP_JREL(c, SETUP_FINALLY, end);
2964 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002965 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002967 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2968 if (!compiler_try_except(c, s))
2969 return 0;
2970 }
2971 else {
2972 VISIT_SEQ(c, stmt, s->v.Try.body);
2973 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002975 compiler_pop_fblock(c, FINALLY_TRY, body);
2976 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2977 ADDOP_JREL(c, JUMP_FORWARD, exit);
2978 /* `finally` block */
2979 compiler_use_next_block(c, end);
2980 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2981 return 0;
2982 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2983 compiler_pop_fblock(c, FINALLY_END, end);
2984 ADDOP(c, RERAISE);
2985 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987}
2988
2989/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002990 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 (The contents of the value stack is shown in [], with the top
2992 at the right; 'tb' is trace-back info, 'val' the exception's
2993 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994
2995 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002996 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 [] <code for S>
2998 [] POP_BLOCK
2999 [] JUMP_FORWARD L0
3000
3001 [tb, val, exc] L1: DUP )
3002 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003003 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 [tb, val, exc] POP
3005 [tb, val] <assign to V1> (or POP if no V1)
3006 [tb] POP
3007 [] <code for S1>
3008 JUMP_FORWARD L0
3009
3010 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011 .............................etc.......................
3012
Mark Shannonfee55262019-11-21 09:11:43 +00003013 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014
3015 [] L0: <next statement>
3016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 Of course, parts are not generated if Vi or Ei is not present.
3018*/
3019static int
3020compiler_try_except(struct compiler *c, stmt_ty s)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003023 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 body = compiler_new_block(c);
3026 except = compiler_new_block(c);
3027 orelse = compiler_new_block(c);
3028 end = compiler_new_block(c);
3029 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3030 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003031 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003033 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003035 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 ADDOP(c, POP_BLOCK);
3037 compiler_pop_fblock(c, EXCEPT, body);
3038 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 compiler_use_next_block(c, except);
3041 for (i = 0; i < n; i++) {
3042 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003043 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 if (!handler->v.ExceptHandler.type && i < n-1)
3045 return compiler_error(c, "default 'except:' must be last");
3046 c->u->u_lineno_set = 0;
3047 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003048 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 except = compiler_new_block(c);
3050 if (except == NULL)
3051 return 0;
3052 if (handler->v.ExceptHandler.type) {
3053 ADDOP(c, DUP_TOP);
3054 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003055 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 }
3057 ADDOP(c, POP_TOP);
3058 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003060
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 cleanup_end = compiler_new_block(c);
3062 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003063 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003064 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003065 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3068 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 /*
3071 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003072 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003074 try:
3075 # body
3076 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003077 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003078 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 /* second try: */
3082 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3083 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003084 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 /* second # body */
3088 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003089 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003090 ADDOP(c, POP_BLOCK);
3091 ADDOP(c, POP_EXCEPT);
3092 /* name = None; del name */
3093 ADDOP_LOAD_CONST(c, Py_None);
3094 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3095 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3096 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Mark Shannonfee55262019-11-21 09:11:43 +00003098 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003101 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003102 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003104 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105
Mark Shannonfee55262019-11-21 09:11:43 +00003106 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 }
3108 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003112 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Guido van Rossumb940e112007-01-10 16:19:56 +00003115 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003116 ADDOP(c, POP_TOP);
3117 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003118 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003121 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003122 ADDOP(c, POP_EXCEPT);
3123 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 compiler_use_next_block(c, except);
3126 }
Mark Shannonfee55262019-11-21 09:11:43 +00003127 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003129 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 compiler_use_next_block(c, end);
3131 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132}
3133
3134static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003135compiler_try(struct compiler *c, stmt_ty s) {
3136 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3137 return compiler_try_finally(c, s);
3138 else
3139 return compiler_try_except(c, s);
3140}
3141
3142
3143static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144compiler_import_as(struct compiler *c, identifier name, identifier asname)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* The IMPORT_NAME opcode was already generated. This function
3147 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003150 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003152 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3153 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003155 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003156 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003158 while (1) {
3159 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003161 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003162 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003163 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003164 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003166 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003167 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003168 if (dot == -1) {
3169 break;
3170 }
3171 ADDOP(c, ROT_TWO);
3172 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003174 if (!compiler_nameop(c, asname, Store)) {
3175 return 0;
3176 }
3177 ADDOP(c, POP_TOP);
3178 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 }
3180 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
3184compiler_import(struct compiler *c, stmt_ty s)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 /* The Import node stores a module name like a.b.c as a single
3187 string. This is convenient for all cases except
3188 import a.b.c as d
3189 where we need to parse that string to extract the individual
3190 module names.
3191 XXX Perhaps change the representation to make this case simpler?
3192 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003193 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 for (i = 0; i < n; i++) {
3196 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3197 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003199 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3200 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 if (alias->asname) {
3204 r = compiler_import_as(c, alias->name, alias->asname);
3205 if (!r)
3206 return r;
3207 }
3208 else {
3209 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003210 Py_ssize_t dot = PyUnicode_FindChar(
3211 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003212 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003213 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003214 if (tmp == NULL)
3215 return 0;
3216 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003218 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 Py_DECREF(tmp);
3220 }
3221 if (!r)
3222 return r;
3223 }
3224 }
3225 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226}
3227
3228static int
3229compiler_from_import(struct compiler *c, stmt_ty s)
3230{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003231 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003232 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 if (!empty_string) {
3236 empty_string = PyUnicode_FromString("");
3237 if (!empty_string)
3238 return 0;
3239 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003241 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003242
3243 names = PyTuple_New(n);
3244 if (!names)
3245 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 /* build up the names */
3248 for (i = 0; i < n; i++) {
3249 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3250 Py_INCREF(alias->name);
3251 PyTuple_SET_ITEM(names, i, alias->name);
3252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003255 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 Py_DECREF(names);
3257 return compiler_error(c, "from __future__ imports must occur "
3258 "at the beginning of the file");
3259 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003260 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 if (s->v.ImportFrom.module) {
3263 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3264 }
3265 else {
3266 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3267 }
3268 for (i = 0; i < n; i++) {
3269 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3270 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003272 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 assert(n == 1);
3274 ADDOP(c, IMPORT_STAR);
3275 return 1;
3276 }
3277
3278 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3279 store_name = alias->name;
3280 if (alias->asname)
3281 store_name = alias->asname;
3282
3283 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 return 0;
3285 }
3286 }
3287 /* remove imported module */
3288 ADDOP(c, POP_TOP);
3289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290}
3291
3292static int
3293compiler_assert(struct compiler *c, stmt_ty s)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296
Georg Brandl8334fd92010-12-04 10:26:46 +00003297 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003300 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3301 {
3302 if (!compiler_warn(c, "assertion is always true, "
3303 "perhaps remove parentheses?"))
3304 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003305 return 0;
3306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 end = compiler_new_block(c);
3309 if (end == NULL)
3310 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003311 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3312 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003313 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (s->v.Assert.msg) {
3315 VISIT(c, expr, s->v.Assert.msg);
3316 ADDOP_I(c, CALL_FUNCTION, 1);
3317 }
3318 ADDOP_I(c, RAISE_VARARGS, 1);
3319 compiler_use_next_block(c, end);
3320 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321}
3322
3323static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003324compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3325{
3326 if (c->c_interactive && c->c_nestlevel <= 1) {
3327 VISIT(c, expr, value);
3328 ADDOP(c, PRINT_EXPR);
3329 return 1;
3330 }
3331
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003332 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003333 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003334 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003335 }
3336
3337 VISIT(c, expr, value);
3338 ADDOP(c, POP_TOP);
3339 return 1;
3340}
3341
3342static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343compiler_visit_stmt(struct compiler *c, stmt_ty s)
3344{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003345 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 /* Always assign a lineno to the next instruction for a stmt. */
3348 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003349 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 switch (s->kind) {
3353 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003354 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case ClassDef_kind:
3356 return compiler_class(c, s);
3357 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003358 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 case Delete_kind:
3360 VISIT_SEQ(c, expr, s->v.Delete.targets)
3361 break;
3362 case Assign_kind:
3363 n = asdl_seq_LEN(s->v.Assign.targets);
3364 VISIT(c, expr, s->v.Assign.value);
3365 for (i = 0; i < n; i++) {
3366 if (i < n - 1)
3367 ADDOP(c, DUP_TOP);
3368 VISIT(c, expr,
3369 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3370 }
3371 break;
3372 case AugAssign_kind:
3373 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003374 case AnnAssign_kind:
3375 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 case For_kind:
3377 return compiler_for(c, s);
3378 case While_kind:
3379 return compiler_while(c, s);
3380 case If_kind:
3381 return compiler_if(c, s);
3382 case Raise_kind:
3383 n = 0;
3384 if (s->v.Raise.exc) {
3385 VISIT(c, expr, s->v.Raise.exc);
3386 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003387 if (s->v.Raise.cause) {
3388 VISIT(c, expr, s->v.Raise.cause);
3389 n++;
3390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003392 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003394 case Try_kind:
3395 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 case Assert_kind:
3397 return compiler_assert(c, s);
3398 case Import_kind:
3399 return compiler_import(c, s);
3400 case ImportFrom_kind:
3401 return compiler_from_import(c, s);
3402 case Global_kind:
3403 case Nonlocal_kind:
3404 break;
3405 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003406 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 case Pass_kind:
3408 break;
3409 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003410 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 case Continue_kind:
3412 return compiler_continue(c);
3413 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003414 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003415 case AsyncFunctionDef_kind:
3416 return compiler_function(c, s, 1);
3417 case AsyncWith_kind:
3418 return compiler_async_with(c, s, 0);
3419 case AsyncFor_kind:
3420 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 }
Yury Selivanov75445082015-05-11 22:57:16 -04003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424}
3425
3426static int
3427unaryop(unaryop_ty op)
3428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 switch (op) {
3430 case Invert:
3431 return UNARY_INVERT;
3432 case Not:
3433 return UNARY_NOT;
3434 case UAdd:
3435 return UNARY_POSITIVE;
3436 case USub:
3437 return UNARY_NEGATIVE;
3438 default:
3439 PyErr_Format(PyExc_SystemError,
3440 "unary op %d should not be possible", op);
3441 return 0;
3442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
3446binop(struct compiler *c, operator_ty op)
3447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 switch (op) {
3449 case Add:
3450 return BINARY_ADD;
3451 case Sub:
3452 return BINARY_SUBTRACT;
3453 case Mult:
3454 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003455 case MatMult:
3456 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 case Div:
3458 return BINARY_TRUE_DIVIDE;
3459 case Mod:
3460 return BINARY_MODULO;
3461 case Pow:
3462 return BINARY_POWER;
3463 case LShift:
3464 return BINARY_LSHIFT;
3465 case RShift:
3466 return BINARY_RSHIFT;
3467 case BitOr:
3468 return BINARY_OR;
3469 case BitXor:
3470 return BINARY_XOR;
3471 case BitAnd:
3472 return BINARY_AND;
3473 case FloorDiv:
3474 return BINARY_FLOOR_DIVIDE;
3475 default:
3476 PyErr_Format(PyExc_SystemError,
3477 "binary op %d should not be possible", op);
3478 return 0;
3479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480}
3481
3482static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483inplace_binop(struct compiler *c, operator_ty op)
3484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 switch (op) {
3486 case Add:
3487 return INPLACE_ADD;
3488 case Sub:
3489 return INPLACE_SUBTRACT;
3490 case Mult:
3491 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003492 case MatMult:
3493 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 case Div:
3495 return INPLACE_TRUE_DIVIDE;
3496 case Mod:
3497 return INPLACE_MODULO;
3498 case Pow:
3499 return INPLACE_POWER;
3500 case LShift:
3501 return INPLACE_LSHIFT;
3502 case RShift:
3503 return INPLACE_RSHIFT;
3504 case BitOr:
3505 return INPLACE_OR;
3506 case BitXor:
3507 return INPLACE_XOR;
3508 case BitAnd:
3509 return INPLACE_AND;
3510 case FloorDiv:
3511 return INPLACE_FLOOR_DIVIDE;
3512 default:
3513 PyErr_Format(PyExc_SystemError,
3514 "inplace binary op %d should not be possible", op);
3515 return 0;
3516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517}
3518
3519static int
3520compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3521{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003522 int op, scope;
3523 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 PyObject *dict = c->u->u_names;
3527 PyObject *mangled;
3528 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003530 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3531 !_PyUnicode_EqualToASCIIString(name, "True") &&
3532 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003533
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003534 mangled = _Py_Mangle(c->u->u_private, name);
3535 if (!mangled)
3536 return 0;
3537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 op = 0;
3539 optype = OP_NAME;
3540 scope = PyST_GetScope(c->u->u_ste, mangled);
3541 switch (scope) {
3542 case FREE:
3543 dict = c->u->u_freevars;
3544 optype = OP_DEREF;
3545 break;
3546 case CELL:
3547 dict = c->u->u_cellvars;
3548 optype = OP_DEREF;
3549 break;
3550 case LOCAL:
3551 if (c->u->u_ste->ste_type == FunctionBlock)
3552 optype = OP_FAST;
3553 break;
3554 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003555 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 optype = OP_GLOBAL;
3557 break;
3558 case GLOBAL_EXPLICIT:
3559 optype = OP_GLOBAL;
3560 break;
3561 default:
3562 /* scope can be 0 */
3563 break;
3564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003567 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 switch (optype) {
3570 case OP_DEREF:
3571 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003572 case Load:
3573 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3574 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003575 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003576 op = STORE_DEREF;
3577 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 case AugLoad:
3579 case AugStore:
3580 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003581 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 case Param:
3583 default:
3584 PyErr_SetString(PyExc_SystemError,
3585 "param invalid for deref variable");
3586 return 0;
3587 }
3588 break;
3589 case OP_FAST:
3590 switch (ctx) {
3591 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003592 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003593 op = STORE_FAST;
3594 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 case Del: op = DELETE_FAST; break;
3596 case AugLoad:
3597 case AugStore:
3598 break;
3599 case Param:
3600 default:
3601 PyErr_SetString(PyExc_SystemError,
3602 "param invalid for local variable");
3603 return 0;
3604 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003605 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 return 1;
3607 case OP_GLOBAL:
3608 switch (ctx) {
3609 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003610 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003611 op = STORE_GLOBAL;
3612 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 case Del: op = DELETE_GLOBAL; break;
3614 case AugLoad:
3615 case AugStore:
3616 break;
3617 case Param:
3618 default:
3619 PyErr_SetString(PyExc_SystemError,
3620 "param invalid for global variable");
3621 return 0;
3622 }
3623 break;
3624 case OP_NAME:
3625 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003626 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003627 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003628 op = STORE_NAME;
3629 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 case Del: op = DELETE_NAME; break;
3631 case AugLoad:
3632 case AugStore:
3633 break;
3634 case Param:
3635 default:
3636 PyErr_SetString(PyExc_SystemError,
3637 "param invalid for name variable");
3638 return 0;
3639 }
3640 break;
3641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 assert(op);
3644 arg = compiler_add_o(c, dict, mangled);
3645 Py_DECREF(mangled);
3646 if (arg < 0)
3647 return 0;
3648 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649}
3650
3651static int
3652compiler_boolop(struct compiler *c, expr_ty e)
3653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003655 int jumpi;
3656 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 assert(e->kind == BoolOp_kind);
3660 if (e->v.BoolOp.op == And)
3661 jumpi = JUMP_IF_FALSE_OR_POP;
3662 else
3663 jumpi = JUMP_IF_TRUE_OR_POP;
3664 end = compiler_new_block(c);
3665 if (end == NULL)
3666 return 0;
3667 s = e->v.BoolOp.values;
3668 n = asdl_seq_LEN(s) - 1;
3669 assert(n >= 0);
3670 for (i = 0; i < n; ++i) {
3671 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3672 ADDOP_JABS(c, jumpi, end);
3673 }
3674 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3675 compiler_use_next_block(c, end);
3676 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677}
3678
3679static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003680starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3681 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003682{
3683 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003684 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 if (n > 2 && are_all_items_const(elts, 0, n)) {
3686 PyObject *folded = PyTuple_New(n);
3687 if (folded == NULL) {
3688 return 0;
3689 }
3690 PyObject *val;
3691 for (i = 0; i < n; i++) {
3692 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3693 Py_INCREF(val);
3694 PyTuple_SET_ITEM(folded, i, val);
3695 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003696 if (tuple) {
3697 ADDOP_LOAD_CONST_NEW(c, folded);
3698 } else {
3699 if (add == SET_ADD) {
3700 Py_SETREF(folded, PyFrozenSet_New(folded));
3701 if (folded == NULL) {
3702 return 0;
3703 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003704 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003705 ADDOP_I(c, build, pushed);
3706 ADDOP_LOAD_CONST_NEW(c, folded);
3707 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003708 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003709 return 1;
3710 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003711
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003712 for (i = 0; i < n; i++) {
3713 expr_ty elt = asdl_seq_GET(elts, i);
3714 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003715 seen_star = 1;
3716 }
3717 }
3718 if (seen_star) {
3719 seen_star = 0;
3720 for (i = 0; i < n; i++) {
3721 expr_ty elt = asdl_seq_GET(elts, i);
3722 if (elt->kind == Starred_kind) {
3723 if (seen_star == 0) {
3724 ADDOP_I(c, build, i+pushed);
3725 seen_star = 1;
3726 }
3727 VISIT(c, expr, elt->v.Starred.value);
3728 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003730 else {
3731 VISIT(c, expr, elt);
3732 if (seen_star) {
3733 ADDOP_I(c, add, 1);
3734 }
3735 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003737 assert(seen_star);
3738 if (tuple) {
3739 ADDOP(c, LIST_TO_TUPLE);
3740 }
3741 }
3742 else {
3743 for (i = 0; i < n; i++) {
3744 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003745 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003746 }
3747 if (tuple) {
3748 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3749 } else {
3750 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 }
3752 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 return 1;
3754}
3755
3756static int
3757assignment_helper(struct compiler *c, asdl_seq *elts)
3758{
3759 Py_ssize_t n = asdl_seq_LEN(elts);
3760 Py_ssize_t i;
3761 int seen_star = 0;
3762 for (i = 0; i < n; i++) {
3763 expr_ty elt = asdl_seq_GET(elts, i);
3764 if (elt->kind == Starred_kind && !seen_star) {
3765 if ((i >= (1 << 8)) ||
3766 (n-i-1 >= (INT_MAX >> 8)))
3767 return compiler_error(c,
3768 "too many expressions in "
3769 "star-unpacking assignment");
3770 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3771 seen_star = 1;
3772 asdl_seq_SET(elts, i, elt->v.Starred.value);
3773 }
3774 else if (elt->kind == Starred_kind) {
3775 return compiler_error(c,
3776 "two starred expressions in assignment");
3777 }
3778 }
3779 if (!seen_star) {
3780 ADDOP_I(c, UNPACK_SEQUENCE, n);
3781 }
3782 VISIT_SEQ(c, expr, elts);
3783 return 1;
3784}
3785
3786static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787compiler_list(struct compiler *c, expr_ty e)
3788{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003790 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003794 return starunpack_helper(c, elts, 0, BUILD_LIST,
3795 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 else
3798 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800}
3801
3802static int
3803compiler_tuple(struct compiler *c, expr_ty e)
3804{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003806 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003807 return assignment_helper(c, elts);
3808 }
3809 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003810 return starunpack_helper(c, elts, 0, BUILD_LIST,
3811 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003812 }
3813 else
3814 VISIT_SEQ(c, expr, elts);
3815 return 1;
3816}
3817
3818static int
3819compiler_set(struct compiler *c, expr_ty e)
3820{
Mark Shannon13bc1392020-01-23 09:25:17 +00003821 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3822 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003823}
3824
3825static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003826are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3827{
3828 Py_ssize_t i;
3829 for (i = begin; i < end; i++) {
3830 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003831 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003832 return 0;
3833 }
3834 return 1;
3835}
3836
3837static int
3838compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3839{
3840 Py_ssize_t i, n = end - begin;
3841 PyObject *keys, *key;
3842 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3843 for (i = begin; i < end; i++) {
3844 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3845 }
3846 keys = PyTuple_New(n);
3847 if (keys == NULL) {
3848 return 0;
3849 }
3850 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003851 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003852 Py_INCREF(key);
3853 PyTuple_SET_ITEM(keys, i - begin, key);
3854 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003855 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003856 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3857 }
3858 else {
3859 for (i = begin; i < end; i++) {
3860 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3861 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3862 }
3863 ADDOP_I(c, BUILD_MAP, n);
3864 }
3865 return 1;
3866}
3867
3868static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003869compiler_dict(struct compiler *c, expr_ty e)
3870{
Victor Stinner976bb402016-03-23 11:36:19 +01003871 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003872 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873 int is_unpacking = 0;
3874 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003875 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003876 elements = 0;
3877 for (i = 0; i < n; i++) {
3878 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003880 if (elements) {
3881 if (!compiler_subdict(c, e, i - elements, i)) {
3882 return 0;
3883 }
3884 if (have_dict) {
3885 ADDOP_I(c, DICT_UPDATE, 1);
3886 }
3887 have_dict = 1;
3888 elements = 0;
3889 }
3890 if (have_dict == 0) {
3891 ADDOP_I(c, BUILD_MAP, 0);
3892 have_dict = 1;
3893 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003894 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003895 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003896 }
3897 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003898 if (elements == 0xFFFF) {
3899 if (!compiler_subdict(c, e, i - elements, i)) {
3900 return 0;
3901 }
3902 if (have_dict) {
3903 ADDOP_I(c, DICT_UPDATE, 1);
3904 }
3905 have_dict = 1;
3906 elements = 0;
3907 }
3908 else {
3909 elements++;
3910 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 }
3912 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003913 if (elements) {
3914 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003915 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003916 }
3917 if (have_dict) {
3918 ADDOP_I(c, DICT_UPDATE, 1);
3919 }
3920 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003921 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003922 if (!have_dict) {
3923 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 }
3925 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003926}
3927
3928static int
3929compiler_compare(struct compiler *c, expr_ty e)
3930{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003931 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003933 if (!check_compare(c, e)) {
3934 return 0;
3935 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003937 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3938 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3939 if (n == 0) {
3940 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003941 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003942 }
3943 else {
3944 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 if (cleanup == NULL)
3946 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003947 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 VISIT(c, expr,
3949 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003950 ADDOP(c, DUP_TOP);
3951 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003952 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003953 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3954 NEXT_BLOCK(c);
3955 }
3956 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003957 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 basicblock *end = compiler_new_block(c);
3959 if (end == NULL)
3960 return 0;
3961 ADDOP_JREL(c, JUMP_FORWARD, end);
3962 compiler_use_next_block(c, cleanup);
3963 ADDOP(c, ROT_TWO);
3964 ADDOP(c, POP_TOP);
3965 compiler_use_next_block(c, end);
3966 }
3967 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003968}
3969
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003970static PyTypeObject *
3971infer_type(expr_ty e)
3972{
3973 switch (e->kind) {
3974 case Tuple_kind:
3975 return &PyTuple_Type;
3976 case List_kind:
3977 case ListComp_kind:
3978 return &PyList_Type;
3979 case Dict_kind:
3980 case DictComp_kind:
3981 return &PyDict_Type;
3982 case Set_kind:
3983 case SetComp_kind:
3984 return &PySet_Type;
3985 case GeneratorExp_kind:
3986 return &PyGen_Type;
3987 case Lambda_kind:
3988 return &PyFunction_Type;
3989 case JoinedStr_kind:
3990 case FormattedValue_kind:
3991 return &PyUnicode_Type;
3992 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003993 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003994 default:
3995 return NULL;
3996 }
3997}
3998
3999static int
4000check_caller(struct compiler *c, expr_ty e)
4001{
4002 switch (e->kind) {
4003 case Constant_kind:
4004 case Tuple_kind:
4005 case List_kind:
4006 case ListComp_kind:
4007 case Dict_kind:
4008 case DictComp_kind:
4009 case Set_kind:
4010 case SetComp_kind:
4011 case GeneratorExp_kind:
4012 case JoinedStr_kind:
4013 case FormattedValue_kind:
4014 return compiler_warn(c, "'%.200s' object is not callable; "
4015 "perhaps you missed a comma?",
4016 infer_type(e)->tp_name);
4017 default:
4018 return 1;
4019 }
4020}
4021
4022static int
4023check_subscripter(struct compiler *c, expr_ty e)
4024{
4025 PyObject *v;
4026
4027 switch (e->kind) {
4028 case Constant_kind:
4029 v = e->v.Constant.value;
4030 if (!(v == Py_None || v == Py_Ellipsis ||
4031 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4032 PyAnySet_Check(v)))
4033 {
4034 return 1;
4035 }
4036 /* fall through */
4037 case Set_kind:
4038 case SetComp_kind:
4039 case GeneratorExp_kind:
4040 case Lambda_kind:
4041 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4042 "perhaps you missed a comma?",
4043 infer_type(e)->tp_name);
4044 default:
4045 return 1;
4046 }
4047}
4048
4049static int
4050check_index(struct compiler *c, expr_ty e, slice_ty s)
4051{
4052 PyObject *v;
4053
4054 if (s->kind != Index_kind) {
4055 return 1;
4056 }
4057 PyTypeObject *index_type = infer_type(s->v.Index.value);
4058 if (index_type == NULL
4059 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4060 || index_type == &PySlice_Type) {
4061 return 1;
4062 }
4063
4064 switch (e->kind) {
4065 case Constant_kind:
4066 v = e->v.Constant.value;
4067 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4068 return 1;
4069 }
4070 /* fall through */
4071 case Tuple_kind:
4072 case List_kind:
4073 case ListComp_kind:
4074 case JoinedStr_kind:
4075 case FormattedValue_kind:
4076 return compiler_warn(c, "%.200s indices must be integers or slices, "
4077 "not %.200s; "
4078 "perhaps you missed a comma?",
4079 infer_type(e)->tp_name,
4080 index_type->tp_name);
4081 default:
4082 return 1;
4083 }
4084}
4085
Zackery Spytz97f5de02019-03-22 01:30:32 -06004086// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004088maybe_optimize_method_call(struct compiler *c, expr_ty e)
4089{
4090 Py_ssize_t argsl, i;
4091 expr_ty meth = e->v.Call.func;
4092 asdl_seq *args = e->v.Call.args;
4093
4094 /* Check that the call node is an attribute access, and that
4095 the call doesn't have keyword parameters. */
4096 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4097 asdl_seq_LEN(e->v.Call.keywords))
4098 return -1;
4099
4100 /* Check that there are no *varargs types of arguments. */
4101 argsl = asdl_seq_LEN(args);
4102 for (i = 0; i < argsl; i++) {
4103 expr_ty elt = asdl_seq_GET(args, i);
4104 if (elt->kind == Starred_kind) {
4105 return -1;
4106 }
4107 }
4108
4109 /* Alright, we can optimize the code. */
4110 VISIT(c, expr, meth->v.Attribute.value);
4111 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4112 VISIT_SEQ(c, expr, e->v.Call.args);
4113 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4114 return 1;
4115}
4116
4117static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004118compiler_call(struct compiler *c, expr_ty e)
4119{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004120 int ret = maybe_optimize_method_call(c, e);
4121 if (ret >= 0) {
4122 return ret;
4123 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004124 if (!check_caller(c, e->v.Call.func)) {
4125 return 0;
4126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 VISIT(c, expr, e->v.Call.func);
4128 return compiler_call_helper(c, 0,
4129 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004130 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004131}
4132
Eric V. Smith235a6f02015-09-19 14:51:32 -04004133static int
4134compiler_joined_str(struct compiler *c, expr_ty e)
4135{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004136 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004137 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4138 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004139 return 1;
4140}
4141
Eric V. Smitha78c7952015-11-03 12:45:05 -05004142/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004143static int
4144compiler_formatted_value(struct compiler *c, expr_ty e)
4145{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004146 /* Our oparg encodes 2 pieces of information: the conversion
4147 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004148
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004149 Convert the conversion char to 3 bits:
4150 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004151 !s : 001 0x1 FVC_STR
4152 !r : 010 0x2 FVC_REPR
4153 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004154
Eric V. Smitha78c7952015-11-03 12:45:05 -05004155 next bit is whether or not we have a format spec:
4156 yes : 100 0x4
4157 no : 000 0x0
4158 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004159
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004160 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004161 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004163 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004164 VISIT(c, expr, e->v.FormattedValue.value);
4165
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004166 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004167 case 's': oparg = FVC_STR; break;
4168 case 'r': oparg = FVC_REPR; break;
4169 case 'a': oparg = FVC_ASCII; break;
4170 case -1: oparg = FVC_NONE; break;
4171 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004172 PyErr_Format(PyExc_SystemError,
4173 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004174 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004175 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004179 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004180 }
4181
Eric V. Smitha78c7952015-11-03 12:45:05 -05004182 /* And push our opcode and oparg */
4183 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004184
Eric V. Smith235a6f02015-09-19 14:51:32 -04004185 return 1;
4186}
4187
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004188static int
4189compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4190{
4191 Py_ssize_t i, n = end - begin;
4192 keyword_ty kw;
4193 PyObject *keys, *key;
4194 assert(n > 0);
4195 if (n > 1) {
4196 for (i = begin; i < end; i++) {
4197 kw = asdl_seq_GET(keywords, i);
4198 VISIT(c, expr, kw->value);
4199 }
4200 keys = PyTuple_New(n);
4201 if (keys == NULL) {
4202 return 0;
4203 }
4204 for (i = begin; i < end; i++) {
4205 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4206 Py_INCREF(key);
4207 PyTuple_SET_ITEM(keys, i - begin, key);
4208 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004209 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004210 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4211 }
4212 else {
4213 /* a for loop only executes once */
4214 for (i = begin; i < end; i++) {
4215 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004216 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004217 VISIT(c, expr, kw->value);
4218 }
4219 ADDOP_I(c, BUILD_MAP, n);
4220 }
4221 return 1;
4222}
4223
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004224/* shared code between compiler_call and compiler_class */
4225static int
4226compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004227 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004228 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004229 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004230{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004231 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004232
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004233 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004234 nkwelts = asdl_seq_LEN(keywords);
4235
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004236 for (i = 0; i < nelts; i++) {
4237 expr_ty elt = asdl_seq_GET(args, i);
4238 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004239 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004240 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004241 }
4242 for (i = 0; i < nkwelts; i++) {
4243 keyword_ty kw = asdl_seq_GET(keywords, i);
4244 if (kw->arg == NULL) {
4245 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004247 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004248
Mark Shannon13bc1392020-01-23 09:25:17 +00004249 /* No * or ** args, so can use faster calling sequence */
4250 for (i = 0; i < nelts; i++) {
4251 expr_ty elt = asdl_seq_GET(args, i);
4252 assert(elt->kind != Starred_kind);
4253 VISIT(c, expr, elt);
4254 }
4255 if (nkwelts) {
4256 PyObject *names;
4257 VISIT_SEQ(c, keyword, keywords);
4258 names = PyTuple_New(nkwelts);
4259 if (names == NULL) {
4260 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004261 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004262 for (i = 0; i < nkwelts; i++) {
4263 keyword_ty kw = asdl_seq_GET(keywords, i);
4264 Py_INCREF(kw->arg);
4265 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004266 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004267 ADDOP_LOAD_CONST_NEW(c, names);
4268 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4269 return 1;
4270 }
4271 else {
4272 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4273 return 1;
4274 }
4275
4276ex_call:
4277
4278 /* Do positional arguments. */
4279 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4280 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4281 }
4282 else if (starunpack_helper(c, args, n, BUILD_LIST,
4283 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4284 return 0;
4285 }
4286 /* Then keyword arguments */
4287 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004288 /* Has a new dict been pushed */
4289 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004290
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004291 nseen = 0; /* the number of keyword arguments on the stack following */
4292 for (i = 0; i < nkwelts; i++) {
4293 keyword_ty kw = asdl_seq_GET(keywords, i);
4294 if (kw->arg == NULL) {
4295 /* A keyword argument unpacking. */
4296 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004297 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004298 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004299 }
4300 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004301 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004302 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004303 if (!have_dict) {
4304 ADDOP_I(c, BUILD_MAP, 0);
4305 have_dict = 1;
4306 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004307 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004308 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004309 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004310 else {
4311 nseen++;
4312 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004313 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004314 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004315 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004316 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004317 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004318 }
4319 if (have_dict) {
4320 ADDOP_I(c, DICT_MERGE, 1);
4321 }
4322 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004323 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004324 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004326 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4327 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328}
4329
Nick Coghlan650f0d02007-04-15 12:05:43 +00004330
4331/* List and set comprehensions and generator expressions work by creating a
4332 nested function to perform the actual iteration. This means that the
4333 iteration variables don't leak into the current scope.
4334 The defined function is called immediately following its definition, with the
4335 result of that call being the result of the expression.
4336 The LC/SC version returns the populated container, while the GE version is
4337 flagged in symtable.c as a generator, so it returns the generator object
4338 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004339
4340 Possible cleanups:
4341 - iterate over the generator sequence instead of using recursion
4342*/
4343
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346compiler_comprehension_generator(struct compiler *c,
4347 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004348 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004350{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004351 comprehension_ty gen;
4352 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4353 if (gen->is_async) {
4354 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004355 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004356 } else {
4357 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004358 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004359 }
4360}
4361
4362static int
4363compiler_sync_comprehension_generator(struct compiler *c,
4364 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004365 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004366 expr_ty elt, expr_ty val, int type)
4367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 /* generate code for the iterator, then each of the ifs,
4369 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 comprehension_ty gen;
4372 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004373 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 start = compiler_new_block(c);
4376 skip = compiler_new_block(c);
4377 if_cleanup = compiler_new_block(c);
4378 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4381 anchor == NULL)
4382 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 if (gen_index == 0) {
4387 /* Receive outermost iter as an implicit argument */
4388 c->u->u_argcount = 1;
4389 ADDOP_I(c, LOAD_FAST, 0);
4390 }
4391 else {
4392 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004393 /* Fast path for the temporary variable assignment idiom:
4394 for y in [f(x)]
4395 */
4396 asdl_seq *elts;
4397 switch (gen->iter->kind) {
4398 case List_kind:
4399 elts = gen->iter->v.List.elts;
4400 break;
4401 case Tuple_kind:
4402 elts = gen->iter->v.Tuple.elts;
4403 break;
4404 default:
4405 elts = NULL;
4406 }
4407 if (asdl_seq_LEN(elts) == 1) {
4408 expr_ty elt = asdl_seq_GET(elts, 0);
4409 if (elt->kind != Starred_kind) {
4410 VISIT(c, expr, elt);
4411 start = NULL;
4412 }
4413 }
4414 if (start) {
4415 VISIT(c, expr, gen->iter);
4416 ADDOP(c, GET_ITER);
4417 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004419 if (start) {
4420 depth++;
4421 compiler_use_next_block(c, start);
4422 ADDOP_JREL(c, FOR_ITER, anchor);
4423 NEXT_BLOCK(c);
4424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 /* XXX this needs to be cleaned up...a lot! */
4428 n = asdl_seq_LEN(gen->ifs);
4429 for (i = 0; i < n; i++) {
4430 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004431 if (!compiler_jump_if(c, e, if_cleanup, 0))
4432 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 NEXT_BLOCK(c);
4434 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 if (++gen_index < asdl_seq_LEN(generators))
4437 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004438 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 elt, val, type))
4440 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* only append after the last for generator */
4443 if (gen_index >= asdl_seq_LEN(generators)) {
4444 /* comprehension specific code */
4445 switch (type) {
4446 case COMP_GENEXP:
4447 VISIT(c, expr, elt);
4448 ADDOP(c, YIELD_VALUE);
4449 ADDOP(c, POP_TOP);
4450 break;
4451 case COMP_LISTCOMP:
4452 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004453 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 break;
4455 case COMP_SETCOMP:
4456 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004457 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 break;
4459 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004460 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004463 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004464 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 break;
4466 default:
4467 return 0;
4468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 compiler_use_next_block(c, skip);
4471 }
4472 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004473 if (start) {
4474 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4475 compiler_use_next_block(c, anchor);
4476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477
4478 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004479}
4480
4481static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004482compiler_async_comprehension_generator(struct compiler *c,
4483 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004484 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004485 expr_ty elt, expr_ty val, int type)
4486{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004487 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004488 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004490 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004493
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004494 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 return 0;
4496 }
4497
4498 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4499
4500 if (gen_index == 0) {
4501 /* Receive outermost iter as an implicit argument */
4502 c->u->u_argcount = 1;
4503 ADDOP_I(c, LOAD_FAST, 0);
4504 }
4505 else {
4506 /* Sub-iter - calculate on the fly */
4507 VISIT(c, expr, gen->iter);
4508 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509 }
4510
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004511 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004513 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004515 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004517 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004518 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004519
4520 n = asdl_seq_LEN(gen->ifs);
4521 for (i = 0; i < n; i++) {
4522 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004523 if (!compiler_jump_if(c, e, if_cleanup, 0))
4524 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 NEXT_BLOCK(c);
4526 }
4527
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004528 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 if (++gen_index < asdl_seq_LEN(generators))
4530 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004531 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 elt, val, type))
4533 return 0;
4534
4535 /* only append after the last for generator */
4536 if (gen_index >= asdl_seq_LEN(generators)) {
4537 /* comprehension specific code */
4538 switch (type) {
4539 case COMP_GENEXP:
4540 VISIT(c, expr, elt);
4541 ADDOP(c, YIELD_VALUE);
4542 ADDOP(c, POP_TOP);
4543 break;
4544 case COMP_LISTCOMP:
4545 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004546 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004547 break;
4548 case COMP_SETCOMP:
4549 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004550 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551 break;
4552 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004553 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004556 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004557 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558 break;
4559 default:
4560 return 0;
4561 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 }
4563 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004564 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4565
4566 compiler_use_next_block(c, except);
4567 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568
4569 return 1;
4570}
4571
4572static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004573compiler_comprehension(struct compiler *c, expr_ty e, int type,
4574 identifier name, asdl_seq *generators, expr_ty elt,
4575 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004579 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004580 int is_async_function = c->u->u_ste->ste_coroutine;
4581 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004582
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004584
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004585 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4586 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004587 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589 }
4590
4591 is_async_generator = c->u->u_ste->ste_coroutine;
4592
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004593 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004594 compiler_error(c, "asynchronous comprehension outside of "
4595 "an asynchronous function");
4596 goto error_in_scope;
4597 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 if (type != COMP_GENEXP) {
4600 int op;
4601 switch (type) {
4602 case COMP_LISTCOMP:
4603 op = BUILD_LIST;
4604 break;
4605 case COMP_SETCOMP:
4606 op = BUILD_SET;
4607 break;
4608 case COMP_DICTCOMP:
4609 op = BUILD_MAP;
4610 break;
4611 default:
4612 PyErr_Format(PyExc_SystemError,
4613 "unknown comprehension type %d", type);
4614 goto error_in_scope;
4615 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 ADDOP_I(c, op, 0);
4618 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004619
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004620 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 val, type))
4622 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 if (type != COMP_GENEXP) {
4625 ADDOP(c, RETURN_VALUE);
4626 }
4627
4628 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004629 qualname = c->u->u_qualname;
4630 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004632 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 goto error;
4634
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004635 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004637 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 Py_DECREF(co);
4639
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004640 VISIT(c, expr, outermost->iter);
4641
4642 if (outermost->is_async) {
4643 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004644 } else {
4645 ADDOP(c, GET_ITER);
4646 }
4647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004649
4650 if (is_async_generator && type != COMP_GENEXP) {
4651 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004652 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004653 ADDOP(c, YIELD_FROM);
4654 }
4655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004657error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004659error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004660 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 Py_XDECREF(co);
4662 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004663}
4664
4665static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004666compiler_genexp(struct compiler *c, expr_ty e)
4667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 static identifier name;
4669 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004670 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 if (!name)
4672 return 0;
4673 }
4674 assert(e->kind == GeneratorExp_kind);
4675 return compiler_comprehension(c, e, COMP_GENEXP, name,
4676 e->v.GeneratorExp.generators,
4677 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004678}
4679
4680static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004681compiler_listcomp(struct compiler *c, expr_ty e)
4682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 static identifier name;
4684 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004685 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 if (!name)
4687 return 0;
4688 }
4689 assert(e->kind == ListComp_kind);
4690 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4691 e->v.ListComp.generators,
4692 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004693}
4694
4695static int
4696compiler_setcomp(struct compiler *c, expr_ty e)
4697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 static identifier name;
4699 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004700 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 if (!name)
4702 return 0;
4703 }
4704 assert(e->kind == SetComp_kind);
4705 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4706 e->v.SetComp.generators,
4707 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004708}
4709
4710
4711static int
4712compiler_dictcomp(struct compiler *c, expr_ty e)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 static identifier name;
4715 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004716 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (!name)
4718 return 0;
4719 }
4720 assert(e->kind == DictComp_kind);
4721 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4722 e->v.DictComp.generators,
4723 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004724}
4725
4726
4727static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728compiler_visit_keyword(struct compiler *c, keyword_ty k)
4729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 VISIT(c, expr, k->value);
4731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004732}
4733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004735 whether they are true or false.
4736
4737 Return values: 1 for true, 0 for false, -1 for non-constant.
4738 */
4739
4740static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004741expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004742{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004743 if (e->kind == Constant_kind) {
4744 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004745 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004746 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004747}
4748
Mark Shannonfee55262019-11-21 09:11:43 +00004749static int
4750compiler_with_except_finish(struct compiler *c) {
4751 basicblock *exit;
4752 exit = compiler_new_block(c);
4753 if (exit == NULL)
4754 return 0;
4755 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4756 ADDOP(c, RERAISE);
4757 compiler_use_next_block(c, exit);
4758 ADDOP(c, POP_TOP);
4759 ADDOP(c, POP_TOP);
4760 ADDOP(c, POP_TOP);
4761 ADDOP(c, POP_EXCEPT);
4762 ADDOP(c, POP_TOP);
4763 return 1;
4764}
Yury Selivanov75445082015-05-11 22:57:16 -04004765
4766/*
4767 Implements the async with statement.
4768
4769 The semantics outlined in that PEP are as follows:
4770
4771 async with EXPR as VAR:
4772 BLOCK
4773
4774 It is implemented roughly as:
4775
4776 context = EXPR
4777 exit = context.__aexit__ # not calling it
4778 value = await context.__aenter__()
4779 try:
4780 VAR = value # if VAR present in the syntax
4781 BLOCK
4782 finally:
4783 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004784 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004785 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004786 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004787 if not (await exit(*exc)):
4788 raise
4789 */
4790static int
4791compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4792{
Mark Shannonfee55262019-11-21 09:11:43 +00004793 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004794 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4795
4796 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004797 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4798 c->u->u_ste->ste_coroutine = 1;
4799 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004800 return compiler_error(c, "'async with' outside async function");
4801 }
Yury Selivanov75445082015-05-11 22:57:16 -04004802
4803 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004804 final = compiler_new_block(c);
4805 exit = compiler_new_block(c);
4806 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004807 return 0;
4808
4809 /* Evaluate EXPR */
4810 VISIT(c, expr, item->context_expr);
4811
4812 ADDOP(c, BEFORE_ASYNC_WITH);
4813 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004814 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004815 ADDOP(c, YIELD_FROM);
4816
Mark Shannonfee55262019-11-21 09:11:43 +00004817 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004818
4819 /* SETUP_ASYNC_WITH pushes a finally block. */
4820 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004821 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004822 return 0;
4823 }
4824
4825 if (item->optional_vars) {
4826 VISIT(c, expr, item->optional_vars);
4827 }
4828 else {
4829 /* Discard result from context.__aenter__() */
4830 ADDOP(c, POP_TOP);
4831 }
4832
4833 pos++;
4834 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4835 /* BLOCK code */
4836 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4837 else if (!compiler_async_with(c, s, pos))
4838 return 0;
4839
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004840 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004841 ADDOP(c, POP_BLOCK);
4842 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004843
Mark Shannonfee55262019-11-21 09:11:43 +00004844 /* For successful outcome:
4845 * call __exit__(None, None, None)
4846 */
4847 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004848 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004849 ADDOP(c, GET_AWAITABLE);
4850 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4851 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004852
Mark Shannonfee55262019-11-21 09:11:43 +00004853 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004854
Mark Shannonfee55262019-11-21 09:11:43 +00004855 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4856
4857 /* For exceptional outcome: */
4858 compiler_use_next_block(c, final);
4859
4860 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004861 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004862 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004863 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004864 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004865
Mark Shannonfee55262019-11-21 09:11:43 +00004866compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004867 return 1;
4868}
4869
4870
Guido van Rossumc2e20742006-02-27 22:32:47 +00004871/*
4872 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004873 with EXPR as VAR:
4874 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004875 is implemented as:
4876 <code for EXPR>
4877 SETUP_WITH E
4878 <code to store to VAR> or POP_TOP
4879 <code for BLOCK>
4880 LOAD_CONST (None, None, None)
4881 CALL_FUNCTION_EX 0
4882 JUMP_FORWARD EXIT
4883 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4884 POP_JUMP_IF_TRUE T:
4885 RERAISE
4886 T: POP_TOP * 3 (remove exception from stack)
4887 POP_EXCEPT
4888 POP_TOP
4889 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890 */
Mark Shannonfee55262019-11-21 09:11:43 +00004891
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004893compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004894{
Mark Shannonfee55262019-11-21 09:11:43 +00004895 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004896 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004897
4898 assert(s->kind == With_kind);
4899
Guido van Rossumc2e20742006-02-27 22:32:47 +00004900 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004901 final = compiler_new_block(c);
4902 exit = compiler_new_block(c);
4903 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004904 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004905
Thomas Wouters477c8d52006-05-27 19:21:47 +00004906 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004907 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004908 /* Will push bound __exit__ */
4909 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004911 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004912 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004913 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004914 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004915 }
4916
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004917 if (item->optional_vars) {
4918 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004919 }
4920 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004922 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004923 }
4924
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004925 pos++;
4926 if (pos == asdl_seq_LEN(s->v.With.items))
4927 /* BLOCK code */
4928 VISIT_SEQ(c, stmt, s->v.With.body)
4929 else if (!compiler_with(c, s, pos))
4930 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004931
Guido van Rossumc2e20742006-02-27 22:32:47 +00004932 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004933 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004934
Mark Shannonfee55262019-11-21 09:11:43 +00004935 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004936
Mark Shannonfee55262019-11-21 09:11:43 +00004937 /* For successful outcome:
4938 * call __exit__(None, None, None)
4939 */
4940 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004941 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004942 ADDOP(c, POP_TOP);
4943 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004944
Mark Shannonfee55262019-11-21 09:11:43 +00004945 /* For exceptional outcome: */
4946 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004947
Mark Shannonfee55262019-11-21 09:11:43 +00004948 ADDOP(c, WITH_EXCEPT_START);
4949 compiler_with_except_finish(c);
4950
4951 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004952 return 1;
4953}
4954
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004955static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004956compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004959 case NamedExpr_kind:
4960 VISIT(c, expr, e->v.NamedExpr.value);
4961 ADDOP(c, DUP_TOP);
4962 VISIT(c, expr, e->v.NamedExpr.target);
4963 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 case BoolOp_kind:
4965 return compiler_boolop(c, e);
4966 case BinOp_kind:
4967 VISIT(c, expr, e->v.BinOp.left);
4968 VISIT(c, expr, e->v.BinOp.right);
4969 ADDOP(c, binop(c, e->v.BinOp.op));
4970 break;
4971 case UnaryOp_kind:
4972 VISIT(c, expr, e->v.UnaryOp.operand);
4973 ADDOP(c, unaryop(e->v.UnaryOp.op));
4974 break;
4975 case Lambda_kind:
4976 return compiler_lambda(c, e);
4977 case IfExp_kind:
4978 return compiler_ifexp(c, e);
4979 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004980 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004982 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 case GeneratorExp_kind:
4984 return compiler_genexp(c, e);
4985 case ListComp_kind:
4986 return compiler_listcomp(c, e);
4987 case SetComp_kind:
4988 return compiler_setcomp(c, e);
4989 case DictComp_kind:
4990 return compiler_dictcomp(c, e);
4991 case Yield_kind:
4992 if (c->u->u_ste->ste_type != FunctionBlock)
4993 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004994 if (e->v.Yield.value) {
4995 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 }
4997 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004998 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005000 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005002 case YieldFrom_kind:
5003 if (c->u->u_ste->ste_type != FunctionBlock)
5004 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005005
5006 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5007 return compiler_error(c, "'yield from' inside async function");
5008
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005009 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005010 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005011 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005012 ADDOP(c, YIELD_FROM);
5013 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005014 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005015 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
5016 if (c->u->u_ste->ste_type != FunctionBlock){
5017 return compiler_error(c, "'await' outside function");
5018 }
Yury Selivanov75445082015-05-11 22:57:16 -04005019
Victor Stinner331a6a52019-05-27 16:39:22 +02005020 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005021 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5022 return compiler_error(c, "'await' outside async function");
5023 }
5024 }
Yury Selivanov75445082015-05-11 22:57:16 -04005025
5026 VISIT(c, expr, e->v.Await.value);
5027 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005028 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005029 ADDOP(c, YIELD_FROM);
5030 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 case Compare_kind:
5032 return compiler_compare(c, e);
5033 case Call_kind:
5034 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005035 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005036 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005037 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005038 case JoinedStr_kind:
5039 return compiler_joined_str(c, e);
5040 case FormattedValue_kind:
5041 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 /* The following exprs can be assignment targets. */
5043 case Attribute_kind:
5044 if (e->v.Attribute.ctx != AugStore)
5045 VISIT(c, expr, e->v.Attribute.value);
5046 switch (e->v.Attribute.ctx) {
5047 case AugLoad:
5048 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005049 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 case Load:
5051 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5052 break;
5053 case AugStore:
5054 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005055 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 case Store:
5057 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5058 break;
5059 case Del:
5060 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5061 break;
5062 case Param:
5063 default:
5064 PyErr_SetString(PyExc_SystemError,
5065 "param invalid in attribute expression");
5066 return 0;
5067 }
5068 break;
5069 case Subscript_kind:
5070 switch (e->v.Subscript.ctx) {
5071 case AugLoad:
5072 VISIT(c, expr, e->v.Subscript.value);
5073 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5074 break;
5075 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005076 if (!check_subscripter(c, e->v.Subscript.value)) {
5077 return 0;
5078 }
5079 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5080 return 0;
5081 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 VISIT(c, expr, e->v.Subscript.value);
5083 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5084 break;
5085 case AugStore:
5086 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5087 break;
5088 case Store:
5089 VISIT(c, expr, e->v.Subscript.value);
5090 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5091 break;
5092 case Del:
5093 VISIT(c, expr, e->v.Subscript.value);
5094 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5095 break;
5096 case Param:
5097 default:
5098 PyErr_SetString(PyExc_SystemError,
5099 "param invalid in subscript expression");
5100 return 0;
5101 }
5102 break;
5103 case Starred_kind:
5104 switch (e->v.Starred.ctx) {
5105 case Store:
5106 /* In all legitimate cases, the Starred node was already replaced
5107 * by compiler_list/compiler_tuple. XXX: is that okay? */
5108 return compiler_error(c,
5109 "starred assignment target must be in a list or tuple");
5110 default:
5111 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005112 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 case Name_kind:
5115 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5116 /* child nodes of List and Tuple will have expr_context set */
5117 case List_kind:
5118 return compiler_list(c, e);
5119 case Tuple_kind:
5120 return compiler_tuple(c, e);
5121 }
5122 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123}
5124
5125static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005126compiler_visit_expr(struct compiler *c, expr_ty e)
5127{
5128 /* If expr e has a different line number than the last expr/stmt,
5129 set a new line number for the next instruction.
5130 */
5131 int old_lineno = c->u->u_lineno;
5132 int old_col_offset = c->u->u_col_offset;
5133 if (e->lineno != c->u->u_lineno) {
5134 c->u->u_lineno = e->lineno;
5135 c->u->u_lineno_set = 0;
5136 }
5137 /* Updating the column offset is always harmless. */
5138 c->u->u_col_offset = e->col_offset;
5139
5140 int res = compiler_visit_expr1(c, e);
5141
5142 if (old_lineno != c->u->u_lineno) {
5143 c->u->u_lineno = old_lineno;
5144 c->u->u_lineno_set = 0;
5145 }
5146 c->u->u_col_offset = old_col_offset;
5147 return res;
5148}
5149
5150static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005151compiler_augassign(struct compiler *c, stmt_ty s)
5152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 expr_ty e = s->v.AugAssign.target;
5154 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 switch (e->kind) {
5159 case Attribute_kind:
5160 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005161 AugLoad, e->lineno, e->col_offset,
5162 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005163 if (auge == NULL)
5164 return 0;
5165 VISIT(c, expr, auge);
5166 VISIT(c, expr, s->v.AugAssign.value);
5167 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5168 auge->v.Attribute.ctx = AugStore;
5169 VISIT(c, expr, auge);
5170 break;
5171 case Subscript_kind:
5172 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005173 AugLoad, e->lineno, e->col_offset,
5174 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 if (auge == NULL)
5176 return 0;
5177 VISIT(c, expr, auge);
5178 VISIT(c, expr, s->v.AugAssign.value);
5179 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5180 auge->v.Subscript.ctx = AugStore;
5181 VISIT(c, expr, auge);
5182 break;
5183 case Name_kind:
5184 if (!compiler_nameop(c, e->v.Name.id, Load))
5185 return 0;
5186 VISIT(c, expr, s->v.AugAssign.value);
5187 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5188 return compiler_nameop(c, e->v.Name.id, Store);
5189 default:
5190 PyErr_Format(PyExc_SystemError,
5191 "invalid node type (%d) for augmented assignment",
5192 e->kind);
5193 return 0;
5194 }
5195 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005196}
5197
5198static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005199check_ann_expr(struct compiler *c, expr_ty e)
5200{
5201 VISIT(c, expr, e);
5202 ADDOP(c, POP_TOP);
5203 return 1;
5204}
5205
5206static int
5207check_annotation(struct compiler *c, stmt_ty s)
5208{
5209 /* Annotations are only evaluated in a module or class. */
5210 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5211 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5212 return check_ann_expr(c, s->v.AnnAssign.annotation);
5213 }
5214 return 1;
5215}
5216
5217static int
5218check_ann_slice(struct compiler *c, slice_ty sl)
5219{
5220 switch(sl->kind) {
5221 case Index_kind:
5222 return check_ann_expr(c, sl->v.Index.value);
5223 case Slice_kind:
5224 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5225 return 0;
5226 }
5227 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5228 return 0;
5229 }
5230 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5231 return 0;
5232 }
5233 break;
5234 default:
5235 PyErr_SetString(PyExc_SystemError,
5236 "unexpected slice kind");
5237 return 0;
5238 }
5239 return 1;
5240}
5241
5242static int
5243check_ann_subscr(struct compiler *c, slice_ty sl)
5244{
5245 /* We check that everything in a subscript is defined at runtime. */
5246 Py_ssize_t i, n;
5247
5248 switch (sl->kind) {
5249 case Index_kind:
5250 case Slice_kind:
5251 if (!check_ann_slice(c, sl)) {
5252 return 0;
5253 }
5254 break;
5255 case ExtSlice_kind:
5256 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5257 for (i = 0; i < n; i++) {
5258 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5259 switch (subsl->kind) {
5260 case Index_kind:
5261 case Slice_kind:
5262 if (!check_ann_slice(c, subsl)) {
5263 return 0;
5264 }
5265 break;
5266 case ExtSlice_kind:
5267 default:
5268 PyErr_SetString(PyExc_SystemError,
5269 "extended slice invalid in nested slice");
5270 return 0;
5271 }
5272 }
5273 break;
5274 default:
5275 PyErr_Format(PyExc_SystemError,
5276 "invalid subscript kind %d", sl->kind);
5277 return 0;
5278 }
5279 return 1;
5280}
5281
5282static int
5283compiler_annassign(struct compiler *c, stmt_ty s)
5284{
5285 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005286 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005287
5288 assert(s->kind == AnnAssign_kind);
5289
5290 /* We perform the actual assignment first. */
5291 if (s->v.AnnAssign.value) {
5292 VISIT(c, expr, s->v.AnnAssign.value);
5293 VISIT(c, expr, targ);
5294 }
5295 switch (targ->kind) {
5296 case Name_kind:
5297 /* If we have a simple name in a module or class, store annotation. */
5298 if (s->v.AnnAssign.simple &&
5299 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5300 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005301 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5302 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5303 }
5304 else {
5305 VISIT(c, expr, s->v.AnnAssign.annotation);
5306 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005307 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005308 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005309 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005310 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005311 }
5312 break;
5313 case Attribute_kind:
5314 if (!s->v.AnnAssign.value &&
5315 !check_ann_expr(c, targ->v.Attribute.value)) {
5316 return 0;
5317 }
5318 break;
5319 case Subscript_kind:
5320 if (!s->v.AnnAssign.value &&
5321 (!check_ann_expr(c, targ->v.Subscript.value) ||
5322 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5323 return 0;
5324 }
5325 break;
5326 default:
5327 PyErr_Format(PyExc_SystemError,
5328 "invalid node type (%d) for annotated assignment",
5329 targ->kind);
5330 return 0;
5331 }
5332 /* Annotation is evaluated last. */
5333 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5334 return 0;
5335 }
5336 return 1;
5337}
5338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005339/* Raises a SyntaxError and returns 0.
5340 If something goes wrong, a different exception may be raised.
5341*/
5342
5343static int
5344compiler_error(struct compiler *c, const char *errstr)
5345{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005346 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005348
Victor Stinner14e461d2013-08-26 22:28:21 +02005349 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 if (!loc) {
5351 Py_INCREF(Py_None);
5352 loc = Py_None;
5353 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005354 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005355 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 if (!u)
5357 goto exit;
5358 v = Py_BuildValue("(zO)", errstr, u);
5359 if (!v)
5360 goto exit;
5361 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005362 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 Py_DECREF(loc);
5364 Py_XDECREF(u);
5365 Py_XDECREF(v);
5366 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005367}
5368
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005369/* Emits a SyntaxWarning and returns 1 on success.
5370 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5371 and returns 0.
5372*/
5373static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005374compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005375{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005376 va_list vargs;
5377#ifdef HAVE_STDARG_PROTOTYPES
5378 va_start(vargs, format);
5379#else
5380 va_start(vargs);
5381#endif
5382 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5383 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005384 if (msg == NULL) {
5385 return 0;
5386 }
5387 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5388 c->u->u_lineno, NULL, NULL) < 0)
5389 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005390 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005391 /* Replace the SyntaxWarning exception with a SyntaxError
5392 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005393 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005394 assert(PyUnicode_AsUTF8(msg) != NULL);
5395 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005396 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005397 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005398 return 0;
5399 }
5400 Py_DECREF(msg);
5401 return 1;
5402}
5403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405compiler_handle_subscr(struct compiler *c, const char *kind,
5406 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 /* XXX this code is duplicated */
5411 switch (ctx) {
5412 case AugLoad: /* fall through to Load */
5413 case Load: op = BINARY_SUBSCR; break;
5414 case AugStore:/* fall through to Store */
5415 case Store: op = STORE_SUBSCR; break;
5416 case Del: op = DELETE_SUBSCR; break;
5417 case Param:
5418 PyErr_Format(PyExc_SystemError,
5419 "invalid %s kind %d in subscript\n",
5420 kind, ctx);
5421 return 0;
5422 }
5423 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005424 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 }
5426 else if (ctx == AugStore) {
5427 ADDOP(c, ROT_THREE);
5428 }
5429 ADDOP(c, op);
5430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431}
5432
5433static int
5434compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 int n = 2;
5437 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 /* only handles the cases where BUILD_SLICE is emitted */
5440 if (s->v.Slice.lower) {
5441 VISIT(c, expr, s->v.Slice.lower);
5442 }
5443 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005444 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 if (s->v.Slice.upper) {
5448 VISIT(c, expr, s->v.Slice.upper);
5449 }
5450 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005451 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 }
5453
5454 if (s->v.Slice.step) {
5455 n++;
5456 VISIT(c, expr, s->v.Slice.step);
5457 }
5458 ADDOP_I(c, BUILD_SLICE, n);
5459 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005460}
5461
5462static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005463compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5464 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 switch (s->kind) {
5467 case Slice_kind:
5468 return compiler_slice(c, s, ctx);
5469 case Index_kind:
5470 VISIT(c, expr, s->v.Index.value);
5471 break;
5472 case ExtSlice_kind:
5473 default:
5474 PyErr_SetString(PyExc_SystemError,
5475 "extended slice invalid in nested slice");
5476 return 0;
5477 }
5478 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479}
5480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005481static int
5482compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5483{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005484 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 switch (s->kind) {
5486 case Index_kind:
5487 kindname = "index";
5488 if (ctx != AugStore) {
5489 VISIT(c, expr, s->v.Index.value);
5490 }
5491 break;
5492 case Slice_kind:
5493 kindname = "slice";
5494 if (ctx != AugStore) {
5495 if (!compiler_slice(c, s, ctx))
5496 return 0;
5497 }
5498 break;
5499 case ExtSlice_kind:
5500 kindname = "extended slice";
5501 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005502 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 for (i = 0; i < n; i++) {
5504 slice_ty sub = (slice_ty)asdl_seq_GET(
5505 s->v.ExtSlice.dims, i);
5506 if (!compiler_visit_nested_slice(c, sub, ctx))
5507 return 0;
5508 }
5509 ADDOP_I(c, BUILD_TUPLE, n);
5510 }
5511 break;
5512 default:
5513 PyErr_Format(PyExc_SystemError,
5514 "invalid subscript kind %d", s->kind);
5515 return 0;
5516 }
5517 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005518}
5519
Thomas Wouters89f507f2006-12-13 04:49:30 +00005520/* End of the compiler section, beginning of the assembler section */
5521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005523 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005524
5525 XXX must handle implicit jumps from one block to next
5526*/
5527
Thomas Wouters89f507f2006-12-13 04:49:30 +00005528struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 PyObject *a_bytecode; /* string containing bytecode */
5530 int a_offset; /* offset into bytecode */
5531 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005532 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 PyObject *a_lnotab; /* string containing lnotab */
5534 int a_lnotab_off; /* offset into lnotab */
5535 int a_lineno; /* last lineno of emitted instruction */
5536 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005537};
5538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005539static void
T. Wouters99b54d62019-09-12 07:05:33 -07005540dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005541{
T. Wouters99b54d62019-09-12 07:05:33 -07005542 int i, j;
5543
5544 /* Get rid of recursion for normal control flow.
5545 Since the number of blocks is limited, unused space in a_postorder
5546 (from a_nblocks to end) can be used as a stack for still not ordered
5547 blocks. */
5548 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005549 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005550 assert(a->a_nblocks < j);
5551 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 }
T. Wouters99b54d62019-09-12 07:05:33 -07005553 while (j < end) {
5554 b = a->a_postorder[j++];
5555 for (i = 0; i < b->b_iused; i++) {
5556 struct instr *instr = &b->b_instr[i];
5557 if (instr->i_jrel || instr->i_jabs)
5558 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005559 }
T. Wouters99b54d62019-09-12 07:05:33 -07005560 assert(a->a_nblocks < j);
5561 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005563}
5564
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005565Py_LOCAL_INLINE(void)
5566stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005567{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005568 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005569 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005570 assert(b->b_startdepth < 0);
5571 b->b_startdepth = depth;
5572 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005574}
5575
5576/* Find the flow path that needs the largest stack. We assume that
5577 * cycles in the flow graph have no net effect on the stack depth.
5578 */
5579static int
5580stackdepth(struct compiler *c)
5581{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005582 basicblock *b, *entryblock = NULL;
5583 basicblock **stack, **sp;
5584 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 b->b_startdepth = INT_MIN;
5587 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005588 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 }
5590 if (!entryblock)
5591 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005592 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5593 if (!stack) {
5594 PyErr_NoMemory();
5595 return -1;
5596 }
5597
5598 sp = stack;
5599 stackdepth_push(&sp, entryblock, 0);
5600 while (sp != stack) {
5601 b = *--sp;
5602 int depth = b->b_startdepth;
5603 assert(depth >= 0);
5604 basicblock *next = b->b_next;
5605 for (int i = 0; i < b->b_iused; i++) {
5606 struct instr *instr = &b->b_instr[i];
5607 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5608 if (effect == PY_INVALID_STACK_EFFECT) {
5609 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5610 Py_FatalError("PyCompile_OpcodeStackEffect()");
5611 }
5612 int new_depth = depth + effect;
5613 if (new_depth > maxdepth) {
5614 maxdepth = new_depth;
5615 }
5616 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5617 if (instr->i_jrel || instr->i_jabs) {
5618 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5619 assert(effect != PY_INVALID_STACK_EFFECT);
5620 int target_depth = depth + effect;
5621 if (target_depth > maxdepth) {
5622 maxdepth = target_depth;
5623 }
5624 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005625 stackdepth_push(&sp, instr->i_target, target_depth);
5626 }
5627 depth = new_depth;
5628 if (instr->i_opcode == JUMP_ABSOLUTE ||
5629 instr->i_opcode == JUMP_FORWARD ||
5630 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005631 instr->i_opcode == RAISE_VARARGS ||
5632 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005633 {
5634 /* remaining code is dead */
5635 next = NULL;
5636 break;
5637 }
5638 }
5639 if (next != NULL) {
5640 stackdepth_push(&sp, next, depth);
5641 }
5642 }
5643 PyObject_Free(stack);
5644 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005645}
5646
5647static int
5648assemble_init(struct assembler *a, int nblocks, int firstlineno)
5649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 memset(a, 0, sizeof(struct assembler));
5651 a->a_lineno = firstlineno;
5652 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5653 if (!a->a_bytecode)
5654 return 0;
5655 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5656 if (!a->a_lnotab)
5657 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005658 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 PyErr_NoMemory();
5660 return 0;
5661 }
T. Wouters99b54d62019-09-12 07:05:33 -07005662 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005664 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005665 PyErr_NoMemory();
5666 return 0;
5667 }
5668 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005669}
5670
5671static void
5672assemble_free(struct assembler *a)
5673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 Py_XDECREF(a->a_bytecode);
5675 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005676 if (a->a_postorder)
5677 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005678}
5679
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005680static int
5681blocksize(basicblock *b)
5682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 int i;
5684 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005687 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005689}
5690
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005691/* Appends a pair to the end of the line number table, a_lnotab, representing
5692 the instruction's bytecode offset and line number. See
5693 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005694
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005695static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005696assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005699 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005701
Serhiy Storchakaab874002016-09-11 13:48:15 +03005702 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 if(d_bytecode == 0 && d_lineno == 0)
5708 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 if (d_bytecode > 255) {
5711 int j, nbytes, ncodes = d_bytecode / 255;
5712 nbytes = a->a_lnotab_off + 2 * ncodes;
5713 len = PyBytes_GET_SIZE(a->a_lnotab);
5714 if (nbytes >= len) {
5715 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5716 len = nbytes;
5717 else if (len <= INT_MAX / 2)
5718 len *= 2;
5719 else {
5720 PyErr_NoMemory();
5721 return 0;
5722 }
5723 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5724 return 0;
5725 }
5726 lnotab = (unsigned char *)
5727 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5728 for (j = 0; j < ncodes; j++) {
5729 *lnotab++ = 255;
5730 *lnotab++ = 0;
5731 }
5732 d_bytecode -= ncodes * 255;
5733 a->a_lnotab_off += ncodes * 2;
5734 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005735 assert(0 <= d_bytecode && d_bytecode <= 255);
5736
5737 if (d_lineno < -128 || 127 < d_lineno) {
5738 int j, nbytes, ncodes, k;
5739 if (d_lineno < 0) {
5740 k = -128;
5741 /* use division on positive numbers */
5742 ncodes = (-d_lineno) / 128;
5743 }
5744 else {
5745 k = 127;
5746 ncodes = d_lineno / 127;
5747 }
5748 d_lineno -= ncodes * k;
5749 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 nbytes = a->a_lnotab_off + 2 * ncodes;
5751 len = PyBytes_GET_SIZE(a->a_lnotab);
5752 if (nbytes >= len) {
5753 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5754 len = nbytes;
5755 else if (len <= INT_MAX / 2)
5756 len *= 2;
5757 else {
5758 PyErr_NoMemory();
5759 return 0;
5760 }
5761 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5762 return 0;
5763 }
5764 lnotab = (unsigned char *)
5765 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5766 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005767 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 d_bytecode = 0;
5769 for (j = 1; j < ncodes; j++) {
5770 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005771 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 a->a_lnotab_off += ncodes * 2;
5774 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005775 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 len = PyBytes_GET_SIZE(a->a_lnotab);
5778 if (a->a_lnotab_off + 2 >= len) {
5779 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5780 return 0;
5781 }
5782 lnotab = (unsigned char *)
5783 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 a->a_lnotab_off += 2;
5786 if (d_bytecode) {
5787 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005788 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 }
5790 else { /* First line of a block; def stmt, etc. */
5791 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005792 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 }
5794 a->a_lineno = i->i_lineno;
5795 a->a_lineno_off = a->a_offset;
5796 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005797}
5798
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005799/* assemble_emit()
5800 Extend the bytecode with a new instruction.
5801 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005802*/
5803
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005804static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005805assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005806{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005807 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005809 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005810
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005811 arg = i->i_oparg;
5812 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 if (i->i_lineno && !assemble_lnotab(a, i))
5814 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005815 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 if (len > PY_SSIZE_T_MAX / 2)
5817 return 0;
5818 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5819 return 0;
5820 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005821 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005823 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005825}
5826
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005827static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005828assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005831 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 /* Compute the size of each block and fixup jump args.
5835 Replace block pointer with position in bytecode. */
5836 do {
5837 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005838 for (i = a->a_nblocks - 1; i >= 0; i--) {
5839 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 bsize = blocksize(b);
5841 b->b_offset = totsize;
5842 totsize += bsize;
5843 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005844 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5846 bsize = b->b_offset;
5847 for (i = 0; i < b->b_iused; i++) {
5848 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005849 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 /* Relative jumps are computed relative to
5851 the instruction pointer after fetching
5852 the jump instruction.
5853 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005854 bsize += isize;
5855 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005857 if (instr->i_jrel) {
5858 instr->i_oparg -= bsize;
5859 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005860 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005861 if (instrsize(instr->i_oparg) != isize) {
5862 extended_arg_recompile = 1;
5863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 }
5866 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 /* XXX: This is an awful hack that could hurt performance, but
5869 on the bright side it should work until we come up
5870 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 The issue is that in the first loop blocksize() is called
5873 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005874 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 So we loop until we stop seeing new EXTENDED_ARGs.
5878 The only EXTENDED_ARGs that could be popping up are
5879 ones in jump instructions. So this should converge
5880 fairly quickly.
5881 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005882 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005883}
5884
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005885static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005886dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005889 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 tuple = PyTuple_New(size);
5892 if (tuple == NULL)
5893 return NULL;
5894 while (PyDict_Next(dict, &pos, &k, &v)) {
5895 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005896 Py_INCREF(k);
5897 assert((i - offset) < size);
5898 assert((i - offset) >= 0);
5899 PyTuple_SET_ITEM(tuple, i - offset, k);
5900 }
5901 return tuple;
5902}
5903
5904static PyObject *
5905consts_dict_keys_inorder(PyObject *dict)
5906{
5907 PyObject *consts, *k, *v;
5908 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5909
5910 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5911 if (consts == NULL)
5912 return NULL;
5913 while (PyDict_Next(dict, &pos, &k, &v)) {
5914 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005915 /* The keys of the dictionary can be tuples wrapping a contant.
5916 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5917 * the object we want is always second. */
5918 if (PyTuple_CheckExact(k)) {
5919 k = PyTuple_GET_ITEM(k, 1);
5920 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005922 assert(i < size);
5923 assert(i >= 0);
5924 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005926 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005927}
5928
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005929static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005930compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005933 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005935 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 if (ste->ste_nested)
5937 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005938 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005940 if (!ste->ste_generator && ste->ste_coroutine)
5941 flags |= CO_COROUTINE;
5942 if (ste->ste_generator && ste->ste_coroutine)
5943 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 if (ste->ste_varargs)
5945 flags |= CO_VARARGS;
5946 if (ste->ste_varkeywords)
5947 flags |= CO_VARKEYWORDS;
5948 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 /* (Only) inherit compilerflags in PyCF_MASK */
5951 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005952
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005953 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5954 ste->ste_coroutine &&
5955 !ste->ste_generator) {
5956 flags |= CO_COROUTINE;
5957 }
5958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005959 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005960}
5961
INADA Naokic2e16072018-11-26 21:23:22 +09005962// Merge *tuple* with constant cache.
5963// Unlike merge_consts_recursive(), this function doesn't work recursively.
5964static int
5965merge_const_tuple(struct compiler *c, PyObject **tuple)
5966{
5967 assert(PyTuple_CheckExact(*tuple));
5968
5969 PyObject *key = _PyCode_ConstantKey(*tuple);
5970 if (key == NULL) {
5971 return 0;
5972 }
5973
5974 // t is borrowed reference
5975 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5976 Py_DECREF(key);
5977 if (t == NULL) {
5978 return 0;
5979 }
5980 if (t == key) { // tuple is new constant.
5981 return 1;
5982 }
5983
5984 PyObject *u = PyTuple_GET_ITEM(t, 1);
5985 Py_INCREF(u);
5986 Py_DECREF(*tuple);
5987 *tuple = u;
5988 return 1;
5989}
5990
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005991static PyCodeObject *
5992makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 PyObject *tmp;
5995 PyCodeObject *co = NULL;
5996 PyObject *consts = NULL;
5997 PyObject *names = NULL;
5998 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 PyObject *name = NULL;
6000 PyObject *freevars = NULL;
6001 PyObject *cellvars = NULL;
6002 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006003 Py_ssize_t nlocals;
6004 int nlocals_int;
6005 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006006 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006007
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006008 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006009 names = dict_keys_inorder(c->u->u_names, 0);
6010 varnames = dict_keys_inorder(c->u->u_varnames, 0);
6011 if (!consts || !names || !varnames)
6012 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6015 if (!cellvars)
6016 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006017 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 if (!freevars)
6019 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006020
INADA Naokic2e16072018-11-26 21:23:22 +09006021 if (!merge_const_tuple(c, &names) ||
6022 !merge_const_tuple(c, &varnames) ||
6023 !merge_const_tuple(c, &cellvars) ||
6024 !merge_const_tuple(c, &freevars))
6025 {
6026 goto error;
6027 }
6028
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006029 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006030 assert(nlocals < INT_MAX);
6031 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006033 flags = compute_code_flags(c);
6034 if (flags < 0)
6035 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
6038 if (!bytecode)
6039 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006041 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6042 if (!tmp)
6043 goto error;
6044 Py_DECREF(consts);
6045 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09006046 if (!merge_const_tuple(c, &consts)) {
6047 goto error;
6048 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006050 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006051 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006052 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006053 maxdepth = stackdepth(c);
6054 if (maxdepth < 0) {
6055 goto error;
6056 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006057 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006058 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006059 maxdepth, flags, bytecode, consts, names,
6060 varnames, freevars, cellvars, c->c_filename,
6061 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006062 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 Py_XDECREF(consts);
6064 Py_XDECREF(names);
6065 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006066 Py_XDECREF(name);
6067 Py_XDECREF(freevars);
6068 Py_XDECREF(cellvars);
6069 Py_XDECREF(bytecode);
6070 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006071}
6072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006073
6074/* For debugging purposes only */
6075#if 0
6076static void
6077dump_instr(const struct instr *i)
6078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 const char *jrel = i->i_jrel ? "jrel " : "";
6080 const char *jabs = i->i_jabs ? "jabs " : "";
6081 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006083 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006084 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006087 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6088 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006089}
6090
6091static void
6092dump_basicblock(const basicblock *b)
6093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006094 const char *seen = b->b_seen ? "seen " : "";
6095 const char *b_return = b->b_return ? "return " : "";
6096 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6097 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6098 if (b->b_instr) {
6099 int i;
6100 for (i = 0; i < b->b_iused; i++) {
6101 fprintf(stderr, " [%02d] ", i);
6102 dump_instr(b->b_instr + i);
6103 }
6104 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006105}
6106#endif
6107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006108static PyCodeObject *
6109assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006111 basicblock *b, *entryblock;
6112 struct assembler a;
6113 int i, j, nblocks;
6114 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006116 /* Make sure every block that falls off the end returns None.
6117 XXX NEXT_BLOCK() isn't quite right, because if the last
6118 block ends with a jump or return b_next shouldn't set.
6119 */
6120 if (!c->u->u_curblock->b_return) {
6121 NEXT_BLOCK(c);
6122 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006123 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006124 ADDOP(c, RETURN_VALUE);
6125 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006127 nblocks = 0;
6128 entryblock = NULL;
6129 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6130 nblocks++;
6131 entryblock = b;
6132 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006134 /* Set firstlineno if it wasn't explicitly set. */
6135 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006136 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006137 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6138 else
6139 c->u->u_firstlineno = 1;
6140 }
6141 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6142 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006143 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006145 /* Can't modify the bytecode after computing jump offsets. */
6146 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006147
T. Wouters99b54d62019-09-12 07:05:33 -07006148 /* Emit code in reverse postorder from dfs. */
6149 for (i = a.a_nblocks - 1; i >= 0; i--) {
6150 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006151 for (j = 0; j < b->b_iused; j++)
6152 if (!assemble_emit(&a, &b->b_instr[j]))
6153 goto error;
6154 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6157 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006158 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006162 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006163 assemble_free(&a);
6164 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006165}
Georg Brandl8334fd92010-12-04 10:26:46 +00006166
6167#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006168PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006169PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6170 PyArena *arena)
6171{
6172 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6173}