blob: f603e3d29e539d17ebdfab7815186fa8df7d3cf8 [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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 default:
1866 PyErr_Format(PyExc_SystemError,
1867 "module kind %d should not be possible",
1868 mod->kind);
1869 return 0;
1870 }
1871 co = assemble(c, addNone);
1872 compiler_exit_scope(c);
1873 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001874}
1875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876/* The test for LOCAL must come before the test for FREE in order to
1877 handle classes where name is both local and free. The local var is
1878 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001879*/
1880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881static int
1882get_ref_type(struct compiler *c, PyObject *name)
1883{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001884 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001885 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001886 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001887 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001888 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 if (scope == 0) {
1890 char buf[350];
1891 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001892 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001894 PyUnicode_AsUTF8(name),
1895 PyUnicode_AsUTF8(c->u->u_name),
1896 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1897 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1898 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1899 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 );
1901 Py_FatalError(buf);
1902 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905}
1906
1907static int
1908compiler_lookup_arg(PyObject *dict, PyObject *name)
1909{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001910 PyObject *v;
1911 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001913 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001914 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915}
1916
1917static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001920 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001921 if (qualname == NULL)
1922 qualname = co->co_name;
1923
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 if (free) {
1925 for (i = 0; i < free; ++i) {
1926 /* Bypass com_addop_varname because it will generate
1927 LOAD_DEREF but LOAD_CLOSURE is needed.
1928 */
1929 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1930 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001932 /* Special case: If a class contains a method with a
1933 free variable that has the same name as a method,
1934 the name will be considered free *and* local in the
1935 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001936 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001937 */
1938 reftype = get_ref_type(c, name);
1939 if (reftype == CELL)
1940 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1941 else /* (reftype == FREE) */
1942 arg = compiler_lookup_arg(c->u->u_freevars, name);
1943 if (arg == -1) {
1944 fprintf(stderr,
1945 "lookup %s in %s %d %d\n"
1946 "freevars of %s: %s\n",
1947 PyUnicode_AsUTF8(PyObject_Repr(name)),
1948 PyUnicode_AsUTF8(c->u->u_name),
1949 reftype, arg,
1950 PyUnicode_AsUTF8(co->co_name),
1951 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1952 Py_FatalError("compiler_make_closure()");
1953 }
1954 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001956 flags |= 0x08;
1957 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001959 ADDOP_LOAD_CONST(c, (PyObject*)co);
1960 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001961 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963}
1964
1965static int
1966compiler_decorators(struct compiler *c, asdl_seq* decos)
1967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (!decos)
1971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1974 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1975 }
1976 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977}
1978
1979static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001980compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001982{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001983 /* Push a dict of keyword-only default values.
1984
1985 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1986 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 int i;
1988 PyObject *keys = NULL;
1989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1991 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1992 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1993 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001994 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 if (!mangled) {
1996 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 if (keys == NULL) {
1999 keys = PyList_New(1);
2000 if (keys == NULL) {
2001 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002002 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002003 }
2004 PyList_SET_ITEM(keys, 0, mangled);
2005 }
2006 else {
2007 int res = PyList_Append(keys, mangled);
2008 Py_DECREF(mangled);
2009 if (res == -1) {
2010 goto error;
2011 }
2012 }
2013 if (!compiler_visit_expr(c, default_)) {
2014 goto error;
2015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
2017 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 if (keys != NULL) {
2019 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2020 PyObject *keys_tuple = PyList_AsTuple(keys);
2021 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002022 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002023 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002024 assert(default_count > 0);
2025 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002026 }
2027 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002029 }
2030
2031error:
2032 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002033 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002034}
2035
2036static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002037compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2038{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002039 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002040 return 1;
2041}
2042
2043static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002044compiler_visit_argannotation(struct compiler *c, identifier id,
2045 expr_ty annotation, PyObject *names)
2046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002048 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002049 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2050 VISIT(c, annexpr, annotation)
2051 }
2052 else {
2053 VISIT(c, expr, annotation);
2054 }
Victor Stinner065efc32014-02-18 22:07:56 +01002055 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002056 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002058 if (PyList_Append(names, mangled) < 0) {
2059 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002061 }
2062 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002065}
2066
2067static int
2068compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2069 PyObject *names)
2070{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 for (i = 0; i < asdl_seq_LEN(args); i++) {
2073 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 c,
2076 arg->arg,
2077 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002078 names))
2079 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002081 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082}
2083
2084static int
2085compiler_visit_annotations(struct compiler *c, arguments_ty args,
2086 expr_ty returns)
2087{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002088 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002089 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002090
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002091 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 */
2093 static identifier return_str;
2094 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002095 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 names = PyList_New(0);
2097 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002098 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002099
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002102 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2103 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002104 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002105 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002106 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002108 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002110 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002111 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002112 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (!return_str) {
2116 return_str = PyUnicode_InternFromString("return");
2117 if (!return_str)
2118 goto error;
2119 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002120 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 goto error;
2122 }
2123
2124 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002126 PyObject *keytuple = PyList_AsTuple(names);
2127 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002128 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002129 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002130 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002132 else {
2133 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002134 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002135 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002136
2137error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002139 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002140}
2141
2142static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002143compiler_visit_defaults(struct compiler *c, arguments_ty args)
2144{
2145 VISIT_SEQ(c, expr, args->defaults);
2146 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2147 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148}
2149
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002150static Py_ssize_t
2151compiler_default_arguments(struct compiler *c, arguments_ty args)
2152{
2153 Py_ssize_t funcflags = 0;
2154 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002155 if (!compiler_visit_defaults(c, args))
2156 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002157 funcflags |= 0x01;
2158 }
2159 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002160 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002161 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002162 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002163 return -1;
2164 }
2165 else if (res > 0) {
2166 funcflags |= 0x02;
2167 }
2168 }
2169 return funcflags;
2170}
2171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172static int
Yury Selivanov75445082015-05-11 22:57:16 -04002173compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002176 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002177 arguments_ty args;
2178 expr_ty returns;
2179 identifier name;
2180 asdl_seq* decos;
2181 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002182 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002183 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002184 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002185 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186
Yury Selivanov75445082015-05-11 22:57:16 -04002187 if (is_async) {
2188 assert(s->kind == AsyncFunctionDef_kind);
2189
2190 args = s->v.AsyncFunctionDef.args;
2191 returns = s->v.AsyncFunctionDef.returns;
2192 decos = s->v.AsyncFunctionDef.decorator_list;
2193 name = s->v.AsyncFunctionDef.name;
2194 body = s->v.AsyncFunctionDef.body;
2195
2196 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2197 } else {
2198 assert(s->kind == FunctionDef_kind);
2199
2200 args = s->v.FunctionDef.args;
2201 returns = s->v.FunctionDef.returns;
2202 decos = s->v.FunctionDef.decorator_list;
2203 name = s->v.FunctionDef.name;
2204 body = s->v.FunctionDef.body;
2205
2206 scope_type = COMPILER_SCOPE_FUNCTION;
2207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (!compiler_decorators(c, decos))
2210 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002211
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002212 firstlineno = s->lineno;
2213 if (asdl_seq_LEN(decos)) {
2214 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2215 }
2216
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002217 funcflags = compiler_default_arguments(c, args);
2218 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002220 }
2221
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002222 annotations = compiler_visit_annotations(c, args, returns);
2223 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002224 return 0;
2225 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002226 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002227 funcflags |= 0x04;
2228 }
2229
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002230 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002231 return 0;
2232 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233
INADA Naokicb41b272017-02-23 00:31:59 +09002234 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002235 if (c->c_optimize < 2) {
2236 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002237 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002238 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 compiler_exit_scope(c);
2240 return 0;
2241 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002244 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002246 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002248 qualname = c->u->u_qualname;
2249 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002251 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002252 Py_XDECREF(qualname);
2253 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002257 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002258 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* decorators */
2262 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2263 ADDOP_I(c, CALL_FUNCTION, 1);
2264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
Yury Selivanov75445082015-05-11 22:57:16 -04002266 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267}
2268
2269static int
2270compiler_class(struct compiler *c, stmt_ty s)
2271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 PyCodeObject *co;
2273 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002274 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (!compiler_decorators(c, decos))
2278 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002279
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002280 firstlineno = s->lineno;
2281 if (asdl_seq_LEN(decos)) {
2282 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2283 }
2284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* ultimately generate code for:
2286 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2287 where:
2288 <func> is a function/closure created from the class body;
2289 it has a single argument (__locals__) where the dict
2290 (or MutableSequence) representing the locals is passed
2291 <name> is the class name
2292 <bases> is the positional arguments and *varargs argument
2293 <keywords> is the keyword arguments and **kwds argument
2294 This borrows from compiler_call.
2295 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002298 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002299 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 return 0;
2301 /* this block represents what we do in the new scope */
2302 {
2303 /* use the class name for name mangling */
2304 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002305 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* load (global) __name__ ... */
2307 str = PyUnicode_InternFromString("__name__");
2308 if (!str || !compiler_nameop(c, str, Load)) {
2309 Py_XDECREF(str);
2310 compiler_exit_scope(c);
2311 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 Py_DECREF(str);
2314 /* ... and store it as __module__ */
2315 str = PyUnicode_InternFromString("__module__");
2316 if (!str || !compiler_nameop(c, str, Store)) {
2317 Py_XDECREF(str);
2318 compiler_exit_scope(c);
2319 return 0;
2320 }
2321 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002322 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002323 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002324 str = PyUnicode_InternFromString("__qualname__");
2325 if (!str || !compiler_nameop(c, str, Store)) {
2326 Py_XDECREF(str);
2327 compiler_exit_scope(c);
2328 return 0;
2329 }
2330 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002332 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 compiler_exit_scope(c);
2334 return 0;
2335 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002336 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002337 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002338 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002339 str = PyUnicode_InternFromString("__class__");
2340 if (str == NULL) {
2341 compiler_exit_scope(c);
2342 return 0;
2343 }
2344 i = compiler_lookup_arg(c->u->u_cellvars, str);
2345 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002346 if (i < 0) {
2347 compiler_exit_scope(c);
2348 return 0;
2349 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002350 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002353 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002354 str = PyUnicode_InternFromString("__classcell__");
2355 if (!str || !compiler_nameop(c, str, Store)) {
2356 Py_XDECREF(str);
2357 compiler_exit_scope(c);
2358 return 0;
2359 }
2360 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002362 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002363 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002364 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002365 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002366 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002367 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* create the code object */
2369 co = assemble(c, 1);
2370 }
2371 /* leave the new scope */
2372 compiler_exit_scope(c);
2373 if (co == NULL)
2374 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* 2. load the 'build_class' function */
2377 ADDOP(c, LOAD_BUILD_CLASS);
2378
2379 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002380 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_DECREF(co);
2382
2383 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002384 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385
2386 /* 5. generate the rest of the code for the call */
2387 if (!compiler_call_helper(c, 2,
2388 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002389 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return 0;
2391
2392 /* 6. apply decorators */
2393 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2394 ADDOP_I(c, CALL_FUNCTION, 1);
2395 }
2396
2397 /* 7. store into <name> */
2398 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2399 return 0;
2400 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401}
2402
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002403/* Return 0 if the expression is a constant value except named singletons.
2404 Return 1 otherwise. */
2405static int
2406check_is_arg(expr_ty e)
2407{
2408 if (e->kind != Constant_kind) {
2409 return 1;
2410 }
2411 PyObject *value = e->v.Constant.value;
2412 return (value == Py_None
2413 || value == Py_False
2414 || value == Py_True
2415 || value == Py_Ellipsis);
2416}
2417
2418/* Check operands of identity chacks ("is" and "is not").
2419 Emit a warning if any operand is a constant except named singletons.
2420 Return 0 on error.
2421 */
2422static int
2423check_compare(struct compiler *c, expr_ty e)
2424{
2425 Py_ssize_t i, n;
2426 int left = check_is_arg(e->v.Compare.left);
2427 n = asdl_seq_LEN(e->v.Compare.ops);
2428 for (i = 0; i < n; i++) {
2429 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2430 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2431 if (op == Is || op == IsNot) {
2432 if (!right || !left) {
2433 const char *msg = (op == Is)
2434 ? "\"is\" with a literal. Did you mean \"==\"?"
2435 : "\"is not\" with a literal. Did you mean \"!=\"?";
2436 return compiler_warn(c, msg);
2437 }
2438 }
2439 left = right;
2440 }
2441 return 1;
2442}
2443
Mark Shannon9af0e472020-01-14 10:12:45 +00002444static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002445{
Mark Shannon9af0e472020-01-14 10:12:45 +00002446 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002447 switch (op) {
2448 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002449 cmp = Py_EQ;
2450 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002451 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002452 cmp = Py_NE;
2453 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002454 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002455 cmp = Py_LT;
2456 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002457 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002458 cmp = Py_LE;
2459 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002460 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002461 cmp = Py_GT;
2462 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002464 cmp = Py_GE;
2465 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002466 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002467 ADDOP_I(c, IS_OP, 0);
2468 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002470 ADDOP_I(c, IS_OP, 1);
2471 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002472 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002473 ADDOP_I(c, CONTAINS_OP, 0);
2474 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002475 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002476 ADDOP_I(c, CONTAINS_OP, 1);
2477 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002478 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002479 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002480 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 ADDOP_I(c, COMPARE_OP, cmp);
2482 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483}
2484
Mark Shannon9af0e472020-01-14 10:12:45 +00002485
2486
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487static int
2488compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2489{
2490 switch (e->kind) {
2491 case UnaryOp_kind:
2492 if (e->v.UnaryOp.op == Not)
2493 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2494 /* fallback to general implementation */
2495 break;
2496 case BoolOp_kind: {
2497 asdl_seq *s = e->v.BoolOp.values;
2498 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2499 assert(n >= 0);
2500 int cond2 = e->v.BoolOp.op == Or;
2501 basicblock *next2 = next;
2502 if (!cond2 != !cond) {
2503 next2 = compiler_new_block(c);
2504 if (next2 == NULL)
2505 return 0;
2506 }
2507 for (i = 0; i < n; ++i) {
2508 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2509 return 0;
2510 }
2511 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2512 return 0;
2513 if (next2 != next)
2514 compiler_use_next_block(c, next2);
2515 return 1;
2516 }
2517 case IfExp_kind: {
2518 basicblock *end, *next2;
2519 end = compiler_new_block(c);
2520 if (end == NULL)
2521 return 0;
2522 next2 = compiler_new_block(c);
2523 if (next2 == NULL)
2524 return 0;
2525 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2526 return 0;
2527 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2528 return 0;
2529 ADDOP_JREL(c, JUMP_FORWARD, end);
2530 compiler_use_next_block(c, next2);
2531 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2532 return 0;
2533 compiler_use_next_block(c, end);
2534 return 1;
2535 }
2536 case Compare_kind: {
2537 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2538 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002539 if (!check_compare(c, e)) {
2540 return 0;
2541 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002542 basicblock *cleanup = compiler_new_block(c);
2543 if (cleanup == NULL)
2544 return 0;
2545 VISIT(c, expr, e->v.Compare.left);
2546 for (i = 0; i < n; i++) {
2547 VISIT(c, expr,
2548 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2549 ADDOP(c, DUP_TOP);
2550 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002551 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002552 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2553 NEXT_BLOCK(c);
2554 }
2555 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002556 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002557 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2558 basicblock *end = compiler_new_block(c);
2559 if (end == NULL)
2560 return 0;
2561 ADDOP_JREL(c, JUMP_FORWARD, end);
2562 compiler_use_next_block(c, cleanup);
2563 ADDOP(c, POP_TOP);
2564 if (!cond) {
2565 ADDOP_JREL(c, JUMP_FORWARD, next);
2566 }
2567 compiler_use_next_block(c, end);
2568 return 1;
2569 }
2570 /* fallback to general implementation */
2571 break;
2572 }
2573 default:
2574 /* fallback to general implementation */
2575 break;
2576 }
2577
2578 /* general implementation */
2579 VISIT(c, expr, e);
2580 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2581 return 1;
2582}
2583
2584static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002585compiler_ifexp(struct compiler *c, expr_ty e)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 basicblock *end, *next;
2588
2589 assert(e->kind == IfExp_kind);
2590 end = compiler_new_block(c);
2591 if (end == NULL)
2592 return 0;
2593 next = compiler_new_block(c);
2594 if (next == NULL)
2595 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002596 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2597 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 VISIT(c, expr, e->v.IfExp.body);
2599 ADDOP_JREL(c, JUMP_FORWARD, end);
2600 compiler_use_next_block(c, next);
2601 VISIT(c, expr, e->v.IfExp.orelse);
2602 compiler_use_next_block(c, end);
2603 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002604}
2605
2606static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607compiler_lambda(struct compiler *c, expr_ty e)
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002610 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002612 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 arguments_ty args = e->v.Lambda.args;
2614 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (!name) {
2617 name = PyUnicode_InternFromString("<lambda>");
2618 if (!name)
2619 return 0;
2620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002622 funcflags = compiler_default_arguments(c, args);
2623 if (funcflags == -1) {
2624 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002626
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002627 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002628 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 /* Make None the first constant, so the lambda can't have a
2632 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002633 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002637 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2639 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2640 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002641 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 }
2643 else {
2644 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002645 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002647 qualname = c->u->u_qualname;
2648 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002650 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002653 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002654 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 Py_DECREF(co);
2656
2657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658}
2659
2660static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661compiler_if(struct compiler *c, stmt_ty s)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 basicblock *end, *next;
2664 int constant;
2665 assert(s->kind == If_kind);
2666 end = compiler_new_block(c);
2667 if (end == NULL)
2668 return 0;
2669
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002670 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002671 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 * constant = 1: "if 1", "if 2", ...
2673 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002674 if (constant == 0) {
2675 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002677 END_DO_NOT_EMIT_BYTECODE
2678 if (s->v.If.orelse) {
2679 VISIT_SEQ(c, stmt, s->v.If.orelse);
2680 }
2681 } else if (constant == 1) {
2682 VISIT_SEQ(c, stmt, s->v.If.body);
2683 if (s->v.If.orelse) {
2684 BEGIN_DO_NOT_EMIT_BYTECODE
2685 VISIT_SEQ(c, stmt, s->v.If.orelse);
2686 END_DO_NOT_EMIT_BYTECODE
2687 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002689 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 next = compiler_new_block(c);
2691 if (next == NULL)
2692 return 0;
2693 }
Mark Shannonfee55262019-11-21 09:11:43 +00002694 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002696 }
2697 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002698 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002701 if (asdl_seq_LEN(s->v.If.orelse)) {
2702 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 compiler_use_next_block(c, next);
2704 VISIT_SEQ(c, stmt, s->v.If.orelse);
2705 }
2706 }
2707 compiler_use_next_block(c, end);
2708 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709}
2710
2711static int
2712compiler_for(struct compiler *c, stmt_ty s)
2713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 start = compiler_new_block(c);
2717 cleanup = compiler_new_block(c);
2718 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002719 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002721 }
2722 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 VISIT(c, expr, s->v.For.iter);
2726 ADDOP(c, GET_ITER);
2727 compiler_use_next_block(c, start);
2728 ADDOP_JREL(c, FOR_ITER, cleanup);
2729 VISIT(c, expr, s->v.For.target);
2730 VISIT_SEQ(c, stmt, s->v.For.body);
2731 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2732 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002733
2734 compiler_pop_fblock(c, FOR_LOOP, start);
2735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 VISIT_SEQ(c, stmt, s->v.For.orelse);
2737 compiler_use_next_block(c, end);
2738 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739}
2740
Yury Selivanov75445082015-05-11 22:57:16 -04002741
2742static int
2743compiler_async_for(struct compiler *c, stmt_ty s)
2744{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002745 basicblock *start, *except, *end;
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002746 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
2747 c->u->u_ste->ste_coroutine = 1;
2748 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002749 return compiler_error(c, "'async for' outside async function");
2750 }
2751
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002752 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002753 except = compiler_new_block(c);
2754 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002755
Mark Shannonfee55262019-11-21 09:11:43 +00002756 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002757 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002758 }
Yury Selivanov75445082015-05-11 22:57:16 -04002759 VISIT(c, expr, s->v.AsyncFor.iter);
2760 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002761
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002762 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002763 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002764 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002765 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002766 /* SETUP_FINALLY to guard the __anext__ call */
2767 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002768 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002769 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002770 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002771 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002772
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002773 /* Success block for __anext__ */
2774 VISIT(c, expr, s->v.AsyncFor.target);
2775 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2776 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2777
2778 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002779
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002780 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002781 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002782 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002783
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002785 VISIT_SEQ(c, stmt, s->v.For.orelse);
2786
2787 compiler_use_next_block(c, end);
2788
2789 return 1;
2790}
2791
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792static int
2793compiler_while(struct compiler *c, stmt_ty s)
2794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002796 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002799 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002800 // Push a dummy block so the VISIT_SEQ knows that we are
2801 // inside a while loop so it can correctly evaluate syntax
2802 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002803 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002804 return 0;
2805 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002806 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002807 // Remove the dummy block now that is not needed.
2808 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002809 END_DO_NOT_EMIT_BYTECODE
2810 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 return 1;
2814 }
2815 loop = compiler_new_block(c);
2816 end = compiler_new_block(c);
2817 if (constant == -1) {
2818 anchor = compiler_new_block(c);
2819 if (anchor == NULL)
2820 return 0;
2821 }
2822 if (loop == NULL || end == NULL)
2823 return 0;
2824 if (s->v.While.orelse) {
2825 orelse = compiler_new_block(c);
2826 if (orelse == NULL)
2827 return 0;
2828 }
2829 else
2830 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002833 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 return 0;
2835 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002836 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2837 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 }
2839 VISIT_SEQ(c, stmt, s->v.While.body);
2840 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* XXX should the two POP instructions be in a separate block
2843 if there is no else clause ?
2844 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002846 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002848 compiler_pop_fblock(c, WHILE_LOOP, loop);
2849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 if (orelse != NULL) /* what if orelse is just pass? */
2851 VISIT_SEQ(c, stmt, s->v.While.orelse);
2852 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855}
2856
2857static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002858compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002860 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002861 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862 if (c->u->u_ste->ste_type != FunctionBlock)
2863 return compiler_error(c, "'return' outside function");
2864 if (s->v.Return.value != NULL &&
2865 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2866 {
2867 return compiler_error(
2868 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002870 if (preserve_tos) {
2871 VISIT(c, expr, s->v.Return.value);
2872 }
Mark Shannonfee55262019-11-21 09:11:43 +00002873 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2874 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002876 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877 }
2878 else if (!preserve_tos) {
2879 VISIT(c, expr, s->v.Return.value);
2880 }
2881 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884}
2885
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002886static int
2887compiler_break(struct compiler *c)
2888{
Mark Shannonfee55262019-11-21 09:11:43 +00002889 struct fblockinfo *loop = NULL;
2890 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2891 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 }
Mark Shannonfee55262019-11-21 09:11:43 +00002893 if (loop == NULL) {
2894 return compiler_error(c, "'break' outside loop");
2895 }
2896 if (!compiler_unwind_fblock(c, loop, 0)) {
2897 return 0;
2898 }
2899 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2900 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002901}
2902
2903static int
2904compiler_continue(struct compiler *c)
2905{
Mark Shannonfee55262019-11-21 09:11:43 +00002906 struct fblockinfo *loop = NULL;
2907 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2908 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002909 }
Mark Shannonfee55262019-11-21 09:11:43 +00002910 if (loop == NULL) {
2911 return compiler_error(c, "'continue' not properly in loop");
2912 }
2913 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2914 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002915}
2916
2917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919
2920 SETUP_FINALLY L
2921 <code for body>
2922 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002923 <code for finalbody>
2924 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002925 L:
2926 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002927 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 The special instructions use the block stack. Each block
2930 stack entry contains the instruction that created it (here
2931 SETUP_FINALLY), the level of the value stack at the time the
2932 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 Pushes the current value stack level and the label
2936 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002938 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 when a SETUP_FINALLY entry is found, the raised and the caught
2942 exceptions are pushed onto the value stack (and the exception
2943 condition is cleared), and the interpreter jumps to the label
2944 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945*/
2946
2947static int
2948compiler_try_finally(struct compiler *c, stmt_ty s)
2949{
Mark Shannonfee55262019-11-21 09:11:43 +00002950 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 body = compiler_new_block(c);
2953 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002954 exit = compiler_new_block(c);
2955 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002958 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 ADDOP_JREL(c, SETUP_FINALLY, end);
2960 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002961 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002963 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2964 if (!compiler_try_except(c, s))
2965 return 0;
2966 }
2967 else {
2968 VISIT_SEQ(c, stmt, s->v.Try.body);
2969 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002971 compiler_pop_fblock(c, FINALLY_TRY, body);
2972 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2973 ADDOP_JREL(c, JUMP_FORWARD, exit);
2974 /* `finally` block */
2975 compiler_use_next_block(c, end);
2976 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2977 return 0;
2978 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2979 compiler_pop_fblock(c, FINALLY_END, end);
2980 ADDOP(c, RERAISE);
2981 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002986 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987 (The contents of the value stack is shown in [], with the top
2988 at the right; 'tb' is trace-back info, 'val' the exception's
2989 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990
2991 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002992 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 [] <code for S>
2994 [] POP_BLOCK
2995 [] JUMP_FORWARD L0
2996
2997 [tb, val, exc] L1: DUP )
2998 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00002999 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 [tb, val, exc] POP
3001 [tb, val] <assign to V1> (or POP if no V1)
3002 [tb] POP
3003 [] <code for S1>
3004 JUMP_FORWARD L0
3005
3006 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 .............................etc.......................
3008
Mark Shannonfee55262019-11-21 09:11:43 +00003009 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010
3011 [] L0: <next statement>
3012
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 Of course, parts are not generated if Vi or Ei is not present.
3014*/
3015static int
3016compiler_try_except(struct compiler *c, stmt_ty s)
3017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003019 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 body = compiler_new_block(c);
3022 except = compiler_new_block(c);
3023 orelse = compiler_new_block(c);
3024 end = compiler_new_block(c);
3025 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3026 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003027 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003029 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003031 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 ADDOP(c, POP_BLOCK);
3033 compiler_pop_fblock(c, EXCEPT, body);
3034 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003035 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 compiler_use_next_block(c, except);
3037 for (i = 0; i < n; i++) {
3038 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 if (!handler->v.ExceptHandler.type && i < n-1)
3041 return compiler_error(c, "default 'except:' must be last");
3042 c->u->u_lineno_set = 0;
3043 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003044 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 except = compiler_new_block(c);
3046 if (except == NULL)
3047 return 0;
3048 if (handler->v.ExceptHandler.type) {
3049 ADDOP(c, DUP_TOP);
3050 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003051 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 }
3053 ADDOP(c, POP_TOP);
3054 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003055 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003056
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 cleanup_end = compiler_new_block(c);
3058 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003059 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003060 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003061 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003062
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003063 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3064 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003066 /*
3067 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003068 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003070 try:
3071 # body
3072 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003073 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003074 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 /* second try: */
3078 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3079 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003080 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 /* second # body */
3084 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003085 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003086 ADDOP(c, POP_BLOCK);
3087 ADDOP(c, POP_EXCEPT);
3088 /* name = None; del name */
3089 ADDOP_LOAD_CONST(c, Py_None);
3090 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3091 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3092 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093
Mark Shannonfee55262019-11-21 09:11:43 +00003094 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003097 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003098 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003100 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101
Mark Shannonfee55262019-11-21 09:11:43 +00003102 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 }
3104 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003105 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003108 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110
Guido van Rossumb940e112007-01-10 16:19:56 +00003111 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003112 ADDOP(c, POP_TOP);
3113 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003114 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003117 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003118 ADDOP(c, POP_EXCEPT);
3119 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 compiler_use_next_block(c, except);
3122 }
Mark Shannonfee55262019-11-21 09:11:43 +00003123 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003125 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 compiler_use_next_block(c, end);
3127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128}
3129
3130static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003131compiler_try(struct compiler *c, stmt_ty s) {
3132 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3133 return compiler_try_finally(c, s);
3134 else
3135 return compiler_try_except(c, s);
3136}
3137
3138
3139static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140compiler_import_as(struct compiler *c, identifier name, identifier asname)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* The IMPORT_NAME opcode was already generated. This function
3143 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003146 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003148 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3149 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003150 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003151 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003152 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003154 while (1) {
3155 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003157 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003158 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003159 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003160 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003162 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003163 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003164 if (dot == -1) {
3165 break;
3166 }
3167 ADDOP(c, ROT_TWO);
3168 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003170 if (!compiler_nameop(c, asname, Store)) {
3171 return 0;
3172 }
3173 ADDOP(c, POP_TOP);
3174 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 }
3176 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177}
3178
3179static int
3180compiler_import(struct compiler *c, stmt_ty s)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 /* The Import node stores a module name like a.b.c as a single
3183 string. This is convenient for all cases except
3184 import a.b.c as d
3185 where we need to parse that string to extract the individual
3186 module names.
3187 XXX Perhaps change the representation to make this case simpler?
3188 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003189 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 for (i = 0; i < n; i++) {
3192 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3193 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003195 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3196 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 if (alias->asname) {
3200 r = compiler_import_as(c, alias->name, alias->asname);
3201 if (!r)
3202 return r;
3203 }
3204 else {
3205 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003206 Py_ssize_t dot = PyUnicode_FindChar(
3207 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003208 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003209 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003210 if (tmp == NULL)
3211 return 0;
3212 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003214 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 Py_DECREF(tmp);
3216 }
3217 if (!r)
3218 return r;
3219 }
3220 }
3221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
3224static int
3225compiler_from_import(struct compiler *c, stmt_ty s)
3226{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003227 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003228 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 if (!empty_string) {
3232 empty_string = PyUnicode_FromString("");
3233 if (!empty_string)
3234 return 0;
3235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003237 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003238
3239 names = PyTuple_New(n);
3240 if (!names)
3241 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* build up the names */
3244 for (i = 0; i < n; i++) {
3245 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3246 Py_INCREF(alias->name);
3247 PyTuple_SET_ITEM(names, i, alias->name);
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003251 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 Py_DECREF(names);
3253 return compiler_error(c, "from __future__ imports must occur "
3254 "at the beginning of the file");
3255 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003256 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 if (s->v.ImportFrom.module) {
3259 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3260 }
3261 else {
3262 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3263 }
3264 for (i = 0; i < n; i++) {
3265 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3266 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003268 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 assert(n == 1);
3270 ADDOP(c, IMPORT_STAR);
3271 return 1;
3272 }
3273
3274 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3275 store_name = alias->name;
3276 if (alias->asname)
3277 store_name = alias->asname;
3278
3279 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 return 0;
3281 }
3282 }
3283 /* remove imported module */
3284 ADDOP(c, POP_TOP);
3285 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286}
3287
3288static int
3289compiler_assert(struct compiler *c, stmt_ty s)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292
Georg Brandl8334fd92010-12-04 10:26:46 +00003293 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003296 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3297 {
3298 if (!compiler_warn(c, "assertion is always true, "
3299 "perhaps remove parentheses?"))
3300 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003301 return 0;
3302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 end = compiler_new_block(c);
3305 if (end == NULL)
3306 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003307 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3308 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003309 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 if (s->v.Assert.msg) {
3311 VISIT(c, expr, s->v.Assert.msg);
3312 ADDOP_I(c, CALL_FUNCTION, 1);
3313 }
3314 ADDOP_I(c, RAISE_VARARGS, 1);
3315 compiler_use_next_block(c, end);
3316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317}
3318
3319static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003320compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3321{
3322 if (c->c_interactive && c->c_nestlevel <= 1) {
3323 VISIT(c, expr, value);
3324 ADDOP(c, PRINT_EXPR);
3325 return 1;
3326 }
3327
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003328 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003329 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003330 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003331 }
3332
3333 VISIT(c, expr, value);
3334 ADDOP(c, POP_TOP);
3335 return 1;
3336}
3337
3338static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339compiler_visit_stmt(struct compiler *c, stmt_ty s)
3340{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003341 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 /* Always assign a lineno to the next instruction for a stmt. */
3344 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003345 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 switch (s->kind) {
3349 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003350 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 case ClassDef_kind:
3352 return compiler_class(c, s);
3353 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003354 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case Delete_kind:
3356 VISIT_SEQ(c, expr, s->v.Delete.targets)
3357 break;
3358 case Assign_kind:
3359 n = asdl_seq_LEN(s->v.Assign.targets);
3360 VISIT(c, expr, s->v.Assign.value);
3361 for (i = 0; i < n; i++) {
3362 if (i < n - 1)
3363 ADDOP(c, DUP_TOP);
3364 VISIT(c, expr,
3365 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3366 }
3367 break;
3368 case AugAssign_kind:
3369 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003370 case AnnAssign_kind:
3371 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 case For_kind:
3373 return compiler_for(c, s);
3374 case While_kind:
3375 return compiler_while(c, s);
3376 case If_kind:
3377 return compiler_if(c, s);
3378 case Raise_kind:
3379 n = 0;
3380 if (s->v.Raise.exc) {
3381 VISIT(c, expr, s->v.Raise.exc);
3382 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003383 if (s->v.Raise.cause) {
3384 VISIT(c, expr, s->v.Raise.cause);
3385 n++;
3386 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003388 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003390 case Try_kind:
3391 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Assert_kind:
3393 return compiler_assert(c, s);
3394 case Import_kind:
3395 return compiler_import(c, s);
3396 case ImportFrom_kind:
3397 return compiler_from_import(c, s);
3398 case Global_kind:
3399 case Nonlocal_kind:
3400 break;
3401 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003402 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 case Pass_kind:
3404 break;
3405 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003406 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 case Continue_kind:
3408 return compiler_continue(c);
3409 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003410 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003411 case AsyncFunctionDef_kind:
3412 return compiler_function(c, s, 1);
3413 case AsyncWith_kind:
3414 return compiler_async_with(c, s, 0);
3415 case AsyncFor_kind:
3416 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 }
Yury Selivanov75445082015-05-11 22:57:16 -04003418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420}
3421
3422static int
3423unaryop(unaryop_ty op)
3424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 switch (op) {
3426 case Invert:
3427 return UNARY_INVERT;
3428 case Not:
3429 return UNARY_NOT;
3430 case UAdd:
3431 return UNARY_POSITIVE;
3432 case USub:
3433 return UNARY_NEGATIVE;
3434 default:
3435 PyErr_Format(PyExc_SystemError,
3436 "unary op %d should not be possible", op);
3437 return 0;
3438 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439}
3440
3441static int
3442binop(struct compiler *c, operator_ty op)
3443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 switch (op) {
3445 case Add:
3446 return BINARY_ADD;
3447 case Sub:
3448 return BINARY_SUBTRACT;
3449 case Mult:
3450 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003451 case MatMult:
3452 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 case Div:
3454 return BINARY_TRUE_DIVIDE;
3455 case Mod:
3456 return BINARY_MODULO;
3457 case Pow:
3458 return BINARY_POWER;
3459 case LShift:
3460 return BINARY_LSHIFT;
3461 case RShift:
3462 return BINARY_RSHIFT;
3463 case BitOr:
3464 return BINARY_OR;
3465 case BitXor:
3466 return BINARY_XOR;
3467 case BitAnd:
3468 return BINARY_AND;
3469 case FloorDiv:
3470 return BINARY_FLOOR_DIVIDE;
3471 default:
3472 PyErr_Format(PyExc_SystemError,
3473 "binary op %d should not be possible", op);
3474 return 0;
3475 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003476}
3477
3478static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479inplace_binop(struct compiler *c, operator_ty op)
3480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 switch (op) {
3482 case Add:
3483 return INPLACE_ADD;
3484 case Sub:
3485 return INPLACE_SUBTRACT;
3486 case Mult:
3487 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003488 case MatMult:
3489 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 case Div:
3491 return INPLACE_TRUE_DIVIDE;
3492 case Mod:
3493 return INPLACE_MODULO;
3494 case Pow:
3495 return INPLACE_POWER;
3496 case LShift:
3497 return INPLACE_LSHIFT;
3498 case RShift:
3499 return INPLACE_RSHIFT;
3500 case BitOr:
3501 return INPLACE_OR;
3502 case BitXor:
3503 return INPLACE_XOR;
3504 case BitAnd:
3505 return INPLACE_AND;
3506 case FloorDiv:
3507 return INPLACE_FLOOR_DIVIDE;
3508 default:
3509 PyErr_Format(PyExc_SystemError,
3510 "inplace binary op %d should not be possible", op);
3511 return 0;
3512 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513}
3514
3515static int
3516compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3517{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003518 int op, scope;
3519 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 PyObject *dict = c->u->u_names;
3523 PyObject *mangled;
3524 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003526 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3527 !_PyUnicode_EqualToASCIIString(name, "True") &&
3528 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003529
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003530 mangled = _Py_Mangle(c->u->u_private, name);
3531 if (!mangled)
3532 return 0;
3533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 op = 0;
3535 optype = OP_NAME;
3536 scope = PyST_GetScope(c->u->u_ste, mangled);
3537 switch (scope) {
3538 case FREE:
3539 dict = c->u->u_freevars;
3540 optype = OP_DEREF;
3541 break;
3542 case CELL:
3543 dict = c->u->u_cellvars;
3544 optype = OP_DEREF;
3545 break;
3546 case LOCAL:
3547 if (c->u->u_ste->ste_type == FunctionBlock)
3548 optype = OP_FAST;
3549 break;
3550 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003551 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 optype = OP_GLOBAL;
3553 break;
3554 case GLOBAL_EXPLICIT:
3555 optype = OP_GLOBAL;
3556 break;
3557 default:
3558 /* scope can be 0 */
3559 break;
3560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003563 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 switch (optype) {
3566 case OP_DEREF:
3567 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003568 case Load:
3569 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3570 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003571 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003572 op = STORE_DEREF;
3573 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 case AugLoad:
3575 case AugStore:
3576 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003577 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 case Param:
3579 default:
3580 PyErr_SetString(PyExc_SystemError,
3581 "param invalid for deref variable");
3582 return 0;
3583 }
3584 break;
3585 case OP_FAST:
3586 switch (ctx) {
3587 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003588 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003589 op = STORE_FAST;
3590 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 case Del: op = DELETE_FAST; break;
3592 case AugLoad:
3593 case AugStore:
3594 break;
3595 case Param:
3596 default:
3597 PyErr_SetString(PyExc_SystemError,
3598 "param invalid for local variable");
3599 return 0;
3600 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003601 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 return 1;
3603 case OP_GLOBAL:
3604 switch (ctx) {
3605 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003606 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003607 op = STORE_GLOBAL;
3608 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 case Del: op = DELETE_GLOBAL; break;
3610 case AugLoad:
3611 case AugStore:
3612 break;
3613 case Param:
3614 default:
3615 PyErr_SetString(PyExc_SystemError,
3616 "param invalid for global variable");
3617 return 0;
3618 }
3619 break;
3620 case OP_NAME:
3621 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003622 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003623 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003624 op = STORE_NAME;
3625 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 case Del: op = DELETE_NAME; break;
3627 case AugLoad:
3628 case AugStore:
3629 break;
3630 case Param:
3631 default:
3632 PyErr_SetString(PyExc_SystemError,
3633 "param invalid for name variable");
3634 return 0;
3635 }
3636 break;
3637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 assert(op);
3640 arg = compiler_add_o(c, dict, mangled);
3641 Py_DECREF(mangled);
3642 if (arg < 0)
3643 return 0;
3644 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645}
3646
3647static int
3648compiler_boolop(struct compiler *c, expr_ty e)
3649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003651 int jumpi;
3652 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 assert(e->kind == BoolOp_kind);
3656 if (e->v.BoolOp.op == And)
3657 jumpi = JUMP_IF_FALSE_OR_POP;
3658 else
3659 jumpi = JUMP_IF_TRUE_OR_POP;
3660 end = compiler_new_block(c);
3661 if (end == NULL)
3662 return 0;
3663 s = e->v.BoolOp.values;
3664 n = asdl_seq_LEN(s) - 1;
3665 assert(n >= 0);
3666 for (i = 0; i < n; ++i) {
3667 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3668 ADDOP_JABS(c, jumpi, end);
3669 }
3670 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3671 compiler_use_next_block(c, end);
3672 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673}
3674
3675static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003676starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3677 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003678{
3679 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003680 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003681 if (n > 2 && are_all_items_const(elts, 0, n)) {
3682 PyObject *folded = PyTuple_New(n);
3683 if (folded == NULL) {
3684 return 0;
3685 }
3686 PyObject *val;
3687 for (i = 0; i < n; i++) {
3688 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3689 Py_INCREF(val);
3690 PyTuple_SET_ITEM(folded, i, val);
3691 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003692 if (tuple) {
3693 ADDOP_LOAD_CONST_NEW(c, folded);
3694 } else {
3695 if (add == SET_ADD) {
3696 Py_SETREF(folded, PyFrozenSet_New(folded));
3697 if (folded == NULL) {
3698 return 0;
3699 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003700 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003701 ADDOP_I(c, build, pushed);
3702 ADDOP_LOAD_CONST_NEW(c, folded);
3703 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003704 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003705 return 1;
3706 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003707
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003708 for (i = 0; i < n; i++) {
3709 expr_ty elt = asdl_seq_GET(elts, i);
3710 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003711 seen_star = 1;
3712 }
3713 }
3714 if (seen_star) {
3715 seen_star = 0;
3716 for (i = 0; i < n; i++) {
3717 expr_ty elt = asdl_seq_GET(elts, i);
3718 if (elt->kind == Starred_kind) {
3719 if (seen_star == 0) {
3720 ADDOP_I(c, build, i+pushed);
3721 seen_star = 1;
3722 }
3723 VISIT(c, expr, elt->v.Starred.value);
3724 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003726 else {
3727 VISIT(c, expr, elt);
3728 if (seen_star) {
3729 ADDOP_I(c, add, 1);
3730 }
3731 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003732 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003733 assert(seen_star);
3734 if (tuple) {
3735 ADDOP(c, LIST_TO_TUPLE);
3736 }
3737 }
3738 else {
3739 for (i = 0; i < n; i++) {
3740 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003741 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003742 }
3743 if (tuple) {
3744 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3745 } else {
3746 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003747 }
3748 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 return 1;
3750}
3751
3752static int
3753assignment_helper(struct compiler *c, asdl_seq *elts)
3754{
3755 Py_ssize_t n = asdl_seq_LEN(elts);
3756 Py_ssize_t i;
3757 int seen_star = 0;
3758 for (i = 0; i < n; i++) {
3759 expr_ty elt = asdl_seq_GET(elts, i);
3760 if (elt->kind == Starred_kind && !seen_star) {
3761 if ((i >= (1 << 8)) ||
3762 (n-i-1 >= (INT_MAX >> 8)))
3763 return compiler_error(c,
3764 "too many expressions in "
3765 "star-unpacking assignment");
3766 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3767 seen_star = 1;
3768 asdl_seq_SET(elts, i, elt->v.Starred.value);
3769 }
3770 else if (elt->kind == Starred_kind) {
3771 return compiler_error(c,
3772 "two starred expressions in assignment");
3773 }
3774 }
3775 if (!seen_star) {
3776 ADDOP_I(c, UNPACK_SEQUENCE, n);
3777 }
3778 VISIT_SEQ(c, expr, elts);
3779 return 1;
3780}
3781
3782static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783compiler_list(struct compiler *c, expr_ty e)
3784{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003786 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003787 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003790 return starunpack_helper(c, elts, 0, BUILD_LIST,
3791 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793 else
3794 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796}
3797
3798static int
3799compiler_tuple(struct compiler *c, expr_ty e)
3800{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003801 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003802 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 return assignment_helper(c, elts);
3804 }
3805 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003806 return starunpack_helper(c, elts, 0, BUILD_LIST,
3807 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003808 }
3809 else
3810 VISIT_SEQ(c, expr, elts);
3811 return 1;
3812}
3813
3814static int
3815compiler_set(struct compiler *c, expr_ty e)
3816{
Mark Shannon13bc1392020-01-23 09:25:17 +00003817 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3818 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003819}
3820
3821static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003822are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3823{
3824 Py_ssize_t i;
3825 for (i = begin; i < end; i++) {
3826 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003827 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003828 return 0;
3829 }
3830 return 1;
3831}
3832
3833static int
3834compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3835{
3836 Py_ssize_t i, n = end - begin;
3837 PyObject *keys, *key;
3838 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3839 for (i = begin; i < end; i++) {
3840 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3841 }
3842 keys = PyTuple_New(n);
3843 if (keys == NULL) {
3844 return 0;
3845 }
3846 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003847 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003848 Py_INCREF(key);
3849 PyTuple_SET_ITEM(keys, i - begin, key);
3850 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003851 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003852 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3853 }
3854 else {
3855 for (i = begin; i < end; i++) {
3856 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3857 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3858 }
3859 ADDOP_I(c, BUILD_MAP, n);
3860 }
3861 return 1;
3862}
3863
3864static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003865compiler_dict(struct compiler *c, expr_ty e)
3866{
Victor Stinner976bb402016-03-23 11:36:19 +01003867 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003868 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003869 int is_unpacking = 0;
3870 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003871 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003872 elements = 0;
3873 for (i = 0; i < n; i++) {
3874 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003875 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003876 if (elements) {
3877 if (!compiler_subdict(c, e, i - elements, i)) {
3878 return 0;
3879 }
3880 if (have_dict) {
3881 ADDOP_I(c, DICT_UPDATE, 1);
3882 }
3883 have_dict = 1;
3884 elements = 0;
3885 }
3886 if (have_dict == 0) {
3887 ADDOP_I(c, BUILD_MAP, 0);
3888 have_dict = 1;
3889 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003890 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003891 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003892 }
3893 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003894 if (elements == 0xFFFF) {
3895 if (!compiler_subdict(c, e, i - elements, i)) {
3896 return 0;
3897 }
3898 if (have_dict) {
3899 ADDOP_I(c, DICT_UPDATE, 1);
3900 }
3901 have_dict = 1;
3902 elements = 0;
3903 }
3904 else {
3905 elements++;
3906 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 }
3908 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003909 if (elements) {
3910 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003911 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003912 }
3913 if (have_dict) {
3914 ADDOP_I(c, DICT_UPDATE, 1);
3915 }
3916 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003917 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003918 if (!have_dict) {
3919 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 }
3921 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922}
3923
3924static int
3925compiler_compare(struct compiler *c, expr_ty e)
3926{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003927 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003929 if (!check_compare(c, e)) {
3930 return 0;
3931 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003933 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3934 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3935 if (n == 0) {
3936 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003937 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003938 }
3939 else {
3940 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 if (cleanup == NULL)
3942 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003943 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 VISIT(c, expr,
3945 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003946 ADDOP(c, DUP_TOP);
3947 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003948 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003949 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3950 NEXT_BLOCK(c);
3951 }
3952 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003953 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 basicblock *end = compiler_new_block(c);
3955 if (end == NULL)
3956 return 0;
3957 ADDOP_JREL(c, JUMP_FORWARD, end);
3958 compiler_use_next_block(c, cleanup);
3959 ADDOP(c, ROT_TWO);
3960 ADDOP(c, POP_TOP);
3961 compiler_use_next_block(c, end);
3962 }
3963 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964}
3965
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003966static PyTypeObject *
3967infer_type(expr_ty e)
3968{
3969 switch (e->kind) {
3970 case Tuple_kind:
3971 return &PyTuple_Type;
3972 case List_kind:
3973 case ListComp_kind:
3974 return &PyList_Type;
3975 case Dict_kind:
3976 case DictComp_kind:
3977 return &PyDict_Type;
3978 case Set_kind:
3979 case SetComp_kind:
3980 return &PySet_Type;
3981 case GeneratorExp_kind:
3982 return &PyGen_Type;
3983 case Lambda_kind:
3984 return &PyFunction_Type;
3985 case JoinedStr_kind:
3986 case FormattedValue_kind:
3987 return &PyUnicode_Type;
3988 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003989 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003990 default:
3991 return NULL;
3992 }
3993}
3994
3995static int
3996check_caller(struct compiler *c, expr_ty e)
3997{
3998 switch (e->kind) {
3999 case Constant_kind:
4000 case Tuple_kind:
4001 case List_kind:
4002 case ListComp_kind:
4003 case Dict_kind:
4004 case DictComp_kind:
4005 case Set_kind:
4006 case SetComp_kind:
4007 case GeneratorExp_kind:
4008 case JoinedStr_kind:
4009 case FormattedValue_kind:
4010 return compiler_warn(c, "'%.200s' object is not callable; "
4011 "perhaps you missed a comma?",
4012 infer_type(e)->tp_name);
4013 default:
4014 return 1;
4015 }
4016}
4017
4018static int
4019check_subscripter(struct compiler *c, expr_ty e)
4020{
4021 PyObject *v;
4022
4023 switch (e->kind) {
4024 case Constant_kind:
4025 v = e->v.Constant.value;
4026 if (!(v == Py_None || v == Py_Ellipsis ||
4027 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4028 PyAnySet_Check(v)))
4029 {
4030 return 1;
4031 }
4032 /* fall through */
4033 case Set_kind:
4034 case SetComp_kind:
4035 case GeneratorExp_kind:
4036 case Lambda_kind:
4037 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4038 "perhaps you missed a comma?",
4039 infer_type(e)->tp_name);
4040 default:
4041 return 1;
4042 }
4043}
4044
4045static int
4046check_index(struct compiler *c, expr_ty e, slice_ty s)
4047{
4048 PyObject *v;
4049
4050 if (s->kind != Index_kind) {
4051 return 1;
4052 }
4053 PyTypeObject *index_type = infer_type(s->v.Index.value);
4054 if (index_type == NULL
4055 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4056 || index_type == &PySlice_Type) {
4057 return 1;
4058 }
4059
4060 switch (e->kind) {
4061 case Constant_kind:
4062 v = e->v.Constant.value;
4063 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4064 return 1;
4065 }
4066 /* fall through */
4067 case Tuple_kind:
4068 case List_kind:
4069 case ListComp_kind:
4070 case JoinedStr_kind:
4071 case FormattedValue_kind:
4072 return compiler_warn(c, "%.200s indices must be integers or slices, "
4073 "not %.200s; "
4074 "perhaps you missed a comma?",
4075 infer_type(e)->tp_name,
4076 index_type->tp_name);
4077 default:
4078 return 1;
4079 }
4080}
4081
Zackery Spytz97f5de02019-03-22 01:30:32 -06004082// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004084maybe_optimize_method_call(struct compiler *c, expr_ty e)
4085{
4086 Py_ssize_t argsl, i;
4087 expr_ty meth = e->v.Call.func;
4088 asdl_seq *args = e->v.Call.args;
4089
4090 /* Check that the call node is an attribute access, and that
4091 the call doesn't have keyword parameters. */
4092 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4093 asdl_seq_LEN(e->v.Call.keywords))
4094 return -1;
4095
4096 /* Check that there are no *varargs types of arguments. */
4097 argsl = asdl_seq_LEN(args);
4098 for (i = 0; i < argsl; i++) {
4099 expr_ty elt = asdl_seq_GET(args, i);
4100 if (elt->kind == Starred_kind) {
4101 return -1;
4102 }
4103 }
4104
4105 /* Alright, we can optimize the code. */
4106 VISIT(c, expr, meth->v.Attribute.value);
4107 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4108 VISIT_SEQ(c, expr, e->v.Call.args);
4109 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4110 return 1;
4111}
4112
4113static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114compiler_call(struct compiler *c, expr_ty e)
4115{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004116 int ret = maybe_optimize_method_call(c, e);
4117 if (ret >= 0) {
4118 return ret;
4119 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004120 if (!check_caller(c, e->v.Call.func)) {
4121 return 0;
4122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 VISIT(c, expr, e->v.Call.func);
4124 return compiler_call_helper(c, 0,
4125 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004126 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004127}
4128
Eric V. Smith235a6f02015-09-19 14:51:32 -04004129static int
4130compiler_joined_str(struct compiler *c, expr_ty e)
4131{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004132 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004133 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4134 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004135 return 1;
4136}
4137
Eric V. Smitha78c7952015-11-03 12:45:05 -05004138/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004139static int
4140compiler_formatted_value(struct compiler *c, expr_ty e)
4141{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004142 /* Our oparg encodes 2 pieces of information: the conversion
4143 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004144
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004145 Convert the conversion char to 3 bits:
4146 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004147 !s : 001 0x1 FVC_STR
4148 !r : 010 0x2 FVC_REPR
4149 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004150
Eric V. Smitha78c7952015-11-03 12:45:05 -05004151 next bit is whether or not we have a format spec:
4152 yes : 100 0x4
4153 no : 000 0x0
4154 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004155
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004156 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004157 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004159 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004160 VISIT(c, expr, e->v.FormattedValue.value);
4161
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004162 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004163 case 's': oparg = FVC_STR; break;
4164 case 'r': oparg = FVC_REPR; break;
4165 case 'a': oparg = FVC_ASCII; break;
4166 case -1: oparg = FVC_NONE; break;
4167 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004168 PyErr_Format(PyExc_SystemError,
4169 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004170 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004171 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004172 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004173 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176 }
4177
Eric V. Smitha78c7952015-11-03 12:45:05 -05004178 /* And push our opcode and oparg */
4179 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004180
Eric V. Smith235a6f02015-09-19 14:51:32 -04004181 return 1;
4182}
4183
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004184static int
4185compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4186{
4187 Py_ssize_t i, n = end - begin;
4188 keyword_ty kw;
4189 PyObject *keys, *key;
4190 assert(n > 0);
4191 if (n > 1) {
4192 for (i = begin; i < end; i++) {
4193 kw = asdl_seq_GET(keywords, i);
4194 VISIT(c, expr, kw->value);
4195 }
4196 keys = PyTuple_New(n);
4197 if (keys == NULL) {
4198 return 0;
4199 }
4200 for (i = begin; i < end; i++) {
4201 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4202 Py_INCREF(key);
4203 PyTuple_SET_ITEM(keys, i - begin, key);
4204 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004205 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004206 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4207 }
4208 else {
4209 /* a for loop only executes once */
4210 for (i = begin; i < end; i++) {
4211 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004212 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004213 VISIT(c, expr, kw->value);
4214 }
4215 ADDOP_I(c, BUILD_MAP, n);
4216 }
4217 return 1;
4218}
4219
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004220/* shared code between compiler_call and compiler_class */
4221static int
4222compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004223 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004224 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004225 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004226{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004227 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004228
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004229 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004230 nkwelts = asdl_seq_LEN(keywords);
4231
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004232 for (i = 0; i < nelts; i++) {
4233 expr_ty elt = asdl_seq_GET(args, i);
4234 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004235 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004236 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004237 }
4238 for (i = 0; i < nkwelts; i++) {
4239 keyword_ty kw = asdl_seq_GET(keywords, i);
4240 if (kw->arg == NULL) {
4241 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244
Mark Shannon13bc1392020-01-23 09:25:17 +00004245 /* No * or ** args, so can use faster calling sequence */
4246 for (i = 0; i < nelts; i++) {
4247 expr_ty elt = asdl_seq_GET(args, i);
4248 assert(elt->kind != Starred_kind);
4249 VISIT(c, expr, elt);
4250 }
4251 if (nkwelts) {
4252 PyObject *names;
4253 VISIT_SEQ(c, keyword, keywords);
4254 names = PyTuple_New(nkwelts);
4255 if (names == NULL) {
4256 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004257 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004258 for (i = 0; i < nkwelts; i++) {
4259 keyword_ty kw = asdl_seq_GET(keywords, i);
4260 Py_INCREF(kw->arg);
4261 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004262 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004263 ADDOP_LOAD_CONST_NEW(c, names);
4264 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4265 return 1;
4266 }
4267 else {
4268 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4269 return 1;
4270 }
4271
4272ex_call:
4273
4274 /* Do positional arguments. */
4275 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4276 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4277 }
4278 else if (starunpack_helper(c, args, n, BUILD_LIST,
4279 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4280 return 0;
4281 }
4282 /* Then keyword arguments */
4283 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004284 /* Has a new dict been pushed */
4285 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004286
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004287 nseen = 0; /* the number of keyword arguments on the stack following */
4288 for (i = 0; i < nkwelts; i++) {
4289 keyword_ty kw = asdl_seq_GET(keywords, i);
4290 if (kw->arg == NULL) {
4291 /* A keyword argument unpacking. */
4292 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004293 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004294 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004295 }
4296 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004297 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004298 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004299 if (!have_dict) {
4300 ADDOP_I(c, BUILD_MAP, 0);
4301 have_dict = 1;
4302 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004303 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004304 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004305 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004306 else {
4307 nseen++;
4308 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004309 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004310 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004311 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004312 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004313 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004314 }
4315 if (have_dict) {
4316 ADDOP_I(c, DICT_MERGE, 1);
4317 }
4318 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004319 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004320 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004322 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324}
4325
Nick Coghlan650f0d02007-04-15 12:05:43 +00004326
4327/* List and set comprehensions and generator expressions work by creating a
4328 nested function to perform the actual iteration. This means that the
4329 iteration variables don't leak into the current scope.
4330 The defined function is called immediately following its definition, with the
4331 result of that call being the result of the expression.
4332 The LC/SC version returns the populated container, while the GE version is
4333 flagged in symtable.c as a generator, so it returns the generator object
4334 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004335
4336 Possible cleanups:
4337 - iterate over the generator sequence instead of using recursion
4338*/
4339
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004341static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342compiler_comprehension_generator(struct compiler *c,
4343 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004344 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004347 comprehension_ty gen;
4348 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4349 if (gen->is_async) {
4350 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004351 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004352 } else {
4353 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004354 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355 }
4356}
4357
4358static int
4359compiler_sync_comprehension_generator(struct compiler *c,
4360 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004361 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 expr_ty elt, expr_ty val, int type)
4363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 /* generate code for the iterator, then each of the ifs,
4365 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 comprehension_ty gen;
4368 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004369 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 start = compiler_new_block(c);
4372 skip = compiler_new_block(c);
4373 if_cleanup = compiler_new_block(c);
4374 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4377 anchor == NULL)
4378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 if (gen_index == 0) {
4383 /* Receive outermost iter as an implicit argument */
4384 c->u->u_argcount = 1;
4385 ADDOP_I(c, LOAD_FAST, 0);
4386 }
4387 else {
4388 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004389 /* Fast path for the temporary variable assignment idiom:
4390 for y in [f(x)]
4391 */
4392 asdl_seq *elts;
4393 switch (gen->iter->kind) {
4394 case List_kind:
4395 elts = gen->iter->v.List.elts;
4396 break;
4397 case Tuple_kind:
4398 elts = gen->iter->v.Tuple.elts;
4399 break;
4400 default:
4401 elts = NULL;
4402 }
4403 if (asdl_seq_LEN(elts) == 1) {
4404 expr_ty elt = asdl_seq_GET(elts, 0);
4405 if (elt->kind != Starred_kind) {
4406 VISIT(c, expr, elt);
4407 start = NULL;
4408 }
4409 }
4410 if (start) {
4411 VISIT(c, expr, gen->iter);
4412 ADDOP(c, GET_ITER);
4413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004415 if (start) {
4416 depth++;
4417 compiler_use_next_block(c, start);
4418 ADDOP_JREL(c, FOR_ITER, anchor);
4419 NEXT_BLOCK(c);
4420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 /* XXX this needs to be cleaned up...a lot! */
4424 n = asdl_seq_LEN(gen->ifs);
4425 for (i = 0; i < n; i++) {
4426 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004427 if (!compiler_jump_if(c, e, if_cleanup, 0))
4428 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 NEXT_BLOCK(c);
4430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 if (++gen_index < asdl_seq_LEN(generators))
4433 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004434 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 elt, val, type))
4436 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 /* only append after the last for generator */
4439 if (gen_index >= asdl_seq_LEN(generators)) {
4440 /* comprehension specific code */
4441 switch (type) {
4442 case COMP_GENEXP:
4443 VISIT(c, expr, elt);
4444 ADDOP(c, YIELD_VALUE);
4445 ADDOP(c, POP_TOP);
4446 break;
4447 case COMP_LISTCOMP:
4448 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004449 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 break;
4451 case COMP_SETCOMP:
4452 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004453 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 break;
4455 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004456 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004459 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004460 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 break;
4462 default:
4463 return 0;
4464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 compiler_use_next_block(c, skip);
4467 }
4468 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004469 if (start) {
4470 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4471 compiler_use_next_block(c, anchor);
4472 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473
4474 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004475}
4476
4477static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004478compiler_async_comprehension_generator(struct compiler *c,
4479 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004480 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004481 expr_ty elt, expr_ty val, int type)
4482{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004483 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004484 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004485 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004486 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004487 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004490 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 return 0;
4492 }
4493
4494 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4495
4496 if (gen_index == 0) {
4497 /* Receive outermost iter as an implicit argument */
4498 c->u->u_argcount = 1;
4499 ADDOP_I(c, LOAD_FAST, 0);
4500 }
4501 else {
4502 /* Sub-iter - calculate on the fly */
4503 VISIT(c, expr, gen->iter);
4504 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505 }
4506
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004507 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004509 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004511 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004513 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004514 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004515
4516 n = asdl_seq_LEN(gen->ifs);
4517 for (i = 0; i < n; i++) {
4518 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004519 if (!compiler_jump_if(c, e, if_cleanup, 0))
4520 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521 NEXT_BLOCK(c);
4522 }
4523
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004524 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 if (++gen_index < asdl_seq_LEN(generators))
4526 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004527 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 elt, val, type))
4529 return 0;
4530
4531 /* only append after the last for generator */
4532 if (gen_index >= asdl_seq_LEN(generators)) {
4533 /* comprehension specific code */
4534 switch (type) {
4535 case COMP_GENEXP:
4536 VISIT(c, expr, elt);
4537 ADDOP(c, YIELD_VALUE);
4538 ADDOP(c, POP_TOP);
4539 break;
4540 case COMP_LISTCOMP:
4541 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004542 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004543 break;
4544 case COMP_SETCOMP:
4545 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004546 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004547 break;
4548 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004549 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004552 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004553 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 break;
4555 default:
4556 return 0;
4557 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558 }
4559 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004560 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4561
4562 compiler_use_next_block(c, except);
4563 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004564
4565 return 1;
4566}
4567
4568static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004569compiler_comprehension(struct compiler *c, expr_ty e, int type,
4570 identifier name, asdl_seq *generators, expr_ty elt,
4571 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004575 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004576 int is_async_function = c->u->u_ste->ste_coroutine;
4577 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004578
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004580
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004581 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4582 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004585 }
4586
4587 is_async_generator = c->u->u_ste->ste_coroutine;
4588
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004589 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590 compiler_error(c, "asynchronous comprehension outside of "
4591 "an asynchronous function");
4592 goto error_in_scope;
4593 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 if (type != COMP_GENEXP) {
4596 int op;
4597 switch (type) {
4598 case COMP_LISTCOMP:
4599 op = BUILD_LIST;
4600 break;
4601 case COMP_SETCOMP:
4602 op = BUILD_SET;
4603 break;
4604 case COMP_DICTCOMP:
4605 op = BUILD_MAP;
4606 break;
4607 default:
4608 PyErr_Format(PyExc_SystemError,
4609 "unknown comprehension type %d", type);
4610 goto error_in_scope;
4611 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 ADDOP_I(c, op, 0);
4614 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004615
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004616 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 val, type))
4618 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 if (type != COMP_GENEXP) {
4621 ADDOP(c, RETURN_VALUE);
4622 }
4623
4624 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004625 qualname = c->u->u_qualname;
4626 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004628 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 goto error;
4630
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004631 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004633 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 Py_DECREF(co);
4635
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004636 VISIT(c, expr, outermost->iter);
4637
4638 if (outermost->is_async) {
4639 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004640 } else {
4641 ADDOP(c, GET_ITER);
4642 }
4643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004645
4646 if (is_async_generator && type != COMP_GENEXP) {
4647 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004648 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004649 ADDOP(c, YIELD_FROM);
4650 }
4651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004653error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004655error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004656 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 Py_XDECREF(co);
4658 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004659}
4660
4661static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004662compiler_genexp(struct compiler *c, expr_ty e)
4663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 static identifier name;
4665 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004666 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 if (!name)
4668 return 0;
4669 }
4670 assert(e->kind == GeneratorExp_kind);
4671 return compiler_comprehension(c, e, COMP_GENEXP, name,
4672 e->v.GeneratorExp.generators,
4673 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004674}
4675
4676static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004677compiler_listcomp(struct compiler *c, expr_ty e)
4678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 static identifier name;
4680 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004681 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 if (!name)
4683 return 0;
4684 }
4685 assert(e->kind == ListComp_kind);
4686 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4687 e->v.ListComp.generators,
4688 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004689}
4690
4691static int
4692compiler_setcomp(struct compiler *c, expr_ty e)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 static identifier name;
4695 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004696 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (!name)
4698 return 0;
4699 }
4700 assert(e->kind == SetComp_kind);
4701 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4702 e->v.SetComp.generators,
4703 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004704}
4705
4706
4707static int
4708compiler_dictcomp(struct compiler *c, expr_ty e)
4709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 static identifier name;
4711 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004712 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 if (!name)
4714 return 0;
4715 }
4716 assert(e->kind == DictComp_kind);
4717 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4718 e->v.DictComp.generators,
4719 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004720}
4721
4722
4723static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004724compiler_visit_keyword(struct compiler *c, keyword_ty k)
4725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 VISIT(c, expr, k->value);
4727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728}
4729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004731 whether they are true or false.
4732
4733 Return values: 1 for true, 0 for false, -1 for non-constant.
4734 */
4735
4736static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004737expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004738{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004739 if (e->kind == Constant_kind) {
4740 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004741 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004742 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004743}
4744
Mark Shannonfee55262019-11-21 09:11:43 +00004745static int
4746compiler_with_except_finish(struct compiler *c) {
4747 basicblock *exit;
4748 exit = compiler_new_block(c);
4749 if (exit == NULL)
4750 return 0;
4751 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4752 ADDOP(c, RERAISE);
4753 compiler_use_next_block(c, exit);
4754 ADDOP(c, POP_TOP);
4755 ADDOP(c, POP_TOP);
4756 ADDOP(c, POP_TOP);
4757 ADDOP(c, POP_EXCEPT);
4758 ADDOP(c, POP_TOP);
4759 return 1;
4760}
Yury Selivanov75445082015-05-11 22:57:16 -04004761
4762/*
4763 Implements the async with statement.
4764
4765 The semantics outlined in that PEP are as follows:
4766
4767 async with EXPR as VAR:
4768 BLOCK
4769
4770 It is implemented roughly as:
4771
4772 context = EXPR
4773 exit = context.__aexit__ # not calling it
4774 value = await context.__aenter__()
4775 try:
4776 VAR = value # if VAR present in the syntax
4777 BLOCK
4778 finally:
4779 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004780 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004781 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004782 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004783 if not (await exit(*exc)):
4784 raise
4785 */
4786static int
4787compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4788{
Mark Shannonfee55262019-11-21 09:11:43 +00004789 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004790 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4791
4792 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004793 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4794 c->u->u_ste->ste_coroutine = 1;
4795 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004796 return compiler_error(c, "'async with' outside async function");
4797 }
Yury Selivanov75445082015-05-11 22:57:16 -04004798
4799 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004800 final = compiler_new_block(c);
4801 exit = compiler_new_block(c);
4802 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004803 return 0;
4804
4805 /* Evaluate EXPR */
4806 VISIT(c, expr, item->context_expr);
4807
4808 ADDOP(c, BEFORE_ASYNC_WITH);
4809 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004810 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004811 ADDOP(c, YIELD_FROM);
4812
Mark Shannonfee55262019-11-21 09:11:43 +00004813 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004814
4815 /* SETUP_ASYNC_WITH pushes a finally block. */
4816 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004817 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004818 return 0;
4819 }
4820
4821 if (item->optional_vars) {
4822 VISIT(c, expr, item->optional_vars);
4823 }
4824 else {
4825 /* Discard result from context.__aenter__() */
4826 ADDOP(c, POP_TOP);
4827 }
4828
4829 pos++;
4830 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4831 /* BLOCK code */
4832 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4833 else if (!compiler_async_with(c, s, pos))
4834 return 0;
4835
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004836 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004837 ADDOP(c, POP_BLOCK);
4838 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004839
Mark Shannonfee55262019-11-21 09:11:43 +00004840 /* For successful outcome:
4841 * call __exit__(None, None, None)
4842 */
4843 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004844 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004845 ADDOP(c, GET_AWAITABLE);
4846 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4847 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004848
Mark Shannonfee55262019-11-21 09:11:43 +00004849 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004850
Mark Shannonfee55262019-11-21 09:11:43 +00004851 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4852
4853 /* For exceptional outcome: */
4854 compiler_use_next_block(c, final);
4855
4856 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004857 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004858 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004859 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004860 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004861
Mark Shannonfee55262019-11-21 09:11:43 +00004862compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004863 return 1;
4864}
4865
4866
Guido van Rossumc2e20742006-02-27 22:32:47 +00004867/*
4868 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004869 with EXPR as VAR:
4870 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004871 is implemented as:
4872 <code for EXPR>
4873 SETUP_WITH E
4874 <code to store to VAR> or POP_TOP
4875 <code for BLOCK>
4876 LOAD_CONST (None, None, None)
4877 CALL_FUNCTION_EX 0
4878 JUMP_FORWARD EXIT
4879 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4880 POP_JUMP_IF_TRUE T:
4881 RERAISE
4882 T: POP_TOP * 3 (remove exception from stack)
4883 POP_EXCEPT
4884 POP_TOP
4885 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004886 */
Mark Shannonfee55262019-11-21 09:11:43 +00004887
Guido van Rossumc2e20742006-02-27 22:32:47 +00004888static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004889compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890{
Mark Shannonfee55262019-11-21 09:11:43 +00004891 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004892 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004893
4894 assert(s->kind == With_kind);
4895
Guido van Rossumc2e20742006-02-27 22:32:47 +00004896 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004897 final = compiler_new_block(c);
4898 exit = compiler_new_block(c);
4899 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004900 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004901
Thomas Wouters477c8d52006-05-27 19:21:47 +00004902 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004903 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004904 /* Will push bound __exit__ */
4905 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004906
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004907 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004909 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004910 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911 }
4912
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004913 if (item->optional_vars) {
4914 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004915 }
4916 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004918 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004919 }
4920
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004921 pos++;
4922 if (pos == asdl_seq_LEN(s->v.With.items))
4923 /* BLOCK code */
4924 VISIT_SEQ(c, stmt, s->v.With.body)
4925 else if (!compiler_with(c, s, pos))
4926 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927
Guido van Rossumc2e20742006-02-27 22:32:47 +00004928 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004929 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004930
Mark Shannonfee55262019-11-21 09:11:43 +00004931 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004932
Mark Shannonfee55262019-11-21 09:11:43 +00004933 /* For successful outcome:
4934 * call __exit__(None, None, None)
4935 */
4936 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004937 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004938 ADDOP(c, POP_TOP);
4939 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004940
Mark Shannonfee55262019-11-21 09:11:43 +00004941 /* For exceptional outcome: */
4942 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943
Mark Shannonfee55262019-11-21 09:11:43 +00004944 ADDOP(c, WITH_EXCEPT_START);
4945 compiler_with_except_finish(c);
4946
4947 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004948 return 1;
4949}
4950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004951static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004952compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004955 case NamedExpr_kind:
4956 VISIT(c, expr, e->v.NamedExpr.value);
4957 ADDOP(c, DUP_TOP);
4958 VISIT(c, expr, e->v.NamedExpr.target);
4959 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 case BoolOp_kind:
4961 return compiler_boolop(c, e);
4962 case BinOp_kind:
4963 VISIT(c, expr, e->v.BinOp.left);
4964 VISIT(c, expr, e->v.BinOp.right);
4965 ADDOP(c, binop(c, e->v.BinOp.op));
4966 break;
4967 case UnaryOp_kind:
4968 VISIT(c, expr, e->v.UnaryOp.operand);
4969 ADDOP(c, unaryop(e->v.UnaryOp.op));
4970 break;
4971 case Lambda_kind:
4972 return compiler_lambda(c, e);
4973 case IfExp_kind:
4974 return compiler_ifexp(c, e);
4975 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004976 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004978 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 case GeneratorExp_kind:
4980 return compiler_genexp(c, e);
4981 case ListComp_kind:
4982 return compiler_listcomp(c, e);
4983 case SetComp_kind:
4984 return compiler_setcomp(c, e);
4985 case DictComp_kind:
4986 return compiler_dictcomp(c, e);
4987 case Yield_kind:
4988 if (c->u->u_ste->ste_type != FunctionBlock)
4989 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004990 if (e->v.Yield.value) {
4991 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 }
4993 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004994 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004996 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004998 case YieldFrom_kind:
4999 if (c->u->u_ste->ste_type != FunctionBlock)
5000 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005001
5002 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5003 return compiler_error(c, "'yield from' inside async function");
5004
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005005 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005006 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005007 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005008 ADDOP(c, YIELD_FROM);
5009 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005010 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005011 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
5012 if (c->u->u_ste->ste_type != FunctionBlock){
5013 return compiler_error(c, "'await' outside function");
5014 }
Yury Selivanov75445082015-05-11 22:57:16 -04005015
Victor Stinner331a6a52019-05-27 16:39:22 +02005016 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005017 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5018 return compiler_error(c, "'await' outside async function");
5019 }
5020 }
Yury Selivanov75445082015-05-11 22:57:16 -04005021
5022 VISIT(c, expr, e->v.Await.value);
5023 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005024 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005025 ADDOP(c, YIELD_FROM);
5026 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 case Compare_kind:
5028 return compiler_compare(c, e);
5029 case Call_kind:
5030 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005031 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005032 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005033 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005034 case JoinedStr_kind:
5035 return compiler_joined_str(c, e);
5036 case FormattedValue_kind:
5037 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 /* The following exprs can be assignment targets. */
5039 case Attribute_kind:
5040 if (e->v.Attribute.ctx != AugStore)
5041 VISIT(c, expr, e->v.Attribute.value);
5042 switch (e->v.Attribute.ctx) {
5043 case AugLoad:
5044 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005045 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 case Load:
5047 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5048 break;
5049 case AugStore:
5050 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005051 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 case Store:
5053 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5054 break;
5055 case Del:
5056 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5057 break;
5058 case Param:
5059 default:
5060 PyErr_SetString(PyExc_SystemError,
5061 "param invalid in attribute expression");
5062 return 0;
5063 }
5064 break;
5065 case Subscript_kind:
5066 switch (e->v.Subscript.ctx) {
5067 case AugLoad:
5068 VISIT(c, expr, e->v.Subscript.value);
5069 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5070 break;
5071 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005072 if (!check_subscripter(c, e->v.Subscript.value)) {
5073 return 0;
5074 }
5075 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5076 return 0;
5077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 VISIT(c, expr, e->v.Subscript.value);
5079 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5080 break;
5081 case AugStore:
5082 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5083 break;
5084 case Store:
5085 VISIT(c, expr, e->v.Subscript.value);
5086 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5087 break;
5088 case Del:
5089 VISIT(c, expr, e->v.Subscript.value);
5090 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5091 break;
5092 case Param:
5093 default:
5094 PyErr_SetString(PyExc_SystemError,
5095 "param invalid in subscript expression");
5096 return 0;
5097 }
5098 break;
5099 case Starred_kind:
5100 switch (e->v.Starred.ctx) {
5101 case Store:
5102 /* In all legitimate cases, the Starred node was already replaced
5103 * by compiler_list/compiler_tuple. XXX: is that okay? */
5104 return compiler_error(c,
5105 "starred assignment target must be in a list or tuple");
5106 default:
5107 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005108 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 case Name_kind:
5111 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5112 /* child nodes of List and Tuple will have expr_context set */
5113 case List_kind:
5114 return compiler_list(c, e);
5115 case Tuple_kind:
5116 return compiler_tuple(c, e);
5117 }
5118 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005119}
5120
5121static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005122compiler_visit_expr(struct compiler *c, expr_ty e)
5123{
5124 /* If expr e has a different line number than the last expr/stmt,
5125 set a new line number for the next instruction.
5126 */
5127 int old_lineno = c->u->u_lineno;
5128 int old_col_offset = c->u->u_col_offset;
5129 if (e->lineno != c->u->u_lineno) {
5130 c->u->u_lineno = e->lineno;
5131 c->u->u_lineno_set = 0;
5132 }
5133 /* Updating the column offset is always harmless. */
5134 c->u->u_col_offset = e->col_offset;
5135
5136 int res = compiler_visit_expr1(c, e);
5137
5138 if (old_lineno != c->u->u_lineno) {
5139 c->u->u_lineno = old_lineno;
5140 c->u->u_lineno_set = 0;
5141 }
5142 c->u->u_col_offset = old_col_offset;
5143 return res;
5144}
5145
5146static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005147compiler_augassign(struct compiler *c, stmt_ty s)
5148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 expr_ty e = s->v.AugAssign.target;
5150 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 switch (e->kind) {
5155 case Attribute_kind:
5156 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005157 AugLoad, e->lineno, e->col_offset,
5158 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 if (auge == NULL)
5160 return 0;
5161 VISIT(c, expr, auge);
5162 VISIT(c, expr, s->v.AugAssign.value);
5163 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5164 auge->v.Attribute.ctx = AugStore;
5165 VISIT(c, expr, auge);
5166 break;
5167 case Subscript_kind:
5168 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005169 AugLoad, e->lineno, e->col_offset,
5170 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 if (auge == NULL)
5172 return 0;
5173 VISIT(c, expr, auge);
5174 VISIT(c, expr, s->v.AugAssign.value);
5175 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5176 auge->v.Subscript.ctx = AugStore;
5177 VISIT(c, expr, auge);
5178 break;
5179 case Name_kind:
5180 if (!compiler_nameop(c, e->v.Name.id, Load))
5181 return 0;
5182 VISIT(c, expr, s->v.AugAssign.value);
5183 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5184 return compiler_nameop(c, e->v.Name.id, Store);
5185 default:
5186 PyErr_Format(PyExc_SystemError,
5187 "invalid node type (%d) for augmented assignment",
5188 e->kind);
5189 return 0;
5190 }
5191 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005192}
5193
5194static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005195check_ann_expr(struct compiler *c, expr_ty e)
5196{
5197 VISIT(c, expr, e);
5198 ADDOP(c, POP_TOP);
5199 return 1;
5200}
5201
5202static int
5203check_annotation(struct compiler *c, stmt_ty s)
5204{
5205 /* Annotations are only evaluated in a module or class. */
5206 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5207 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5208 return check_ann_expr(c, s->v.AnnAssign.annotation);
5209 }
5210 return 1;
5211}
5212
5213static int
5214check_ann_slice(struct compiler *c, slice_ty sl)
5215{
5216 switch(sl->kind) {
5217 case Index_kind:
5218 return check_ann_expr(c, sl->v.Index.value);
5219 case Slice_kind:
5220 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5221 return 0;
5222 }
5223 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5224 return 0;
5225 }
5226 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5227 return 0;
5228 }
5229 break;
5230 default:
5231 PyErr_SetString(PyExc_SystemError,
5232 "unexpected slice kind");
5233 return 0;
5234 }
5235 return 1;
5236}
5237
5238static int
5239check_ann_subscr(struct compiler *c, slice_ty sl)
5240{
5241 /* We check that everything in a subscript is defined at runtime. */
5242 Py_ssize_t i, n;
5243
5244 switch (sl->kind) {
5245 case Index_kind:
5246 case Slice_kind:
5247 if (!check_ann_slice(c, sl)) {
5248 return 0;
5249 }
5250 break;
5251 case ExtSlice_kind:
5252 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5253 for (i = 0; i < n; i++) {
5254 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5255 switch (subsl->kind) {
5256 case Index_kind:
5257 case Slice_kind:
5258 if (!check_ann_slice(c, subsl)) {
5259 return 0;
5260 }
5261 break;
5262 case ExtSlice_kind:
5263 default:
5264 PyErr_SetString(PyExc_SystemError,
5265 "extended slice invalid in nested slice");
5266 return 0;
5267 }
5268 }
5269 break;
5270 default:
5271 PyErr_Format(PyExc_SystemError,
5272 "invalid subscript kind %d", sl->kind);
5273 return 0;
5274 }
5275 return 1;
5276}
5277
5278static int
5279compiler_annassign(struct compiler *c, stmt_ty s)
5280{
5281 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005282 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005283
5284 assert(s->kind == AnnAssign_kind);
5285
5286 /* We perform the actual assignment first. */
5287 if (s->v.AnnAssign.value) {
5288 VISIT(c, expr, s->v.AnnAssign.value);
5289 VISIT(c, expr, targ);
5290 }
5291 switch (targ->kind) {
5292 case Name_kind:
5293 /* If we have a simple name in a module or class, store annotation. */
5294 if (s->v.AnnAssign.simple &&
5295 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5296 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005297 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5298 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5299 }
5300 else {
5301 VISIT(c, expr, s->v.AnnAssign.annotation);
5302 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005303 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005304 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005305 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005306 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005307 }
5308 break;
5309 case Attribute_kind:
5310 if (!s->v.AnnAssign.value &&
5311 !check_ann_expr(c, targ->v.Attribute.value)) {
5312 return 0;
5313 }
5314 break;
5315 case Subscript_kind:
5316 if (!s->v.AnnAssign.value &&
5317 (!check_ann_expr(c, targ->v.Subscript.value) ||
5318 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5319 return 0;
5320 }
5321 break;
5322 default:
5323 PyErr_Format(PyExc_SystemError,
5324 "invalid node type (%d) for annotated assignment",
5325 targ->kind);
5326 return 0;
5327 }
5328 /* Annotation is evaluated last. */
5329 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5330 return 0;
5331 }
5332 return 1;
5333}
5334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005335/* Raises a SyntaxError and returns 0.
5336 If something goes wrong, a different exception may be raised.
5337*/
5338
5339static int
5340compiler_error(struct compiler *c, const char *errstr)
5341{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005342 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005344
Victor Stinner14e461d2013-08-26 22:28:21 +02005345 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 if (!loc) {
5347 Py_INCREF(Py_None);
5348 loc = Py_None;
5349 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005350 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005351 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 if (!u)
5353 goto exit;
5354 v = Py_BuildValue("(zO)", errstr, u);
5355 if (!v)
5356 goto exit;
5357 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005358 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 Py_DECREF(loc);
5360 Py_XDECREF(u);
5361 Py_XDECREF(v);
5362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005363}
5364
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005365/* Emits a SyntaxWarning and returns 1 on success.
5366 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5367 and returns 0.
5368*/
5369static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005370compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005371{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005372 va_list vargs;
5373#ifdef HAVE_STDARG_PROTOTYPES
5374 va_start(vargs, format);
5375#else
5376 va_start(vargs);
5377#endif
5378 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5379 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005380 if (msg == NULL) {
5381 return 0;
5382 }
5383 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5384 c->u->u_lineno, NULL, NULL) < 0)
5385 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005386 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005387 /* Replace the SyntaxWarning exception with a SyntaxError
5388 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005389 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005390 assert(PyUnicode_AsUTF8(msg) != NULL);
5391 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005392 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005393 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005394 return 0;
5395 }
5396 Py_DECREF(msg);
5397 return 1;
5398}
5399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401compiler_handle_subscr(struct compiler *c, const char *kind,
5402 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 /* XXX this code is duplicated */
5407 switch (ctx) {
5408 case AugLoad: /* fall through to Load */
5409 case Load: op = BINARY_SUBSCR; break;
5410 case AugStore:/* fall through to Store */
5411 case Store: op = STORE_SUBSCR; break;
5412 case Del: op = DELETE_SUBSCR; break;
5413 case Param:
5414 PyErr_Format(PyExc_SystemError,
5415 "invalid %s kind %d in subscript\n",
5416 kind, ctx);
5417 return 0;
5418 }
5419 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005420 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 }
5422 else if (ctx == AugStore) {
5423 ADDOP(c, ROT_THREE);
5424 }
5425 ADDOP(c, op);
5426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427}
5428
5429static int
5430compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 int n = 2;
5433 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 /* only handles the cases where BUILD_SLICE is emitted */
5436 if (s->v.Slice.lower) {
5437 VISIT(c, expr, s->v.Slice.lower);
5438 }
5439 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005440 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 if (s->v.Slice.upper) {
5444 VISIT(c, expr, s->v.Slice.upper);
5445 }
5446 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005447 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 }
5449
5450 if (s->v.Slice.step) {
5451 n++;
5452 VISIT(c, expr, s->v.Slice.step);
5453 }
5454 ADDOP_I(c, BUILD_SLICE, n);
5455 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005456}
5457
5458static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5460 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 switch (s->kind) {
5463 case Slice_kind:
5464 return compiler_slice(c, s, ctx);
5465 case Index_kind:
5466 VISIT(c, expr, s->v.Index.value);
5467 break;
5468 case ExtSlice_kind:
5469 default:
5470 PyErr_SetString(PyExc_SystemError,
5471 "extended slice invalid in nested slice");
5472 return 0;
5473 }
5474 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475}
5476
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005477static int
5478compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5479{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005480 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 switch (s->kind) {
5482 case Index_kind:
5483 kindname = "index";
5484 if (ctx != AugStore) {
5485 VISIT(c, expr, s->v.Index.value);
5486 }
5487 break;
5488 case Slice_kind:
5489 kindname = "slice";
5490 if (ctx != AugStore) {
5491 if (!compiler_slice(c, s, ctx))
5492 return 0;
5493 }
5494 break;
5495 case ExtSlice_kind:
5496 kindname = "extended slice";
5497 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005498 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 for (i = 0; i < n; i++) {
5500 slice_ty sub = (slice_ty)asdl_seq_GET(
5501 s->v.ExtSlice.dims, i);
5502 if (!compiler_visit_nested_slice(c, sub, ctx))
5503 return 0;
5504 }
5505 ADDOP_I(c, BUILD_TUPLE, n);
5506 }
5507 break;
5508 default:
5509 PyErr_Format(PyExc_SystemError,
5510 "invalid subscript kind %d", s->kind);
5511 return 0;
5512 }
5513 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005514}
5515
Thomas Wouters89f507f2006-12-13 04:49:30 +00005516/* End of the compiler section, beginning of the assembler section */
5517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005518/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005519 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005520
5521 XXX must handle implicit jumps from one block to next
5522*/
5523
Thomas Wouters89f507f2006-12-13 04:49:30 +00005524struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 PyObject *a_bytecode; /* string containing bytecode */
5526 int a_offset; /* offset into bytecode */
5527 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005528 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 PyObject *a_lnotab; /* string containing lnotab */
5530 int a_lnotab_off; /* offset into lnotab */
5531 int a_lineno; /* last lineno of emitted instruction */
5532 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005533};
5534
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005535static void
T. Wouters99b54d62019-09-12 07:05:33 -07005536dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005537{
T. Wouters99b54d62019-09-12 07:05:33 -07005538 int i, j;
5539
5540 /* Get rid of recursion for normal control flow.
5541 Since the number of blocks is limited, unused space in a_postorder
5542 (from a_nblocks to end) can be used as a stack for still not ordered
5543 blocks. */
5544 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005545 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005546 assert(a->a_nblocks < j);
5547 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 }
T. Wouters99b54d62019-09-12 07:05:33 -07005549 while (j < end) {
5550 b = a->a_postorder[j++];
5551 for (i = 0; i < b->b_iused; i++) {
5552 struct instr *instr = &b->b_instr[i];
5553 if (instr->i_jrel || instr->i_jabs)
5554 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005555 }
T. Wouters99b54d62019-09-12 07:05:33 -07005556 assert(a->a_nblocks < j);
5557 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005558 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005559}
5560
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005561Py_LOCAL_INLINE(void)
5562stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005563{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005564 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005565 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005566 assert(b->b_startdepth < 0);
5567 b->b_startdepth = depth;
5568 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005569 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570}
5571
5572/* Find the flow path that needs the largest stack. We assume that
5573 * cycles in the flow graph have no net effect on the stack depth.
5574 */
5575static int
5576stackdepth(struct compiler *c)
5577{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005578 basicblock *b, *entryblock = NULL;
5579 basicblock **stack, **sp;
5580 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 b->b_startdepth = INT_MIN;
5583 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005584 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 }
5586 if (!entryblock)
5587 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005588 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5589 if (!stack) {
5590 PyErr_NoMemory();
5591 return -1;
5592 }
5593
5594 sp = stack;
5595 stackdepth_push(&sp, entryblock, 0);
5596 while (sp != stack) {
5597 b = *--sp;
5598 int depth = b->b_startdepth;
5599 assert(depth >= 0);
5600 basicblock *next = b->b_next;
5601 for (int i = 0; i < b->b_iused; i++) {
5602 struct instr *instr = &b->b_instr[i];
5603 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5604 if (effect == PY_INVALID_STACK_EFFECT) {
5605 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5606 Py_FatalError("PyCompile_OpcodeStackEffect()");
5607 }
5608 int new_depth = depth + effect;
5609 if (new_depth > maxdepth) {
5610 maxdepth = new_depth;
5611 }
5612 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5613 if (instr->i_jrel || instr->i_jabs) {
5614 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5615 assert(effect != PY_INVALID_STACK_EFFECT);
5616 int target_depth = depth + effect;
5617 if (target_depth > maxdepth) {
5618 maxdepth = target_depth;
5619 }
5620 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005621 stackdepth_push(&sp, instr->i_target, target_depth);
5622 }
5623 depth = new_depth;
5624 if (instr->i_opcode == JUMP_ABSOLUTE ||
5625 instr->i_opcode == JUMP_FORWARD ||
5626 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005627 instr->i_opcode == RAISE_VARARGS ||
5628 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005629 {
5630 /* remaining code is dead */
5631 next = NULL;
5632 break;
5633 }
5634 }
5635 if (next != NULL) {
5636 stackdepth_push(&sp, next, depth);
5637 }
5638 }
5639 PyObject_Free(stack);
5640 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005641}
5642
5643static int
5644assemble_init(struct assembler *a, int nblocks, int firstlineno)
5645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 memset(a, 0, sizeof(struct assembler));
5647 a->a_lineno = firstlineno;
5648 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5649 if (!a->a_bytecode)
5650 return 0;
5651 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5652 if (!a->a_lnotab)
5653 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005654 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 PyErr_NoMemory();
5656 return 0;
5657 }
T. Wouters99b54d62019-09-12 07:05:33 -07005658 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005660 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 PyErr_NoMemory();
5662 return 0;
5663 }
5664 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005665}
5666
5667static void
5668assemble_free(struct assembler *a)
5669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 Py_XDECREF(a->a_bytecode);
5671 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005672 if (a->a_postorder)
5673 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005674}
5675
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676static int
5677blocksize(basicblock *b)
5678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 int i;
5680 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005683 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005685}
5686
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005687/* Appends a pair to the end of the line number table, a_lnotab, representing
5688 the instruction's bytecode offset and line number. See
5689 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005690
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005692assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005695 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005697
Serhiy Storchakaab874002016-09-11 13:48:15 +03005698 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 if(d_bytecode == 0 && d_lineno == 0)
5704 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 if (d_bytecode > 255) {
5707 int j, nbytes, ncodes = d_bytecode / 255;
5708 nbytes = a->a_lnotab_off + 2 * ncodes;
5709 len = PyBytes_GET_SIZE(a->a_lnotab);
5710 if (nbytes >= len) {
5711 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5712 len = nbytes;
5713 else if (len <= INT_MAX / 2)
5714 len *= 2;
5715 else {
5716 PyErr_NoMemory();
5717 return 0;
5718 }
5719 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5720 return 0;
5721 }
5722 lnotab = (unsigned char *)
5723 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5724 for (j = 0; j < ncodes; j++) {
5725 *lnotab++ = 255;
5726 *lnotab++ = 0;
5727 }
5728 d_bytecode -= ncodes * 255;
5729 a->a_lnotab_off += ncodes * 2;
5730 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005731 assert(0 <= d_bytecode && d_bytecode <= 255);
5732
5733 if (d_lineno < -128 || 127 < d_lineno) {
5734 int j, nbytes, ncodes, k;
5735 if (d_lineno < 0) {
5736 k = -128;
5737 /* use division on positive numbers */
5738 ncodes = (-d_lineno) / 128;
5739 }
5740 else {
5741 k = 127;
5742 ncodes = d_lineno / 127;
5743 }
5744 d_lineno -= ncodes * k;
5745 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 nbytes = a->a_lnotab_off + 2 * ncodes;
5747 len = PyBytes_GET_SIZE(a->a_lnotab);
5748 if (nbytes >= len) {
5749 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5750 len = nbytes;
5751 else if (len <= INT_MAX / 2)
5752 len *= 2;
5753 else {
5754 PyErr_NoMemory();
5755 return 0;
5756 }
5757 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5758 return 0;
5759 }
5760 lnotab = (unsigned char *)
5761 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5762 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005763 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 d_bytecode = 0;
5765 for (j = 1; j < ncodes; j++) {
5766 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005767 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 a->a_lnotab_off += ncodes * 2;
5770 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005771 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 len = PyBytes_GET_SIZE(a->a_lnotab);
5774 if (a->a_lnotab_off + 2 >= len) {
5775 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5776 return 0;
5777 }
5778 lnotab = (unsigned char *)
5779 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 a->a_lnotab_off += 2;
5782 if (d_bytecode) {
5783 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005784 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 }
5786 else { /* First line of a block; def stmt, etc. */
5787 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005788 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 }
5790 a->a_lineno = i->i_lineno;
5791 a->a_lineno_off = a->a_offset;
5792 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005793}
5794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005795/* assemble_emit()
5796 Extend the bytecode with a new instruction.
5797 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005798*/
5799
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005800static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005801assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005802{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005803 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005805 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005806
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005807 arg = i->i_oparg;
5808 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 if (i->i_lineno && !assemble_lnotab(a, i))
5810 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005811 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 if (len > PY_SSIZE_T_MAX / 2)
5813 return 0;
5814 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5815 return 0;
5816 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005817 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005819 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005821}
5822
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005823static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005824assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005827 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 /* Compute the size of each block and fixup jump args.
5831 Replace block pointer with position in bytecode. */
5832 do {
5833 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005834 for (i = a->a_nblocks - 1; i >= 0; i--) {
5835 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 bsize = blocksize(b);
5837 b->b_offset = totsize;
5838 totsize += bsize;
5839 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005840 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5842 bsize = b->b_offset;
5843 for (i = 0; i < b->b_iused; i++) {
5844 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005845 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 /* Relative jumps are computed relative to
5847 the instruction pointer after fetching
5848 the jump instruction.
5849 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005850 bsize += isize;
5851 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005853 if (instr->i_jrel) {
5854 instr->i_oparg -= bsize;
5855 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005856 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005857 if (instrsize(instr->i_oparg) != isize) {
5858 extended_arg_recompile = 1;
5859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 }
5862 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 /* XXX: This is an awful hack that could hurt performance, but
5865 on the bright side it should work until we come up
5866 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 The issue is that in the first loop blocksize() is called
5869 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005870 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 So we loop until we stop seeing new EXTENDED_ARGs.
5874 The only EXTENDED_ARGs that could be popping up are
5875 ones in jump instructions. So this should converge
5876 fairly quickly.
5877 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005878 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005879}
5880
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005881static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005882dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005885 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 tuple = PyTuple_New(size);
5888 if (tuple == NULL)
5889 return NULL;
5890 while (PyDict_Next(dict, &pos, &k, &v)) {
5891 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005892 Py_INCREF(k);
5893 assert((i - offset) < size);
5894 assert((i - offset) >= 0);
5895 PyTuple_SET_ITEM(tuple, i - offset, k);
5896 }
5897 return tuple;
5898}
5899
5900static PyObject *
5901consts_dict_keys_inorder(PyObject *dict)
5902{
5903 PyObject *consts, *k, *v;
5904 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5905
5906 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5907 if (consts == NULL)
5908 return NULL;
5909 while (PyDict_Next(dict, &pos, &k, &v)) {
5910 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005911 /* The keys of the dictionary can be tuples wrapping a contant.
5912 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5913 * the object we want is always second. */
5914 if (PyTuple_CheckExact(k)) {
5915 k = PyTuple_GET_ITEM(k, 1);
5916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005918 assert(i < size);
5919 assert(i >= 0);
5920 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005922 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005923}
5924
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005925static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005926compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005929 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005931 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 if (ste->ste_nested)
5933 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005934 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005936 if (!ste->ste_generator && ste->ste_coroutine)
5937 flags |= CO_COROUTINE;
5938 if (ste->ste_generator && ste->ste_coroutine)
5939 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 if (ste->ste_varargs)
5941 flags |= CO_VARARGS;
5942 if (ste->ste_varkeywords)
5943 flags |= CO_VARKEYWORDS;
5944 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 /* (Only) inherit compilerflags in PyCF_MASK */
5947 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005948
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005949 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5950 ste->ste_coroutine &&
5951 !ste->ste_generator) {
5952 flags |= CO_COROUTINE;
5953 }
5954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005956}
5957
INADA Naokic2e16072018-11-26 21:23:22 +09005958// Merge *tuple* with constant cache.
5959// Unlike merge_consts_recursive(), this function doesn't work recursively.
5960static int
5961merge_const_tuple(struct compiler *c, PyObject **tuple)
5962{
5963 assert(PyTuple_CheckExact(*tuple));
5964
5965 PyObject *key = _PyCode_ConstantKey(*tuple);
5966 if (key == NULL) {
5967 return 0;
5968 }
5969
5970 // t is borrowed reference
5971 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5972 Py_DECREF(key);
5973 if (t == NULL) {
5974 return 0;
5975 }
5976 if (t == key) { // tuple is new constant.
5977 return 1;
5978 }
5979
5980 PyObject *u = PyTuple_GET_ITEM(t, 1);
5981 Py_INCREF(u);
5982 Py_DECREF(*tuple);
5983 *tuple = u;
5984 return 1;
5985}
5986
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005987static PyCodeObject *
5988makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 PyObject *tmp;
5991 PyCodeObject *co = NULL;
5992 PyObject *consts = NULL;
5993 PyObject *names = NULL;
5994 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 PyObject *name = NULL;
5996 PyObject *freevars = NULL;
5997 PyObject *cellvars = NULL;
5998 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005999 Py_ssize_t nlocals;
6000 int nlocals_int;
6001 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006002 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006003
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006004 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006005 names = dict_keys_inorder(c->u->u_names, 0);
6006 varnames = dict_keys_inorder(c->u->u_varnames, 0);
6007 if (!consts || !names || !varnames)
6008 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6011 if (!cellvars)
6012 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006013 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 if (!freevars)
6015 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006016
INADA Naokic2e16072018-11-26 21:23:22 +09006017 if (!merge_const_tuple(c, &names) ||
6018 !merge_const_tuple(c, &varnames) ||
6019 !merge_const_tuple(c, &cellvars) ||
6020 !merge_const_tuple(c, &freevars))
6021 {
6022 goto error;
6023 }
6024
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006025 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006026 assert(nlocals < INT_MAX);
6027 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 flags = compute_code_flags(c);
6030 if (flags < 0)
6031 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006033 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
6034 if (!bytecode)
6035 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6038 if (!tmp)
6039 goto error;
6040 Py_DECREF(consts);
6041 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09006042 if (!merge_const_tuple(c, &consts)) {
6043 goto error;
6044 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006046 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006047 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006048 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006049 maxdepth = stackdepth(c);
6050 if (maxdepth < 0) {
6051 goto error;
6052 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006053 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006054 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006055 maxdepth, flags, bytecode, consts, names,
6056 varnames, freevars, cellvars, c->c_filename,
6057 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006058 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006059 Py_XDECREF(consts);
6060 Py_XDECREF(names);
6061 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006062 Py_XDECREF(name);
6063 Py_XDECREF(freevars);
6064 Py_XDECREF(cellvars);
6065 Py_XDECREF(bytecode);
6066 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006067}
6068
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006069
6070/* For debugging purposes only */
6071#if 0
6072static void
6073dump_instr(const struct instr *i)
6074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 const char *jrel = i->i_jrel ? "jrel " : "";
6076 const char *jabs = i->i_jabs ? "jabs " : "";
6077 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006079 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006080 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006081 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006083 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6084 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006085}
6086
6087static void
6088dump_basicblock(const basicblock *b)
6089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006090 const char *seen = b->b_seen ? "seen " : "";
6091 const char *b_return = b->b_return ? "return " : "";
6092 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6093 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6094 if (b->b_instr) {
6095 int i;
6096 for (i = 0; i < b->b_iused; i++) {
6097 fprintf(stderr, " [%02d] ", i);
6098 dump_instr(b->b_instr + i);
6099 }
6100 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006101}
6102#endif
6103
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006104static PyCodeObject *
6105assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006107 basicblock *b, *entryblock;
6108 struct assembler a;
6109 int i, j, nblocks;
6110 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006112 /* Make sure every block that falls off the end returns None.
6113 XXX NEXT_BLOCK() isn't quite right, because if the last
6114 block ends with a jump or return b_next shouldn't set.
6115 */
6116 if (!c->u->u_curblock->b_return) {
6117 NEXT_BLOCK(c);
6118 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006119 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006120 ADDOP(c, RETURN_VALUE);
6121 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006123 nblocks = 0;
6124 entryblock = NULL;
6125 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6126 nblocks++;
6127 entryblock = b;
6128 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006130 /* Set firstlineno if it wasn't explicitly set. */
6131 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006132 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006133 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6134 else
6135 c->u->u_firstlineno = 1;
6136 }
6137 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6138 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006139 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006141 /* Can't modify the bytecode after computing jump offsets. */
6142 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006143
T. Wouters99b54d62019-09-12 07:05:33 -07006144 /* Emit code in reverse postorder from dfs. */
6145 for (i = a.a_nblocks - 1; i >= 0; i--) {
6146 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006147 for (j = 0; j < b->b_iused; j++)
6148 if (!assemble_emit(&a, &b->b_instr[j]))
6149 goto error;
6150 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006152 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6153 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006154 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006155 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006158 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 assemble_free(&a);
6160 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006161}
Georg Brandl8334fd92010-12-04 10:26:46 +00006162
6163#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006164PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006165PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6166 PyArena *arena)
6167{
6168 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6169}