blob: f228e16079b2899c352273006485b49040d87fd8 [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;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003768 }
3769 else if (elt->kind == Starred_kind) {
3770 return compiler_error(c,
3771 "two starred expressions in assignment");
3772 }
3773 }
3774 if (!seen_star) {
3775 ADDOP_I(c, UNPACK_SEQUENCE, n);
3776 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003777 for (i = 0; i < n; i++) {
3778 expr_ty elt = asdl_seq_GET(elts, i);
3779 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3780 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 return 1;
3782}
3783
3784static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785compiler_list(struct compiler *c, expr_ty e)
3786{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003787 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003788 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003792 return starunpack_helper(c, elts, 0, BUILD_LIST,
3793 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 else
3796 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798}
3799
3800static int
3801compiler_tuple(struct compiler *c, expr_ty e)
3802{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003804 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 return assignment_helper(c, elts);
3806 }
3807 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003808 return starunpack_helper(c, elts, 0, BUILD_LIST,
3809 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003810 }
3811 else
3812 VISIT_SEQ(c, expr, elts);
3813 return 1;
3814}
3815
3816static int
3817compiler_set(struct compiler *c, expr_ty e)
3818{
Mark Shannon13bc1392020-01-23 09:25:17 +00003819 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3820 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003821}
3822
3823static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003824are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3825{
3826 Py_ssize_t i;
3827 for (i = begin; i < end; i++) {
3828 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003829 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003830 return 0;
3831 }
3832 return 1;
3833}
3834
3835static int
3836compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3837{
3838 Py_ssize_t i, n = end - begin;
3839 PyObject *keys, *key;
3840 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3841 for (i = begin; i < end; i++) {
3842 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3843 }
3844 keys = PyTuple_New(n);
3845 if (keys == NULL) {
3846 return 0;
3847 }
3848 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003849 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003850 Py_INCREF(key);
3851 PyTuple_SET_ITEM(keys, i - begin, key);
3852 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003853 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003854 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3855 }
3856 else {
3857 for (i = begin; i < end; i++) {
3858 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3859 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3860 }
3861 ADDOP_I(c, BUILD_MAP, n);
3862 }
3863 return 1;
3864}
3865
3866static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003867compiler_dict(struct compiler *c, expr_ty e)
3868{
Victor Stinner976bb402016-03-23 11:36:19 +01003869 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003870 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871 int is_unpacking = 0;
3872 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003873 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003874 elements = 0;
3875 for (i = 0; i < n; i++) {
3876 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 if (elements) {
3879 if (!compiler_subdict(c, e, i - elements, i)) {
3880 return 0;
3881 }
3882 if (have_dict) {
3883 ADDOP_I(c, DICT_UPDATE, 1);
3884 }
3885 have_dict = 1;
3886 elements = 0;
3887 }
3888 if (have_dict == 0) {
3889 ADDOP_I(c, BUILD_MAP, 0);
3890 have_dict = 1;
3891 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003892 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003893 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003894 }
3895 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003896 if (elements == 0xFFFF) {
3897 if (!compiler_subdict(c, e, i - elements, i)) {
3898 return 0;
3899 }
3900 if (have_dict) {
3901 ADDOP_I(c, DICT_UPDATE, 1);
3902 }
3903 have_dict = 1;
3904 elements = 0;
3905 }
3906 else {
3907 elements++;
3908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 }
3910 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003911 if (elements) {
3912 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003913 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003914 }
3915 if (have_dict) {
3916 ADDOP_I(c, DICT_UPDATE, 1);
3917 }
3918 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003919 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003920 if (!have_dict) {
3921 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 }
3923 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003924}
3925
3926static int
3927compiler_compare(struct compiler *c, expr_ty e)
3928{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003929 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003931 if (!check_compare(c, e)) {
3932 return 0;
3933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003935 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3936 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3937 if (n == 0) {
3938 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003939 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003940 }
3941 else {
3942 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 if (cleanup == NULL)
3944 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003945 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 VISIT(c, expr,
3947 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003948 ADDOP(c, DUP_TOP);
3949 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003950 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003951 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3952 NEXT_BLOCK(c);
3953 }
3954 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003955 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 basicblock *end = compiler_new_block(c);
3957 if (end == NULL)
3958 return 0;
3959 ADDOP_JREL(c, JUMP_FORWARD, end);
3960 compiler_use_next_block(c, cleanup);
3961 ADDOP(c, ROT_TWO);
3962 ADDOP(c, POP_TOP);
3963 compiler_use_next_block(c, end);
3964 }
3965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966}
3967
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003968static PyTypeObject *
3969infer_type(expr_ty e)
3970{
3971 switch (e->kind) {
3972 case Tuple_kind:
3973 return &PyTuple_Type;
3974 case List_kind:
3975 case ListComp_kind:
3976 return &PyList_Type;
3977 case Dict_kind:
3978 case DictComp_kind:
3979 return &PyDict_Type;
3980 case Set_kind:
3981 case SetComp_kind:
3982 return &PySet_Type;
3983 case GeneratorExp_kind:
3984 return &PyGen_Type;
3985 case Lambda_kind:
3986 return &PyFunction_Type;
3987 case JoinedStr_kind:
3988 case FormattedValue_kind:
3989 return &PyUnicode_Type;
3990 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003991 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003992 default:
3993 return NULL;
3994 }
3995}
3996
3997static int
3998check_caller(struct compiler *c, expr_ty e)
3999{
4000 switch (e->kind) {
4001 case Constant_kind:
4002 case Tuple_kind:
4003 case List_kind:
4004 case ListComp_kind:
4005 case Dict_kind:
4006 case DictComp_kind:
4007 case Set_kind:
4008 case SetComp_kind:
4009 case GeneratorExp_kind:
4010 case JoinedStr_kind:
4011 case FormattedValue_kind:
4012 return compiler_warn(c, "'%.200s' object is not callable; "
4013 "perhaps you missed a comma?",
4014 infer_type(e)->tp_name);
4015 default:
4016 return 1;
4017 }
4018}
4019
4020static int
4021check_subscripter(struct compiler *c, expr_ty e)
4022{
4023 PyObject *v;
4024
4025 switch (e->kind) {
4026 case Constant_kind:
4027 v = e->v.Constant.value;
4028 if (!(v == Py_None || v == Py_Ellipsis ||
4029 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4030 PyAnySet_Check(v)))
4031 {
4032 return 1;
4033 }
4034 /* fall through */
4035 case Set_kind:
4036 case SetComp_kind:
4037 case GeneratorExp_kind:
4038 case Lambda_kind:
4039 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4040 "perhaps you missed a comma?",
4041 infer_type(e)->tp_name);
4042 default:
4043 return 1;
4044 }
4045}
4046
4047static int
4048check_index(struct compiler *c, expr_ty e, slice_ty s)
4049{
4050 PyObject *v;
4051
4052 if (s->kind != Index_kind) {
4053 return 1;
4054 }
4055 PyTypeObject *index_type = infer_type(s->v.Index.value);
4056 if (index_type == NULL
4057 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4058 || index_type == &PySlice_Type) {
4059 return 1;
4060 }
4061
4062 switch (e->kind) {
4063 case Constant_kind:
4064 v = e->v.Constant.value;
4065 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4066 return 1;
4067 }
4068 /* fall through */
4069 case Tuple_kind:
4070 case List_kind:
4071 case ListComp_kind:
4072 case JoinedStr_kind:
4073 case FormattedValue_kind:
4074 return compiler_warn(c, "%.200s indices must be integers or slices, "
4075 "not %.200s; "
4076 "perhaps you missed a comma?",
4077 infer_type(e)->tp_name,
4078 index_type->tp_name);
4079 default:
4080 return 1;
4081 }
4082}
4083
Zackery Spytz97f5de02019-03-22 01:30:32 -06004084// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004086maybe_optimize_method_call(struct compiler *c, expr_ty e)
4087{
4088 Py_ssize_t argsl, i;
4089 expr_ty meth = e->v.Call.func;
4090 asdl_seq *args = e->v.Call.args;
4091
4092 /* Check that the call node is an attribute access, and that
4093 the call doesn't have keyword parameters. */
4094 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4095 asdl_seq_LEN(e->v.Call.keywords))
4096 return -1;
4097
4098 /* Check that there are no *varargs types of arguments. */
4099 argsl = asdl_seq_LEN(args);
4100 for (i = 0; i < argsl; i++) {
4101 expr_ty elt = asdl_seq_GET(args, i);
4102 if (elt->kind == Starred_kind) {
4103 return -1;
4104 }
4105 }
4106
4107 /* Alright, we can optimize the code. */
4108 VISIT(c, expr, meth->v.Attribute.value);
4109 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4110 VISIT_SEQ(c, expr, e->v.Call.args);
4111 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4112 return 1;
4113}
4114
4115static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116compiler_call(struct compiler *c, expr_ty e)
4117{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004118 int ret = maybe_optimize_method_call(c, e);
4119 if (ret >= 0) {
4120 return ret;
4121 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004122 if (!check_caller(c, e->v.Call.func)) {
4123 return 0;
4124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 VISIT(c, expr, e->v.Call.func);
4126 return compiler_call_helper(c, 0,
4127 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004128 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004129}
4130
Eric V. Smith235a6f02015-09-19 14:51:32 -04004131static int
4132compiler_joined_str(struct compiler *c, expr_ty e)
4133{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004134 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004135 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4136 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004137 return 1;
4138}
4139
Eric V. Smitha78c7952015-11-03 12:45:05 -05004140/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004141static int
4142compiler_formatted_value(struct compiler *c, expr_ty e)
4143{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004144 /* Our oparg encodes 2 pieces of information: the conversion
4145 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004146
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004147 Convert the conversion char to 3 bits:
4148 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004149 !s : 001 0x1 FVC_STR
4150 !r : 010 0x2 FVC_REPR
4151 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004152
Eric V. Smitha78c7952015-11-03 12:45:05 -05004153 next bit is whether or not we have a format spec:
4154 yes : 100 0x4
4155 no : 000 0x0
4156 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004158 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004160
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004161 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162 VISIT(c, expr, e->v.FormattedValue.value);
4163
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004164 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 case 's': oparg = FVC_STR; break;
4166 case 'r': oparg = FVC_REPR; break;
4167 case 'a': oparg = FVC_ASCII; break;
4168 case -1: oparg = FVC_NONE; break;
4169 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004170 PyErr_Format(PyExc_SystemError,
4171 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004172 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 }
4179
Eric V. Smitha78c7952015-11-03 12:45:05 -05004180 /* And push our opcode and oparg */
4181 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004182
Eric V. Smith235a6f02015-09-19 14:51:32 -04004183 return 1;
4184}
4185
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004186static int
4187compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4188{
4189 Py_ssize_t i, n = end - begin;
4190 keyword_ty kw;
4191 PyObject *keys, *key;
4192 assert(n > 0);
4193 if (n > 1) {
4194 for (i = begin; i < end; i++) {
4195 kw = asdl_seq_GET(keywords, i);
4196 VISIT(c, expr, kw->value);
4197 }
4198 keys = PyTuple_New(n);
4199 if (keys == NULL) {
4200 return 0;
4201 }
4202 for (i = begin; i < end; i++) {
4203 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4204 Py_INCREF(key);
4205 PyTuple_SET_ITEM(keys, i - begin, key);
4206 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004207 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004208 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4209 }
4210 else {
4211 /* a for loop only executes once */
4212 for (i = begin; i < end; i++) {
4213 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004214 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004215 VISIT(c, expr, kw->value);
4216 }
4217 ADDOP_I(c, BUILD_MAP, n);
4218 }
4219 return 1;
4220}
4221
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004222/* shared code between compiler_call and compiler_class */
4223static int
4224compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004225 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004226 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004227 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004228{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004230
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004231 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004232 nkwelts = asdl_seq_LEN(keywords);
4233
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004234 for (i = 0; i < nelts; i++) {
4235 expr_ty elt = asdl_seq_GET(args, i);
4236 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004237 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004238 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004239 }
4240 for (i = 0; i < nkwelts; i++) {
4241 keyword_ty kw = asdl_seq_GET(keywords, i);
4242 if (kw->arg == NULL) {
4243 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246
Mark Shannon13bc1392020-01-23 09:25:17 +00004247 /* No * or ** args, so can use faster calling sequence */
4248 for (i = 0; i < nelts; i++) {
4249 expr_ty elt = asdl_seq_GET(args, i);
4250 assert(elt->kind != Starred_kind);
4251 VISIT(c, expr, elt);
4252 }
4253 if (nkwelts) {
4254 PyObject *names;
4255 VISIT_SEQ(c, keyword, keywords);
4256 names = PyTuple_New(nkwelts);
4257 if (names == NULL) {
4258 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004259 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004260 for (i = 0; i < nkwelts; i++) {
4261 keyword_ty kw = asdl_seq_GET(keywords, i);
4262 Py_INCREF(kw->arg);
4263 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004265 ADDOP_LOAD_CONST_NEW(c, names);
4266 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4267 return 1;
4268 }
4269 else {
4270 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4271 return 1;
4272 }
4273
4274ex_call:
4275
4276 /* Do positional arguments. */
4277 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4278 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4279 }
4280 else if (starunpack_helper(c, args, n, BUILD_LIST,
4281 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4282 return 0;
4283 }
4284 /* Then keyword arguments */
4285 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004286 /* Has a new dict been pushed */
4287 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004288
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004289 nseen = 0; /* the number of keyword arguments on the stack following */
4290 for (i = 0; i < nkwelts; i++) {
4291 keyword_ty kw = asdl_seq_GET(keywords, i);
4292 if (kw->arg == NULL) {
4293 /* A keyword argument unpacking. */
4294 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004295 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004296 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004297 }
4298 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004299 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004300 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004301 if (!have_dict) {
4302 ADDOP_I(c, BUILD_MAP, 0);
4303 have_dict = 1;
4304 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004305 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004307 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004308 else {
4309 nseen++;
4310 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004311 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004312 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004313 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004314 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004315 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004316 }
4317 if (have_dict) {
4318 ADDOP_I(c, DICT_MERGE, 1);
4319 }
4320 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004321 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004322 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004324 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326}
4327
Nick Coghlan650f0d02007-04-15 12:05:43 +00004328
4329/* List and set comprehensions and generator expressions work by creating a
4330 nested function to perform the actual iteration. This means that the
4331 iteration variables don't leak into the current scope.
4332 The defined function is called immediately following its definition, with the
4333 result of that call being the result of the expression.
4334 The LC/SC version returns the populated container, while the GE version is
4335 flagged in symtable.c as a generator, so it returns the generator object
4336 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004337
4338 Possible cleanups:
4339 - iterate over the generator sequence instead of using recursion
4340*/
4341
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004342
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344compiler_comprehension_generator(struct compiler *c,
4345 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004346 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004348{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004349 comprehension_ty gen;
4350 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4351 if (gen->is_async) {
4352 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004353 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004354 } else {
4355 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004356 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004357 }
4358}
4359
4360static int
4361compiler_sync_comprehension_generator(struct compiler *c,
4362 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004363 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004364 expr_ty elt, expr_ty val, int type)
4365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 /* generate code for the iterator, then each of the ifs,
4367 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 comprehension_ty gen;
4370 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004371 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 start = compiler_new_block(c);
4374 skip = compiler_new_block(c);
4375 if_cleanup = compiler_new_block(c);
4376 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4379 anchor == NULL)
4380 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 if (gen_index == 0) {
4385 /* Receive outermost iter as an implicit argument */
4386 c->u->u_argcount = 1;
4387 ADDOP_I(c, LOAD_FAST, 0);
4388 }
4389 else {
4390 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004391 /* Fast path for the temporary variable assignment idiom:
4392 for y in [f(x)]
4393 */
4394 asdl_seq *elts;
4395 switch (gen->iter->kind) {
4396 case List_kind:
4397 elts = gen->iter->v.List.elts;
4398 break;
4399 case Tuple_kind:
4400 elts = gen->iter->v.Tuple.elts;
4401 break;
4402 default:
4403 elts = NULL;
4404 }
4405 if (asdl_seq_LEN(elts) == 1) {
4406 expr_ty elt = asdl_seq_GET(elts, 0);
4407 if (elt->kind != Starred_kind) {
4408 VISIT(c, expr, elt);
4409 start = NULL;
4410 }
4411 }
4412 if (start) {
4413 VISIT(c, expr, gen->iter);
4414 ADDOP(c, GET_ITER);
4415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004417 if (start) {
4418 depth++;
4419 compiler_use_next_block(c, start);
4420 ADDOP_JREL(c, FOR_ITER, anchor);
4421 NEXT_BLOCK(c);
4422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 /* XXX this needs to be cleaned up...a lot! */
4426 n = asdl_seq_LEN(gen->ifs);
4427 for (i = 0; i < n; i++) {
4428 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004429 if (!compiler_jump_if(c, e, if_cleanup, 0))
4430 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 NEXT_BLOCK(c);
4432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 if (++gen_index < asdl_seq_LEN(generators))
4435 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004436 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 elt, val, type))
4438 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 /* only append after the last for generator */
4441 if (gen_index >= asdl_seq_LEN(generators)) {
4442 /* comprehension specific code */
4443 switch (type) {
4444 case COMP_GENEXP:
4445 VISIT(c, expr, elt);
4446 ADDOP(c, YIELD_VALUE);
4447 ADDOP(c, POP_TOP);
4448 break;
4449 case COMP_LISTCOMP:
4450 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004451 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 break;
4453 case COMP_SETCOMP:
4454 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004455 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 break;
4457 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004458 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004461 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004462 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 break;
4464 default:
4465 return 0;
4466 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 compiler_use_next_block(c, skip);
4469 }
4470 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004471 if (start) {
4472 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4473 compiler_use_next_block(c, anchor);
4474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475
4476 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004477}
4478
4479static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480compiler_async_comprehension_generator(struct compiler *c,
4481 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004482 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004483 expr_ty elt, expr_ty val, int type)
4484{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004485 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004486 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004487 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004488 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004492 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004493 return 0;
4494 }
4495
4496 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4497
4498 if (gen_index == 0) {
4499 /* Receive outermost iter as an implicit argument */
4500 c->u->u_argcount = 1;
4501 ADDOP_I(c, LOAD_FAST, 0);
4502 }
4503 else {
4504 /* Sub-iter - calculate on the fly */
4505 VISIT(c, expr, gen->iter);
4506 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507 }
4508
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004509 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004511 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004513 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004515 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004516 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004517
4518 n = asdl_seq_LEN(gen->ifs);
4519 for (i = 0; i < n; i++) {
4520 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004521 if (!compiler_jump_if(c, e, if_cleanup, 0))
4522 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523 NEXT_BLOCK(c);
4524 }
4525
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004526 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 if (++gen_index < asdl_seq_LEN(generators))
4528 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004529 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 elt, val, type))
4531 return 0;
4532
4533 /* only append after the last for generator */
4534 if (gen_index >= asdl_seq_LEN(generators)) {
4535 /* comprehension specific code */
4536 switch (type) {
4537 case COMP_GENEXP:
4538 VISIT(c, expr, elt);
4539 ADDOP(c, YIELD_VALUE);
4540 ADDOP(c, POP_TOP);
4541 break;
4542 case COMP_LISTCOMP:
4543 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004544 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004545 break;
4546 case COMP_SETCOMP:
4547 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004548 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 break;
4550 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004551 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004552 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004554 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004555 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556 break;
4557 default:
4558 return 0;
4559 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004560 }
4561 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004562 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4563
4564 compiler_use_next_block(c, except);
4565 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004566
4567 return 1;
4568}
4569
4570static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004571compiler_comprehension(struct compiler *c, expr_ty e, int type,
4572 identifier name, asdl_seq *generators, expr_ty elt,
4573 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004576 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004577 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578 int is_async_function = c->u->u_ste->ste_coroutine;
4579 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004580
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004581 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004582
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004583 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4584 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004585 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004587 }
4588
4589 is_async_generator = c->u->u_ste->ste_coroutine;
4590
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004591 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004592 compiler_error(c, "asynchronous comprehension outside of "
4593 "an asynchronous function");
4594 goto error_in_scope;
4595 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 if (type != COMP_GENEXP) {
4598 int op;
4599 switch (type) {
4600 case COMP_LISTCOMP:
4601 op = BUILD_LIST;
4602 break;
4603 case COMP_SETCOMP:
4604 op = BUILD_SET;
4605 break;
4606 case COMP_DICTCOMP:
4607 op = BUILD_MAP;
4608 break;
4609 default:
4610 PyErr_Format(PyExc_SystemError,
4611 "unknown comprehension type %d", type);
4612 goto error_in_scope;
4613 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 ADDOP_I(c, op, 0);
4616 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004617
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004618 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 val, type))
4620 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 if (type != COMP_GENEXP) {
4623 ADDOP(c, RETURN_VALUE);
4624 }
4625
4626 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004627 qualname = c->u->u_qualname;
4628 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004630 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 goto error;
4632
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004633 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004635 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 Py_DECREF(co);
4637
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004638 VISIT(c, expr, outermost->iter);
4639
4640 if (outermost->is_async) {
4641 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004642 } else {
4643 ADDOP(c, GET_ITER);
4644 }
4645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004647
4648 if (is_async_generator && type != COMP_GENEXP) {
4649 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004650 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004651 ADDOP(c, YIELD_FROM);
4652 }
4653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004655error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004657error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004658 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 Py_XDECREF(co);
4660 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004661}
4662
4663static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004664compiler_genexp(struct compiler *c, expr_ty e)
4665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 static identifier name;
4667 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004668 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 if (!name)
4670 return 0;
4671 }
4672 assert(e->kind == GeneratorExp_kind);
4673 return compiler_comprehension(c, e, COMP_GENEXP, name,
4674 e->v.GeneratorExp.generators,
4675 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004676}
4677
4678static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004679compiler_listcomp(struct compiler *c, expr_ty e)
4680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 static identifier name;
4682 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004683 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 if (!name)
4685 return 0;
4686 }
4687 assert(e->kind == ListComp_kind);
4688 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4689 e->v.ListComp.generators,
4690 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004691}
4692
4693static int
4694compiler_setcomp(struct compiler *c, expr_ty e)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 static identifier name;
4697 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004698 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (!name)
4700 return 0;
4701 }
4702 assert(e->kind == SetComp_kind);
4703 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4704 e->v.SetComp.generators,
4705 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004706}
4707
4708
4709static int
4710compiler_dictcomp(struct compiler *c, expr_ty e)
4711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 static identifier name;
4713 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004714 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004715 if (!name)
4716 return 0;
4717 }
4718 assert(e->kind == DictComp_kind);
4719 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4720 e->v.DictComp.generators,
4721 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004722}
4723
4724
4725static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004726compiler_visit_keyword(struct compiler *c, keyword_ty k)
4727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 VISIT(c, expr, k->value);
4729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004730}
4731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004733 whether they are true or false.
4734
4735 Return values: 1 for true, 0 for false, -1 for non-constant.
4736 */
4737
4738static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004739expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004740{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004741 if (e->kind == Constant_kind) {
4742 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004743 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004744 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745}
4746
Mark Shannonfee55262019-11-21 09:11:43 +00004747static int
4748compiler_with_except_finish(struct compiler *c) {
4749 basicblock *exit;
4750 exit = compiler_new_block(c);
4751 if (exit == NULL)
4752 return 0;
4753 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4754 ADDOP(c, RERAISE);
4755 compiler_use_next_block(c, exit);
4756 ADDOP(c, POP_TOP);
4757 ADDOP(c, POP_TOP);
4758 ADDOP(c, POP_TOP);
4759 ADDOP(c, POP_EXCEPT);
4760 ADDOP(c, POP_TOP);
4761 return 1;
4762}
Yury Selivanov75445082015-05-11 22:57:16 -04004763
4764/*
4765 Implements the async with statement.
4766
4767 The semantics outlined in that PEP are as follows:
4768
4769 async with EXPR as VAR:
4770 BLOCK
4771
4772 It is implemented roughly as:
4773
4774 context = EXPR
4775 exit = context.__aexit__ # not calling it
4776 value = await context.__aenter__()
4777 try:
4778 VAR = value # if VAR present in the syntax
4779 BLOCK
4780 finally:
4781 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004782 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004783 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004784 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004785 if not (await exit(*exc)):
4786 raise
4787 */
4788static int
4789compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4790{
Mark Shannonfee55262019-11-21 09:11:43 +00004791 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004792 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4793
4794 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004795 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4796 c->u->u_ste->ste_coroutine = 1;
4797 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004798 return compiler_error(c, "'async with' outside async function");
4799 }
Yury Selivanov75445082015-05-11 22:57:16 -04004800
4801 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004802 final = compiler_new_block(c);
4803 exit = compiler_new_block(c);
4804 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004805 return 0;
4806
4807 /* Evaluate EXPR */
4808 VISIT(c, expr, item->context_expr);
4809
4810 ADDOP(c, BEFORE_ASYNC_WITH);
4811 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004812 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004813 ADDOP(c, YIELD_FROM);
4814
Mark Shannonfee55262019-11-21 09:11:43 +00004815 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004816
4817 /* SETUP_ASYNC_WITH pushes a finally block. */
4818 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004819 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004820 return 0;
4821 }
4822
4823 if (item->optional_vars) {
4824 VISIT(c, expr, item->optional_vars);
4825 }
4826 else {
4827 /* Discard result from context.__aenter__() */
4828 ADDOP(c, POP_TOP);
4829 }
4830
4831 pos++;
4832 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4833 /* BLOCK code */
4834 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4835 else if (!compiler_async_with(c, s, pos))
4836 return 0;
4837
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004838 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004839 ADDOP(c, POP_BLOCK);
4840 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004841
Mark Shannonfee55262019-11-21 09:11:43 +00004842 /* For successful outcome:
4843 * call __exit__(None, None, None)
4844 */
4845 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004846 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004847 ADDOP(c, GET_AWAITABLE);
4848 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4849 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004850
Mark Shannonfee55262019-11-21 09:11:43 +00004851 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004852
Mark Shannonfee55262019-11-21 09:11:43 +00004853 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4854
4855 /* For exceptional outcome: */
4856 compiler_use_next_block(c, final);
4857
4858 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004859 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004860 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004861 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004862 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004863
Mark Shannonfee55262019-11-21 09:11:43 +00004864compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004865 return 1;
4866}
4867
4868
Guido van Rossumc2e20742006-02-27 22:32:47 +00004869/*
4870 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004871 with EXPR as VAR:
4872 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004873 is implemented as:
4874 <code for EXPR>
4875 SETUP_WITH E
4876 <code to store to VAR> or POP_TOP
4877 <code for BLOCK>
4878 LOAD_CONST (None, None, None)
4879 CALL_FUNCTION_EX 0
4880 JUMP_FORWARD EXIT
4881 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4882 POP_JUMP_IF_TRUE T:
4883 RERAISE
4884 T: POP_TOP * 3 (remove exception from stack)
4885 POP_EXCEPT
4886 POP_TOP
4887 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004888 */
Mark Shannonfee55262019-11-21 09:11:43 +00004889
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004891compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892{
Mark Shannonfee55262019-11-21 09:11:43 +00004893 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004894 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004895
4896 assert(s->kind == With_kind);
4897
Guido van Rossumc2e20742006-02-27 22:32:47 +00004898 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004899 final = compiler_new_block(c);
4900 exit = compiler_new_block(c);
4901 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004902 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004903
Thomas Wouters477c8d52006-05-27 19:21:47 +00004904 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004905 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004906 /* Will push bound __exit__ */
4907 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004909 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004911 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004912 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913 }
4914
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004915 if (item->optional_vars) {
4916 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004917 }
4918 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004920 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004921 }
4922
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004923 pos++;
4924 if (pos == asdl_seq_LEN(s->v.With.items))
4925 /* BLOCK code */
4926 VISIT_SEQ(c, stmt, s->v.With.body)
4927 else if (!compiler_with(c, s, pos))
4928 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004929
Guido van Rossumc2e20742006-02-27 22:32:47 +00004930 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004931 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004932
Mark Shannonfee55262019-11-21 09:11:43 +00004933 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004934
Mark Shannonfee55262019-11-21 09:11:43 +00004935 /* For successful outcome:
4936 * call __exit__(None, None, None)
4937 */
4938 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004939 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004940 ADDOP(c, POP_TOP);
4941 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942
Mark Shannonfee55262019-11-21 09:11:43 +00004943 /* For exceptional outcome: */
4944 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004945
Mark Shannonfee55262019-11-21 09:11:43 +00004946 ADDOP(c, WITH_EXCEPT_START);
4947 compiler_with_except_finish(c);
4948
4949 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004950 return 1;
4951}
4952
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004954compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004957 case NamedExpr_kind:
4958 VISIT(c, expr, e->v.NamedExpr.value);
4959 ADDOP(c, DUP_TOP);
4960 VISIT(c, expr, e->v.NamedExpr.target);
4961 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 case BoolOp_kind:
4963 return compiler_boolop(c, e);
4964 case BinOp_kind:
4965 VISIT(c, expr, e->v.BinOp.left);
4966 VISIT(c, expr, e->v.BinOp.right);
4967 ADDOP(c, binop(c, e->v.BinOp.op));
4968 break;
4969 case UnaryOp_kind:
4970 VISIT(c, expr, e->v.UnaryOp.operand);
4971 ADDOP(c, unaryop(e->v.UnaryOp.op));
4972 break;
4973 case Lambda_kind:
4974 return compiler_lambda(c, e);
4975 case IfExp_kind:
4976 return compiler_ifexp(c, e);
4977 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004978 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004980 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 case GeneratorExp_kind:
4982 return compiler_genexp(c, e);
4983 case ListComp_kind:
4984 return compiler_listcomp(c, e);
4985 case SetComp_kind:
4986 return compiler_setcomp(c, e);
4987 case DictComp_kind:
4988 return compiler_dictcomp(c, e);
4989 case Yield_kind:
4990 if (c->u->u_ste->ste_type != FunctionBlock)
4991 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004992 if (e->v.Yield.value) {
4993 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 }
4995 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004996 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004998 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005000 case YieldFrom_kind:
5001 if (c->u->u_ste->ste_type != FunctionBlock)
5002 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005003
5004 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5005 return compiler_error(c, "'yield from' inside async function");
5006
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005007 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005008 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005009 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005010 ADDOP(c, YIELD_FROM);
5011 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005012 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005013 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
5014 if (c->u->u_ste->ste_type != FunctionBlock){
5015 return compiler_error(c, "'await' outside function");
5016 }
Yury Selivanov75445082015-05-11 22:57:16 -04005017
Victor Stinner331a6a52019-05-27 16:39:22 +02005018 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005019 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5020 return compiler_error(c, "'await' outside async function");
5021 }
5022 }
Yury Selivanov75445082015-05-11 22:57:16 -04005023
5024 VISIT(c, expr, e->v.Await.value);
5025 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005026 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005027 ADDOP(c, YIELD_FROM);
5028 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 case Compare_kind:
5030 return compiler_compare(c, e);
5031 case Call_kind:
5032 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005033 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005034 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005035 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005036 case JoinedStr_kind:
5037 return compiler_joined_str(c, e);
5038 case FormattedValue_kind:
5039 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 /* The following exprs can be assignment targets. */
5041 case Attribute_kind:
5042 if (e->v.Attribute.ctx != AugStore)
5043 VISIT(c, expr, e->v.Attribute.value);
5044 switch (e->v.Attribute.ctx) {
5045 case AugLoad:
5046 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005047 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 case Load:
5049 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5050 break;
5051 case AugStore:
5052 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005053 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 case Store:
5055 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5056 break;
5057 case Del:
5058 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5059 break;
5060 case Param:
5061 default:
5062 PyErr_SetString(PyExc_SystemError,
5063 "param invalid in attribute expression");
5064 return 0;
5065 }
5066 break;
5067 case Subscript_kind:
5068 switch (e->v.Subscript.ctx) {
5069 case AugLoad:
5070 VISIT(c, expr, e->v.Subscript.value);
5071 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
5072 break;
5073 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005074 if (!check_subscripter(c, e->v.Subscript.value)) {
5075 return 0;
5076 }
5077 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5078 return 0;
5079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 VISIT(c, expr, e->v.Subscript.value);
5081 VISIT_SLICE(c, e->v.Subscript.slice, Load);
5082 break;
5083 case AugStore:
5084 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
5085 break;
5086 case Store:
5087 VISIT(c, expr, e->v.Subscript.value);
5088 VISIT_SLICE(c, e->v.Subscript.slice, Store);
5089 break;
5090 case Del:
5091 VISIT(c, expr, e->v.Subscript.value);
5092 VISIT_SLICE(c, e->v.Subscript.slice, Del);
5093 break;
5094 case Param:
5095 default:
5096 PyErr_SetString(PyExc_SystemError,
5097 "param invalid in subscript expression");
5098 return 0;
5099 }
5100 break;
5101 case Starred_kind:
5102 switch (e->v.Starred.ctx) {
5103 case Store:
5104 /* In all legitimate cases, the Starred node was already replaced
5105 * by compiler_list/compiler_tuple. XXX: is that okay? */
5106 return compiler_error(c,
5107 "starred assignment target must be in a list or tuple");
5108 default:
5109 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005110 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 case Name_kind:
5113 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5114 /* child nodes of List and Tuple will have expr_context set */
5115 case List_kind:
5116 return compiler_list(c, e);
5117 case Tuple_kind:
5118 return compiler_tuple(c, e);
5119 }
5120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121}
5122
5123static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005124compiler_visit_expr(struct compiler *c, expr_ty e)
5125{
5126 /* If expr e has a different line number than the last expr/stmt,
5127 set a new line number for the next instruction.
5128 */
5129 int old_lineno = c->u->u_lineno;
5130 int old_col_offset = c->u->u_col_offset;
5131 if (e->lineno != c->u->u_lineno) {
5132 c->u->u_lineno = e->lineno;
5133 c->u->u_lineno_set = 0;
5134 }
5135 /* Updating the column offset is always harmless. */
5136 c->u->u_col_offset = e->col_offset;
5137
5138 int res = compiler_visit_expr1(c, e);
5139
5140 if (old_lineno != c->u->u_lineno) {
5141 c->u->u_lineno = old_lineno;
5142 c->u->u_lineno_set = 0;
5143 }
5144 c->u->u_col_offset = old_col_offset;
5145 return res;
5146}
5147
5148static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005149compiler_augassign(struct compiler *c, stmt_ty s)
5150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 expr_ty e = s->v.AugAssign.target;
5152 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 switch (e->kind) {
5157 case Attribute_kind:
5158 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005159 AugLoad, e->lineno, e->col_offset,
5160 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 if (auge == NULL)
5162 return 0;
5163 VISIT(c, expr, auge);
5164 VISIT(c, expr, s->v.AugAssign.value);
5165 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5166 auge->v.Attribute.ctx = AugStore;
5167 VISIT(c, expr, auge);
5168 break;
5169 case Subscript_kind:
5170 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005171 AugLoad, e->lineno, e->col_offset,
5172 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 if (auge == NULL)
5174 return 0;
5175 VISIT(c, expr, auge);
5176 VISIT(c, expr, s->v.AugAssign.value);
5177 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5178 auge->v.Subscript.ctx = AugStore;
5179 VISIT(c, expr, auge);
5180 break;
5181 case Name_kind:
5182 if (!compiler_nameop(c, e->v.Name.id, Load))
5183 return 0;
5184 VISIT(c, expr, s->v.AugAssign.value);
5185 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5186 return compiler_nameop(c, e->v.Name.id, Store);
5187 default:
5188 PyErr_Format(PyExc_SystemError,
5189 "invalid node type (%d) for augmented assignment",
5190 e->kind);
5191 return 0;
5192 }
5193 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005194}
5195
5196static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197check_ann_expr(struct compiler *c, expr_ty e)
5198{
5199 VISIT(c, expr, e);
5200 ADDOP(c, POP_TOP);
5201 return 1;
5202}
5203
5204static int
5205check_annotation(struct compiler *c, stmt_ty s)
5206{
5207 /* Annotations are only evaluated in a module or class. */
5208 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5209 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5210 return check_ann_expr(c, s->v.AnnAssign.annotation);
5211 }
5212 return 1;
5213}
5214
5215static int
5216check_ann_slice(struct compiler *c, slice_ty sl)
5217{
5218 switch(sl->kind) {
5219 case Index_kind:
5220 return check_ann_expr(c, sl->v.Index.value);
5221 case Slice_kind:
5222 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
5223 return 0;
5224 }
5225 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
5226 return 0;
5227 }
5228 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
5229 return 0;
5230 }
5231 break;
5232 default:
5233 PyErr_SetString(PyExc_SystemError,
5234 "unexpected slice kind");
5235 return 0;
5236 }
5237 return 1;
5238}
5239
5240static int
5241check_ann_subscr(struct compiler *c, slice_ty sl)
5242{
5243 /* We check that everything in a subscript is defined at runtime. */
5244 Py_ssize_t i, n;
5245
5246 switch (sl->kind) {
5247 case Index_kind:
5248 case Slice_kind:
5249 if (!check_ann_slice(c, sl)) {
5250 return 0;
5251 }
5252 break;
5253 case ExtSlice_kind:
5254 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5255 for (i = 0; i < n; i++) {
5256 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5257 switch (subsl->kind) {
5258 case Index_kind:
5259 case Slice_kind:
5260 if (!check_ann_slice(c, subsl)) {
5261 return 0;
5262 }
5263 break;
5264 case ExtSlice_kind:
5265 default:
5266 PyErr_SetString(PyExc_SystemError,
5267 "extended slice invalid in nested slice");
5268 return 0;
5269 }
5270 }
5271 break;
5272 default:
5273 PyErr_Format(PyExc_SystemError,
5274 "invalid subscript kind %d", sl->kind);
5275 return 0;
5276 }
5277 return 1;
5278}
5279
5280static int
5281compiler_annassign(struct compiler *c, stmt_ty s)
5282{
5283 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005284 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005285
5286 assert(s->kind == AnnAssign_kind);
5287
5288 /* We perform the actual assignment first. */
5289 if (s->v.AnnAssign.value) {
5290 VISIT(c, expr, s->v.AnnAssign.value);
5291 VISIT(c, expr, targ);
5292 }
5293 switch (targ->kind) {
5294 case Name_kind:
5295 /* If we have a simple name in a module or class, store annotation. */
5296 if (s->v.AnnAssign.simple &&
5297 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5298 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005299 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5300 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5301 }
5302 else {
5303 VISIT(c, expr, s->v.AnnAssign.annotation);
5304 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005305 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005306 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005307 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005308 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005309 }
5310 break;
5311 case Attribute_kind:
5312 if (!s->v.AnnAssign.value &&
5313 !check_ann_expr(c, targ->v.Attribute.value)) {
5314 return 0;
5315 }
5316 break;
5317 case Subscript_kind:
5318 if (!s->v.AnnAssign.value &&
5319 (!check_ann_expr(c, targ->v.Subscript.value) ||
5320 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5321 return 0;
5322 }
5323 break;
5324 default:
5325 PyErr_Format(PyExc_SystemError,
5326 "invalid node type (%d) for annotated assignment",
5327 targ->kind);
5328 return 0;
5329 }
5330 /* Annotation is evaluated last. */
5331 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5332 return 0;
5333 }
5334 return 1;
5335}
5336
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005337/* Raises a SyntaxError and returns 0.
5338 If something goes wrong, a different exception may be raised.
5339*/
5340
5341static int
5342compiler_error(struct compiler *c, const char *errstr)
5343{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005344 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346
Victor Stinner14e461d2013-08-26 22:28:21 +02005347 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 if (!loc) {
5349 Py_INCREF(Py_None);
5350 loc = Py_None;
5351 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005352 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005353 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 if (!u)
5355 goto exit;
5356 v = Py_BuildValue("(zO)", errstr, u);
5357 if (!v)
5358 goto exit;
5359 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005360 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 Py_DECREF(loc);
5362 Py_XDECREF(u);
5363 Py_XDECREF(v);
5364 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005365}
5366
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005367/* Emits a SyntaxWarning and returns 1 on success.
5368 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5369 and returns 0.
5370*/
5371static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005372compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005373{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005374 va_list vargs;
5375#ifdef HAVE_STDARG_PROTOTYPES
5376 va_start(vargs, format);
5377#else
5378 va_start(vargs);
5379#endif
5380 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5381 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005382 if (msg == NULL) {
5383 return 0;
5384 }
5385 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5386 c->u->u_lineno, NULL, NULL) < 0)
5387 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005388 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005389 /* Replace the SyntaxWarning exception with a SyntaxError
5390 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005391 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005392 assert(PyUnicode_AsUTF8(msg) != NULL);
5393 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005394 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005395 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005396 return 0;
5397 }
5398 Py_DECREF(msg);
5399 return 1;
5400}
5401
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403compiler_handle_subscr(struct compiler *c, const char *kind,
5404 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 /* XXX this code is duplicated */
5409 switch (ctx) {
5410 case AugLoad: /* fall through to Load */
5411 case Load: op = BINARY_SUBSCR; break;
5412 case AugStore:/* fall through to Store */
5413 case Store: op = STORE_SUBSCR; break;
5414 case Del: op = DELETE_SUBSCR; break;
5415 case Param:
5416 PyErr_Format(PyExc_SystemError,
5417 "invalid %s kind %d in subscript\n",
5418 kind, ctx);
5419 return 0;
5420 }
5421 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005422 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 }
5424 else if (ctx == AugStore) {
5425 ADDOP(c, ROT_THREE);
5426 }
5427 ADDOP(c, op);
5428 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005429}
5430
5431static int
5432compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 int n = 2;
5435 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 /* only handles the cases where BUILD_SLICE is emitted */
5438 if (s->v.Slice.lower) {
5439 VISIT(c, expr, s->v.Slice.lower);
5440 }
5441 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005442 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 if (s->v.Slice.upper) {
5446 VISIT(c, expr, s->v.Slice.upper);
5447 }
5448 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005449 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 }
5451
5452 if (s->v.Slice.step) {
5453 n++;
5454 VISIT(c, expr, s->v.Slice.step);
5455 }
5456 ADDOP_I(c, BUILD_SLICE, n);
5457 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458}
5459
5460static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5462 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 switch (s->kind) {
5465 case Slice_kind:
5466 return compiler_slice(c, s, ctx);
5467 case Index_kind:
5468 VISIT(c, expr, s->v.Index.value);
5469 break;
5470 case ExtSlice_kind:
5471 default:
5472 PyErr_SetString(PyExc_SystemError,
5473 "extended slice invalid in nested slice");
5474 return 0;
5475 }
5476 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005477}
5478
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479static int
5480compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5481{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005482 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 switch (s->kind) {
5484 case Index_kind:
5485 kindname = "index";
5486 if (ctx != AugStore) {
5487 VISIT(c, expr, s->v.Index.value);
5488 }
5489 break;
5490 case Slice_kind:
5491 kindname = "slice";
5492 if (ctx != AugStore) {
5493 if (!compiler_slice(c, s, ctx))
5494 return 0;
5495 }
5496 break;
5497 case ExtSlice_kind:
5498 kindname = "extended slice";
5499 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005500 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 for (i = 0; i < n; i++) {
5502 slice_ty sub = (slice_ty)asdl_seq_GET(
5503 s->v.ExtSlice.dims, i);
5504 if (!compiler_visit_nested_slice(c, sub, ctx))
5505 return 0;
5506 }
5507 ADDOP_I(c, BUILD_TUPLE, n);
5508 }
5509 break;
5510 default:
5511 PyErr_Format(PyExc_SystemError,
5512 "invalid subscript kind %d", s->kind);
5513 return 0;
5514 }
5515 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005516}
5517
Thomas Wouters89f507f2006-12-13 04:49:30 +00005518/* End of the compiler section, beginning of the assembler section */
5519
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005520/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005521 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522
5523 XXX must handle implicit jumps from one block to next
5524*/
5525
Thomas Wouters89f507f2006-12-13 04:49:30 +00005526struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 PyObject *a_bytecode; /* string containing bytecode */
5528 int a_offset; /* offset into bytecode */
5529 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005530 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 PyObject *a_lnotab; /* string containing lnotab */
5532 int a_lnotab_off; /* offset into lnotab */
5533 int a_lineno; /* last lineno of emitted instruction */
5534 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005535};
5536
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005537static void
T. Wouters99b54d62019-09-12 07:05:33 -07005538dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005539{
T. Wouters99b54d62019-09-12 07:05:33 -07005540 int i, j;
5541
5542 /* Get rid of recursion for normal control flow.
5543 Since the number of blocks is limited, unused space in a_postorder
5544 (from a_nblocks to end) can be used as a stack for still not ordered
5545 blocks. */
5546 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005547 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005548 assert(a->a_nblocks < j);
5549 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 }
T. Wouters99b54d62019-09-12 07:05:33 -07005551 while (j < end) {
5552 b = a->a_postorder[j++];
5553 for (i = 0; i < b->b_iused; i++) {
5554 struct instr *instr = &b->b_instr[i];
5555 if (instr->i_jrel || instr->i_jabs)
5556 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005557 }
T. Wouters99b54d62019-09-12 07:05:33 -07005558 assert(a->a_nblocks < j);
5559 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005560 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005561}
5562
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005563Py_LOCAL_INLINE(void)
5564stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005565{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005566 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005567 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005568 assert(b->b_startdepth < 0);
5569 b->b_startdepth = depth;
5570 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005571 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005572}
5573
5574/* Find the flow path that needs the largest stack. We assume that
5575 * cycles in the flow graph have no net effect on the stack depth.
5576 */
5577static int
5578stackdepth(struct compiler *c)
5579{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005580 basicblock *b, *entryblock = NULL;
5581 basicblock **stack, **sp;
5582 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 b->b_startdepth = INT_MIN;
5585 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005586 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 }
5588 if (!entryblock)
5589 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005590 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5591 if (!stack) {
5592 PyErr_NoMemory();
5593 return -1;
5594 }
5595
5596 sp = stack;
5597 stackdepth_push(&sp, entryblock, 0);
5598 while (sp != stack) {
5599 b = *--sp;
5600 int depth = b->b_startdepth;
5601 assert(depth >= 0);
5602 basicblock *next = b->b_next;
5603 for (int i = 0; i < b->b_iused; i++) {
5604 struct instr *instr = &b->b_instr[i];
5605 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5606 if (effect == PY_INVALID_STACK_EFFECT) {
5607 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5608 Py_FatalError("PyCompile_OpcodeStackEffect()");
5609 }
5610 int new_depth = depth + effect;
5611 if (new_depth > maxdepth) {
5612 maxdepth = new_depth;
5613 }
5614 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5615 if (instr->i_jrel || instr->i_jabs) {
5616 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5617 assert(effect != PY_INVALID_STACK_EFFECT);
5618 int target_depth = depth + effect;
5619 if (target_depth > maxdepth) {
5620 maxdepth = target_depth;
5621 }
5622 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005623 stackdepth_push(&sp, instr->i_target, target_depth);
5624 }
5625 depth = new_depth;
5626 if (instr->i_opcode == JUMP_ABSOLUTE ||
5627 instr->i_opcode == JUMP_FORWARD ||
5628 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005629 instr->i_opcode == RAISE_VARARGS ||
5630 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005631 {
5632 /* remaining code is dead */
5633 next = NULL;
5634 break;
5635 }
5636 }
5637 if (next != NULL) {
5638 stackdepth_push(&sp, next, depth);
5639 }
5640 }
5641 PyObject_Free(stack);
5642 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005643}
5644
5645static int
5646assemble_init(struct assembler *a, int nblocks, int firstlineno)
5647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 memset(a, 0, sizeof(struct assembler));
5649 a->a_lineno = firstlineno;
5650 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5651 if (!a->a_bytecode)
5652 return 0;
5653 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5654 if (!a->a_lnotab)
5655 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005656 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005657 PyErr_NoMemory();
5658 return 0;
5659 }
T. Wouters99b54d62019-09-12 07:05:33 -07005660 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005662 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 PyErr_NoMemory();
5664 return 0;
5665 }
5666 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005667}
5668
5669static void
5670assemble_free(struct assembler *a)
5671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 Py_XDECREF(a->a_bytecode);
5673 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005674 if (a->a_postorder)
5675 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676}
5677
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005678static int
5679blocksize(basicblock *b)
5680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 int i;
5682 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005685 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005687}
5688
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005689/* Appends a pair to the end of the line number table, a_lnotab, representing
5690 the instruction's bytecode offset and line number. See
5691 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005692
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005694assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005697 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005699
Serhiy Storchakaab874002016-09-11 13:48:15 +03005700 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 if(d_bytecode == 0 && d_lineno == 0)
5706 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 if (d_bytecode > 255) {
5709 int j, nbytes, ncodes = d_bytecode / 255;
5710 nbytes = a->a_lnotab_off + 2 * ncodes;
5711 len = PyBytes_GET_SIZE(a->a_lnotab);
5712 if (nbytes >= len) {
5713 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5714 len = nbytes;
5715 else if (len <= INT_MAX / 2)
5716 len *= 2;
5717 else {
5718 PyErr_NoMemory();
5719 return 0;
5720 }
5721 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5722 return 0;
5723 }
5724 lnotab = (unsigned char *)
5725 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5726 for (j = 0; j < ncodes; j++) {
5727 *lnotab++ = 255;
5728 *lnotab++ = 0;
5729 }
5730 d_bytecode -= ncodes * 255;
5731 a->a_lnotab_off += ncodes * 2;
5732 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005733 assert(0 <= d_bytecode && d_bytecode <= 255);
5734
5735 if (d_lineno < -128 || 127 < d_lineno) {
5736 int j, nbytes, ncodes, k;
5737 if (d_lineno < 0) {
5738 k = -128;
5739 /* use division on positive numbers */
5740 ncodes = (-d_lineno) / 128;
5741 }
5742 else {
5743 k = 127;
5744 ncodes = d_lineno / 127;
5745 }
5746 d_lineno -= ncodes * k;
5747 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 nbytes = a->a_lnotab_off + 2 * ncodes;
5749 len = PyBytes_GET_SIZE(a->a_lnotab);
5750 if (nbytes >= len) {
5751 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5752 len = nbytes;
5753 else if (len <= INT_MAX / 2)
5754 len *= 2;
5755 else {
5756 PyErr_NoMemory();
5757 return 0;
5758 }
5759 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5760 return 0;
5761 }
5762 lnotab = (unsigned char *)
5763 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5764 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005765 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 d_bytecode = 0;
5767 for (j = 1; j < ncodes; j++) {
5768 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005769 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 a->a_lnotab_off += ncodes * 2;
5772 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005773 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 len = PyBytes_GET_SIZE(a->a_lnotab);
5776 if (a->a_lnotab_off + 2 >= len) {
5777 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5778 return 0;
5779 }
5780 lnotab = (unsigned char *)
5781 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 a->a_lnotab_off += 2;
5784 if (d_bytecode) {
5785 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005786 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005787 }
5788 else { /* First line of a block; def stmt, etc. */
5789 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005790 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 }
5792 a->a_lineno = i->i_lineno;
5793 a->a_lineno_off = a->a_offset;
5794 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005795}
5796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005797/* assemble_emit()
5798 Extend the bytecode with a new instruction.
5799 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005800*/
5801
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005802static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005803assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005804{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005805 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005807 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005808
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005809 arg = i->i_oparg;
5810 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 if (i->i_lineno && !assemble_lnotab(a, i))
5812 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005813 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 if (len > PY_SSIZE_T_MAX / 2)
5815 return 0;
5816 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5817 return 0;
5818 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005819 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005821 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005823}
5824
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005825static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005826assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005829 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 /* Compute the size of each block and fixup jump args.
5833 Replace block pointer with position in bytecode. */
5834 do {
5835 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005836 for (i = a->a_nblocks - 1; i >= 0; i--) {
5837 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 bsize = blocksize(b);
5839 b->b_offset = totsize;
5840 totsize += bsize;
5841 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005842 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5844 bsize = b->b_offset;
5845 for (i = 0; i < b->b_iused; i++) {
5846 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005847 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 /* Relative jumps are computed relative to
5849 the instruction pointer after fetching
5850 the jump instruction.
5851 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005852 bsize += isize;
5853 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005855 if (instr->i_jrel) {
5856 instr->i_oparg -= bsize;
5857 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005858 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005859 if (instrsize(instr->i_oparg) != isize) {
5860 extended_arg_recompile = 1;
5861 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005863 }
5864 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 /* XXX: This is an awful hack that could hurt performance, but
5867 on the bright side it should work until we come up
5868 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 The issue is that in the first loop blocksize() is called
5871 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005872 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 So we loop until we stop seeing new EXTENDED_ARGs.
5876 The only EXTENDED_ARGs that could be popping up are
5877 ones in jump instructions. So this should converge
5878 fairly quickly.
5879 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005880 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005881}
5882
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005883static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005884dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005887 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 tuple = PyTuple_New(size);
5890 if (tuple == NULL)
5891 return NULL;
5892 while (PyDict_Next(dict, &pos, &k, &v)) {
5893 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005894 Py_INCREF(k);
5895 assert((i - offset) < size);
5896 assert((i - offset) >= 0);
5897 PyTuple_SET_ITEM(tuple, i - offset, k);
5898 }
5899 return tuple;
5900}
5901
5902static PyObject *
5903consts_dict_keys_inorder(PyObject *dict)
5904{
5905 PyObject *consts, *k, *v;
5906 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5907
5908 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5909 if (consts == NULL)
5910 return NULL;
5911 while (PyDict_Next(dict, &pos, &k, &v)) {
5912 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005913 /* The keys of the dictionary can be tuples wrapping a contant.
5914 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5915 * the object we want is always second. */
5916 if (PyTuple_CheckExact(k)) {
5917 k = PyTuple_GET_ITEM(k, 1);
5918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005920 assert(i < size);
5921 assert(i >= 0);
5922 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005924 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005925}
5926
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005927static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005928compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005931 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005933 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 if (ste->ste_nested)
5935 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005936 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005937 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005938 if (!ste->ste_generator && ste->ste_coroutine)
5939 flags |= CO_COROUTINE;
5940 if (ste->ste_generator && ste->ste_coroutine)
5941 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 if (ste->ste_varargs)
5943 flags |= CO_VARARGS;
5944 if (ste->ste_varkeywords)
5945 flags |= CO_VARKEYWORDS;
5946 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005948 /* (Only) inherit compilerflags in PyCF_MASK */
5949 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005950
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005951 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5952 ste->ste_coroutine &&
5953 !ste->ste_generator) {
5954 flags |= CO_COROUTINE;
5955 }
5956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005958}
5959
INADA Naokic2e16072018-11-26 21:23:22 +09005960// Merge *tuple* with constant cache.
5961// Unlike merge_consts_recursive(), this function doesn't work recursively.
5962static int
5963merge_const_tuple(struct compiler *c, PyObject **tuple)
5964{
5965 assert(PyTuple_CheckExact(*tuple));
5966
5967 PyObject *key = _PyCode_ConstantKey(*tuple);
5968 if (key == NULL) {
5969 return 0;
5970 }
5971
5972 // t is borrowed reference
5973 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5974 Py_DECREF(key);
5975 if (t == NULL) {
5976 return 0;
5977 }
5978 if (t == key) { // tuple is new constant.
5979 return 1;
5980 }
5981
5982 PyObject *u = PyTuple_GET_ITEM(t, 1);
5983 Py_INCREF(u);
5984 Py_DECREF(*tuple);
5985 *tuple = u;
5986 return 1;
5987}
5988
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005989static PyCodeObject *
5990makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 PyObject *tmp;
5993 PyCodeObject *co = NULL;
5994 PyObject *consts = NULL;
5995 PyObject *names = NULL;
5996 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 PyObject *name = NULL;
5998 PyObject *freevars = NULL;
5999 PyObject *cellvars = NULL;
6000 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006001 Py_ssize_t nlocals;
6002 int nlocals_int;
6003 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006004 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006005
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006006 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 names = dict_keys_inorder(c->u->u_names, 0);
6008 varnames = dict_keys_inorder(c->u->u_varnames, 0);
6009 if (!consts || !names || !varnames)
6010 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006012 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6013 if (!cellvars)
6014 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006015 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006016 if (!freevars)
6017 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006018
INADA Naokic2e16072018-11-26 21:23:22 +09006019 if (!merge_const_tuple(c, &names) ||
6020 !merge_const_tuple(c, &varnames) ||
6021 !merge_const_tuple(c, &cellvars) ||
6022 !merge_const_tuple(c, &freevars))
6023 {
6024 goto error;
6025 }
6026
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006027 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006028 assert(nlocals < INT_MAX);
6029 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006031 flags = compute_code_flags(c);
6032 if (flags < 0)
6033 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006035 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
6036 if (!bytecode)
6037 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006039 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6040 if (!tmp)
6041 goto error;
6042 Py_DECREF(consts);
6043 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09006044 if (!merge_const_tuple(c, &consts)) {
6045 goto error;
6046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006048 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006049 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006050 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006051 maxdepth = stackdepth(c);
6052 if (maxdepth < 0) {
6053 goto error;
6054 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006055 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006056 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006057 maxdepth, flags, bytecode, consts, names,
6058 varnames, freevars, cellvars, c->c_filename,
6059 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006060 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006061 Py_XDECREF(consts);
6062 Py_XDECREF(names);
6063 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006064 Py_XDECREF(name);
6065 Py_XDECREF(freevars);
6066 Py_XDECREF(cellvars);
6067 Py_XDECREF(bytecode);
6068 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006069}
6070
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006071
6072/* For debugging purposes only */
6073#if 0
6074static void
6075dump_instr(const struct instr *i)
6076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006077 const char *jrel = i->i_jrel ? "jrel " : "";
6078 const char *jabs = i->i_jabs ? "jabs " : "";
6079 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006081 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006082 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006083 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006084 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6086 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006087}
6088
6089static void
6090dump_basicblock(const basicblock *b)
6091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006092 const char *seen = b->b_seen ? "seen " : "";
6093 const char *b_return = b->b_return ? "return " : "";
6094 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
6095 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
6096 if (b->b_instr) {
6097 int i;
6098 for (i = 0; i < b->b_iused; i++) {
6099 fprintf(stderr, " [%02d] ", i);
6100 dump_instr(b->b_instr + i);
6101 }
6102 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006103}
6104#endif
6105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006106static PyCodeObject *
6107assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006109 basicblock *b, *entryblock;
6110 struct assembler a;
6111 int i, j, nblocks;
6112 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006114 /* Make sure every block that falls off the end returns None.
6115 XXX NEXT_BLOCK() isn't quite right, because if the last
6116 block ends with a jump or return b_next shouldn't set.
6117 */
6118 if (!c->u->u_curblock->b_return) {
6119 NEXT_BLOCK(c);
6120 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006121 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006122 ADDOP(c, RETURN_VALUE);
6123 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006125 nblocks = 0;
6126 entryblock = NULL;
6127 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6128 nblocks++;
6129 entryblock = b;
6130 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006132 /* Set firstlineno if it wasn't explicitly set. */
6133 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006134 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006135 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6136 else
6137 c->u->u_firstlineno = 1;
6138 }
6139 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6140 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006141 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006143 /* Can't modify the bytecode after computing jump offsets. */
6144 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006145
T. Wouters99b54d62019-09-12 07:05:33 -07006146 /* Emit code in reverse postorder from dfs. */
6147 for (i = a.a_nblocks - 1; i >= 0; i--) {
6148 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006149 for (j = 0; j < b->b_iused; j++)
6150 if (!assemble_emit(&a, &b->b_instr[j]))
6151 goto error;
6152 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006154 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6155 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006156 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006160 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 assemble_free(&a);
6162 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006163}
Georg Brandl8334fd92010-12-04 10:26:46 +00006164
6165#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006166PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006167PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6168 PyArena *arena)
6169{
6170 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6171}