blob: 55333b39d3ec621d78a5cf7630abc4cd4d7b4e31 [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);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200196static int compiler_subscript(struct compiler *, expr_ty);
197static int compiler_slice(struct compiler *, expr_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
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004048check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004049{
4050 PyObject *v;
4051
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004052 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004053 if (index_type == NULL
4054 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4055 || index_type == &PySlice_Type) {
4056 return 1;
4057 }
4058
4059 switch (e->kind) {
4060 case Constant_kind:
4061 v = e->v.Constant.value;
4062 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4063 return 1;
4064 }
4065 /* fall through */
4066 case Tuple_kind:
4067 case List_kind:
4068 case ListComp_kind:
4069 case JoinedStr_kind:
4070 case FormattedValue_kind:
4071 return compiler_warn(c, "%.200s indices must be integers or slices, "
4072 "not %.200s; "
4073 "perhaps you missed a comma?",
4074 infer_type(e)->tp_name,
4075 index_type->tp_name);
4076 default:
4077 return 1;
4078 }
4079}
4080
Zackery Spytz97f5de02019-03-22 01:30:32 -06004081// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004083maybe_optimize_method_call(struct compiler *c, expr_ty e)
4084{
4085 Py_ssize_t argsl, i;
4086 expr_ty meth = e->v.Call.func;
4087 asdl_seq *args = e->v.Call.args;
4088
4089 /* Check that the call node is an attribute access, and that
4090 the call doesn't have keyword parameters. */
4091 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4092 asdl_seq_LEN(e->v.Call.keywords))
4093 return -1;
4094
4095 /* Check that there are no *varargs types of arguments. */
4096 argsl = asdl_seq_LEN(args);
4097 for (i = 0; i < argsl; i++) {
4098 expr_ty elt = asdl_seq_GET(args, i);
4099 if (elt->kind == Starred_kind) {
4100 return -1;
4101 }
4102 }
4103
4104 /* Alright, we can optimize the code. */
4105 VISIT(c, expr, meth->v.Attribute.value);
4106 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4107 VISIT_SEQ(c, expr, e->v.Call.args);
4108 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4109 return 1;
4110}
4111
4112static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113compiler_call(struct compiler *c, expr_ty e)
4114{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004115 int ret = maybe_optimize_method_call(c, e);
4116 if (ret >= 0) {
4117 return ret;
4118 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004119 if (!check_caller(c, e->v.Call.func)) {
4120 return 0;
4121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 VISIT(c, expr, e->v.Call.func);
4123 return compiler_call_helper(c, 0,
4124 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004125 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004126}
4127
Eric V. Smith235a6f02015-09-19 14:51:32 -04004128static int
4129compiler_joined_str(struct compiler *c, expr_ty e)
4130{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004131 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004132 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4133 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004134 return 1;
4135}
4136
Eric V. Smitha78c7952015-11-03 12:45:05 -05004137/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004138static int
4139compiler_formatted_value(struct compiler *c, expr_ty e)
4140{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004141 /* Our oparg encodes 2 pieces of information: the conversion
4142 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004143
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004144 Convert the conversion char to 3 bits:
4145 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004146 !s : 001 0x1 FVC_STR
4147 !r : 010 0x2 FVC_REPR
4148 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004149
Eric V. Smitha78c7952015-11-03 12:45:05 -05004150 next bit is whether or not we have a format spec:
4151 yes : 100 0x4
4152 no : 000 0x0
4153 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004154
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004155 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004156 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004158 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004159 VISIT(c, expr, e->v.FormattedValue.value);
4160
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004161 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004162 case 's': oparg = FVC_STR; break;
4163 case 'r': oparg = FVC_REPR; break;
4164 case 'a': oparg = FVC_ASCII; break;
4165 case -1: oparg = FVC_NONE; break;
4166 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004167 PyErr_Format(PyExc_SystemError,
4168 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004169 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004170 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004171 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004172 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004174 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004175 }
4176
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 /* And push our opcode and oparg */
4178 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004179
Eric V. Smith235a6f02015-09-19 14:51:32 -04004180 return 1;
4181}
4182
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004183static int
4184compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4185{
4186 Py_ssize_t i, n = end - begin;
4187 keyword_ty kw;
4188 PyObject *keys, *key;
4189 assert(n > 0);
4190 if (n > 1) {
4191 for (i = begin; i < end; i++) {
4192 kw = asdl_seq_GET(keywords, i);
4193 VISIT(c, expr, kw->value);
4194 }
4195 keys = PyTuple_New(n);
4196 if (keys == NULL) {
4197 return 0;
4198 }
4199 for (i = begin; i < end; i++) {
4200 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4201 Py_INCREF(key);
4202 PyTuple_SET_ITEM(keys, i - begin, key);
4203 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004204 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004205 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4206 }
4207 else {
4208 /* a for loop only executes once */
4209 for (i = begin; i < end; i++) {
4210 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004211 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004212 VISIT(c, expr, kw->value);
4213 }
4214 ADDOP_I(c, BUILD_MAP, n);
4215 }
4216 return 1;
4217}
4218
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004219/* shared code between compiler_call and compiler_class */
4220static int
4221compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004222 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004223 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004224 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004225{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004226 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004227
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004228 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 nkwelts = asdl_seq_LEN(keywords);
4230
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004231 for (i = 0; i < nelts; i++) {
4232 expr_ty elt = asdl_seq_GET(args, i);
4233 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004234 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004235 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004236 }
4237 for (i = 0; i < nkwelts; i++) {
4238 keyword_ty kw = asdl_seq_GET(keywords, i);
4239 if (kw->arg == NULL) {
4240 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004241 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004243
Mark Shannon13bc1392020-01-23 09:25:17 +00004244 /* No * or ** args, so can use faster calling sequence */
4245 for (i = 0; i < nelts; i++) {
4246 expr_ty elt = asdl_seq_GET(args, i);
4247 assert(elt->kind != Starred_kind);
4248 VISIT(c, expr, elt);
4249 }
4250 if (nkwelts) {
4251 PyObject *names;
4252 VISIT_SEQ(c, keyword, keywords);
4253 names = PyTuple_New(nkwelts);
4254 if (names == NULL) {
4255 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004256 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004257 for (i = 0; i < nkwelts; i++) {
4258 keyword_ty kw = asdl_seq_GET(keywords, i);
4259 Py_INCREF(kw->arg);
4260 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004261 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004262 ADDOP_LOAD_CONST_NEW(c, names);
4263 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4264 return 1;
4265 }
4266 else {
4267 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4268 return 1;
4269 }
4270
4271ex_call:
4272
4273 /* Do positional arguments. */
4274 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4275 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4276 }
4277 else if (starunpack_helper(c, args, n, BUILD_LIST,
4278 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4279 return 0;
4280 }
4281 /* Then keyword arguments */
4282 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004283 /* Has a new dict been pushed */
4284 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004285
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004286 nseen = 0; /* the number of keyword arguments on the stack following */
4287 for (i = 0; i < nkwelts; i++) {
4288 keyword_ty kw = asdl_seq_GET(keywords, i);
4289 if (kw->arg == NULL) {
4290 /* A keyword argument unpacking. */
4291 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004292 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004293 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004294 }
4295 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004296 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004297 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004298 if (!have_dict) {
4299 ADDOP_I(c, BUILD_MAP, 0);
4300 have_dict = 1;
4301 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004302 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004303 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004304 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004305 else {
4306 nseen++;
4307 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004308 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004309 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004310 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004311 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004312 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004313 }
4314 if (have_dict) {
4315 ADDOP_I(c, DICT_MERGE, 1);
4316 }
4317 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004318 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004319 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004321 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4322 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323}
4324
Nick Coghlan650f0d02007-04-15 12:05:43 +00004325
4326/* List and set comprehensions and generator expressions work by creating a
4327 nested function to perform the actual iteration. This means that the
4328 iteration variables don't leak into the current scope.
4329 The defined function is called immediately following its definition, with the
4330 result of that call being the result of the expression.
4331 The LC/SC version returns the populated container, while the GE version is
4332 flagged in symtable.c as a generator, so it returns the generator object
4333 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004334
4335 Possible cleanups:
4336 - iterate over the generator sequence instead of using recursion
4337*/
4338
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341compiler_comprehension_generator(struct compiler *c,
4342 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004343 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004346 comprehension_ty gen;
4347 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4348 if (gen->is_async) {
4349 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004350 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004351 } else {
4352 return compiler_sync_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 }
4355}
4356
4357static int
4358compiler_sync_comprehension_generator(struct compiler *c,
4359 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004360 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004361 expr_ty elt, expr_ty val, int type)
4362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 /* generate code for the iterator, then each of the ifs,
4364 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 comprehension_ty gen;
4367 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004368 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 start = compiler_new_block(c);
4371 skip = compiler_new_block(c);
4372 if_cleanup = compiler_new_block(c);
4373 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4376 anchor == NULL)
4377 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 if (gen_index == 0) {
4382 /* Receive outermost iter as an implicit argument */
4383 c->u->u_argcount = 1;
4384 ADDOP_I(c, LOAD_FAST, 0);
4385 }
4386 else {
4387 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004388 /* Fast path for the temporary variable assignment idiom:
4389 for y in [f(x)]
4390 */
4391 asdl_seq *elts;
4392 switch (gen->iter->kind) {
4393 case List_kind:
4394 elts = gen->iter->v.List.elts;
4395 break;
4396 case Tuple_kind:
4397 elts = gen->iter->v.Tuple.elts;
4398 break;
4399 default:
4400 elts = NULL;
4401 }
4402 if (asdl_seq_LEN(elts) == 1) {
4403 expr_ty elt = asdl_seq_GET(elts, 0);
4404 if (elt->kind != Starred_kind) {
4405 VISIT(c, expr, elt);
4406 start = NULL;
4407 }
4408 }
4409 if (start) {
4410 VISIT(c, expr, gen->iter);
4411 ADDOP(c, GET_ITER);
4412 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004414 if (start) {
4415 depth++;
4416 compiler_use_next_block(c, start);
4417 ADDOP_JREL(c, FOR_ITER, anchor);
4418 NEXT_BLOCK(c);
4419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 /* XXX this needs to be cleaned up...a lot! */
4423 n = asdl_seq_LEN(gen->ifs);
4424 for (i = 0; i < n; i++) {
4425 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004426 if (!compiler_jump_if(c, e, if_cleanup, 0))
4427 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 NEXT_BLOCK(c);
4429 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 if (++gen_index < asdl_seq_LEN(generators))
4432 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004433 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 elt, val, type))
4435 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 /* only append after the last for generator */
4438 if (gen_index >= asdl_seq_LEN(generators)) {
4439 /* comprehension specific code */
4440 switch (type) {
4441 case COMP_GENEXP:
4442 VISIT(c, expr, elt);
4443 ADDOP(c, YIELD_VALUE);
4444 ADDOP(c, POP_TOP);
4445 break;
4446 case COMP_LISTCOMP:
4447 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004448 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 break;
4450 case COMP_SETCOMP:
4451 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004452 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 break;
4454 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004455 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004458 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004459 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 break;
4461 default:
4462 return 0;
4463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 compiler_use_next_block(c, skip);
4466 }
4467 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004468 if (start) {
4469 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4470 compiler_use_next_block(c, anchor);
4471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472
4473 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004474}
4475
4476static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004477compiler_async_comprehension_generator(struct compiler *c,
4478 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004479 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480 expr_ty elt, expr_ty val, int type)
4481{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004482 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004483 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004485 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004487 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004489 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 return 0;
4491 }
4492
4493 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4494
4495 if (gen_index == 0) {
4496 /* Receive outermost iter as an implicit argument */
4497 c->u->u_argcount = 1;
4498 ADDOP_I(c, LOAD_FAST, 0);
4499 }
4500 else {
4501 /* Sub-iter - calculate on the fly */
4502 VISIT(c, expr, gen->iter);
4503 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004504 }
4505
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004506 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004508 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004510 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004511 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004513 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514
4515 n = asdl_seq_LEN(gen->ifs);
4516 for (i = 0; i < n; i++) {
4517 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004518 if (!compiler_jump_if(c, e, if_cleanup, 0))
4519 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 NEXT_BLOCK(c);
4521 }
4522
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004523 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 if (++gen_index < asdl_seq_LEN(generators))
4525 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004526 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 elt, val, type))
4528 return 0;
4529
4530 /* only append after the last for generator */
4531 if (gen_index >= asdl_seq_LEN(generators)) {
4532 /* comprehension specific code */
4533 switch (type) {
4534 case COMP_GENEXP:
4535 VISIT(c, expr, elt);
4536 ADDOP(c, YIELD_VALUE);
4537 ADDOP(c, POP_TOP);
4538 break;
4539 case COMP_LISTCOMP:
4540 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004541 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004542 break;
4543 case COMP_SETCOMP:
4544 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004545 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 break;
4547 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004548 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004551 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004552 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 break;
4554 default:
4555 return 0;
4556 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 }
4558 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004559 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4560
4561 compiler_use_next_block(c, except);
4562 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004563
4564 return 1;
4565}
4566
4567static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004568compiler_comprehension(struct compiler *c, expr_ty e, int type,
4569 identifier name, asdl_seq *generators, expr_ty elt,
4570 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004573 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004574 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004575 int is_async_function = c->u->u_ste->ste_coroutine;
4576 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004577
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004579
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004580 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4581 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004582 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004584 }
4585
4586 is_async_generator = c->u->u_ste->ste_coroutine;
4587
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004588 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589 compiler_error(c, "asynchronous comprehension outside of "
4590 "an asynchronous function");
4591 goto error_in_scope;
4592 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 if (type != COMP_GENEXP) {
4595 int op;
4596 switch (type) {
4597 case COMP_LISTCOMP:
4598 op = BUILD_LIST;
4599 break;
4600 case COMP_SETCOMP:
4601 op = BUILD_SET;
4602 break;
4603 case COMP_DICTCOMP:
4604 op = BUILD_MAP;
4605 break;
4606 default:
4607 PyErr_Format(PyExc_SystemError,
4608 "unknown comprehension type %d", type);
4609 goto error_in_scope;
4610 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 ADDOP_I(c, op, 0);
4613 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004614
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004615 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 val, type))
4617 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 if (type != COMP_GENEXP) {
4620 ADDOP(c, RETURN_VALUE);
4621 }
4622
4623 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004624 qualname = c->u->u_qualname;
4625 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004627 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 goto error;
4629
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004630 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004632 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 Py_DECREF(co);
4634
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004635 VISIT(c, expr, outermost->iter);
4636
4637 if (outermost->is_async) {
4638 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004639 } else {
4640 ADDOP(c, GET_ITER);
4641 }
4642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004644
4645 if (is_async_generator && type != COMP_GENEXP) {
4646 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004647 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004648 ADDOP(c, YIELD_FROM);
4649 }
4650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004652error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004654error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004655 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 Py_XDECREF(co);
4657 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004658}
4659
4660static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004661compiler_genexp(struct compiler *c, expr_ty e)
4662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 static identifier name;
4664 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004665 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 if (!name)
4667 return 0;
4668 }
4669 assert(e->kind == GeneratorExp_kind);
4670 return compiler_comprehension(c, e, COMP_GENEXP, name,
4671 e->v.GeneratorExp.generators,
4672 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004673}
4674
4675static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004676compiler_listcomp(struct compiler *c, expr_ty e)
4677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 static identifier name;
4679 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004680 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 if (!name)
4682 return 0;
4683 }
4684 assert(e->kind == ListComp_kind);
4685 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4686 e->v.ListComp.generators,
4687 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004688}
4689
4690static int
4691compiler_setcomp(struct compiler *c, expr_ty e)
4692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 static identifier name;
4694 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004695 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (!name)
4697 return 0;
4698 }
4699 assert(e->kind == SetComp_kind);
4700 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4701 e->v.SetComp.generators,
4702 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004703}
4704
4705
4706static int
4707compiler_dictcomp(struct compiler *c, expr_ty e)
4708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 static identifier name;
4710 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004711 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!name)
4713 return 0;
4714 }
4715 assert(e->kind == DictComp_kind);
4716 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4717 e->v.DictComp.generators,
4718 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004719}
4720
4721
4722static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004723compiler_visit_keyword(struct compiler *c, keyword_ty k)
4724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 VISIT(c, expr, k->value);
4726 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004727}
4728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004730 whether they are true or false.
4731
4732 Return values: 1 for true, 0 for false, -1 for non-constant.
4733 */
4734
4735static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004736expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004737{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004738 if (e->kind == Constant_kind) {
4739 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004740 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004741 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004742}
4743
Mark Shannonfee55262019-11-21 09:11:43 +00004744static int
4745compiler_with_except_finish(struct compiler *c) {
4746 basicblock *exit;
4747 exit = compiler_new_block(c);
4748 if (exit == NULL)
4749 return 0;
4750 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4751 ADDOP(c, RERAISE);
4752 compiler_use_next_block(c, exit);
4753 ADDOP(c, POP_TOP);
4754 ADDOP(c, POP_TOP);
4755 ADDOP(c, POP_TOP);
4756 ADDOP(c, POP_EXCEPT);
4757 ADDOP(c, POP_TOP);
4758 return 1;
4759}
Yury Selivanov75445082015-05-11 22:57:16 -04004760
4761/*
4762 Implements the async with statement.
4763
4764 The semantics outlined in that PEP are as follows:
4765
4766 async with EXPR as VAR:
4767 BLOCK
4768
4769 It is implemented roughly as:
4770
4771 context = EXPR
4772 exit = context.__aexit__ # not calling it
4773 value = await context.__aenter__()
4774 try:
4775 VAR = value # if VAR present in the syntax
4776 BLOCK
4777 finally:
4778 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004779 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004780 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004781 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004782 if not (await exit(*exc)):
4783 raise
4784 */
4785static int
4786compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4787{
Mark Shannonfee55262019-11-21 09:11:43 +00004788 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004789 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4790
4791 assert(s->kind == AsyncWith_kind);
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004792 if (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT){
4793 c->u->u_ste->ste_coroutine = 1;
4794 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004795 return compiler_error(c, "'async with' outside async function");
4796 }
Yury Selivanov75445082015-05-11 22:57:16 -04004797
4798 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004799 final = compiler_new_block(c);
4800 exit = compiler_new_block(c);
4801 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004802 return 0;
4803
4804 /* Evaluate EXPR */
4805 VISIT(c, expr, item->context_expr);
4806
4807 ADDOP(c, BEFORE_ASYNC_WITH);
4808 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004809 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004810 ADDOP(c, YIELD_FROM);
4811
Mark Shannonfee55262019-11-21 09:11:43 +00004812 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004813
4814 /* SETUP_ASYNC_WITH pushes a finally block. */
4815 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004816 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004817 return 0;
4818 }
4819
4820 if (item->optional_vars) {
4821 VISIT(c, expr, item->optional_vars);
4822 }
4823 else {
4824 /* Discard result from context.__aenter__() */
4825 ADDOP(c, POP_TOP);
4826 }
4827
4828 pos++;
4829 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4830 /* BLOCK code */
4831 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4832 else if (!compiler_async_with(c, s, pos))
4833 return 0;
4834
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004835 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004836 ADDOP(c, POP_BLOCK);
4837 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004838
Mark Shannonfee55262019-11-21 09:11:43 +00004839 /* For successful outcome:
4840 * call __exit__(None, None, None)
4841 */
4842 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004843 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004844 ADDOP(c, GET_AWAITABLE);
4845 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4846 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004847
Mark Shannonfee55262019-11-21 09:11:43 +00004848 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004849
Mark Shannonfee55262019-11-21 09:11:43 +00004850 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4851
4852 /* For exceptional outcome: */
4853 compiler_use_next_block(c, final);
4854
4855 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004856 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004857 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004858 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004859 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004860
Mark Shannonfee55262019-11-21 09:11:43 +00004861compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004862 return 1;
4863}
4864
4865
Guido van Rossumc2e20742006-02-27 22:32:47 +00004866/*
4867 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004868 with EXPR as VAR:
4869 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004870 is implemented as:
4871 <code for EXPR>
4872 SETUP_WITH E
4873 <code to store to VAR> or POP_TOP
4874 <code for BLOCK>
4875 LOAD_CONST (None, None, None)
4876 CALL_FUNCTION_EX 0
4877 JUMP_FORWARD EXIT
4878 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4879 POP_JUMP_IF_TRUE T:
4880 RERAISE
4881 T: POP_TOP * 3 (remove exception from stack)
4882 POP_EXCEPT
4883 POP_TOP
4884 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004885 */
Mark Shannonfee55262019-11-21 09:11:43 +00004886
Guido van Rossumc2e20742006-02-27 22:32:47 +00004887static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004888compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004889{
Mark Shannonfee55262019-11-21 09:11:43 +00004890 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004891 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892
4893 assert(s->kind == With_kind);
4894
Guido van Rossumc2e20742006-02-27 22:32:47 +00004895 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004896 final = compiler_new_block(c);
4897 exit = compiler_new_block(c);
4898 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004899 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004900
Thomas Wouters477c8d52006-05-27 19:21:47 +00004901 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004902 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004903 /* Will push bound __exit__ */
4904 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004905
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004906 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004907 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004908 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004909 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910 }
4911
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004912 if (item->optional_vars) {
4913 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004914 }
4915 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004917 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918 }
4919
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004920 pos++;
4921 if (pos == asdl_seq_LEN(s->v.With.items))
4922 /* BLOCK code */
4923 VISIT_SEQ(c, stmt, s->v.With.body)
4924 else if (!compiler_with(c, s, pos))
4925 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004926
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004928 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004929
Mark Shannonfee55262019-11-21 09:11:43 +00004930 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004931
Mark Shannonfee55262019-11-21 09:11:43 +00004932 /* For successful outcome:
4933 * call __exit__(None, None, None)
4934 */
4935 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004936 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004937 ADDOP(c, POP_TOP);
4938 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004939
Mark Shannonfee55262019-11-21 09:11:43 +00004940 /* For exceptional outcome: */
4941 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942
Mark Shannonfee55262019-11-21 09:11:43 +00004943 ADDOP(c, WITH_EXCEPT_START);
4944 compiler_with_except_finish(c);
4945
4946 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004947 return 1;
4948}
4949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004950static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004951compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004954 case NamedExpr_kind:
4955 VISIT(c, expr, e->v.NamedExpr.value);
4956 ADDOP(c, DUP_TOP);
4957 VISIT(c, expr, e->v.NamedExpr.target);
4958 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004959 case BoolOp_kind:
4960 return compiler_boolop(c, e);
4961 case BinOp_kind:
4962 VISIT(c, expr, e->v.BinOp.left);
4963 VISIT(c, expr, e->v.BinOp.right);
4964 ADDOP(c, binop(c, e->v.BinOp.op));
4965 break;
4966 case UnaryOp_kind:
4967 VISIT(c, expr, e->v.UnaryOp.operand);
4968 ADDOP(c, unaryop(e->v.UnaryOp.op));
4969 break;
4970 case Lambda_kind:
4971 return compiler_lambda(c, e);
4972 case IfExp_kind:
4973 return compiler_ifexp(c, e);
4974 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004975 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004977 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 case GeneratorExp_kind:
4979 return compiler_genexp(c, e);
4980 case ListComp_kind:
4981 return compiler_listcomp(c, e);
4982 case SetComp_kind:
4983 return compiler_setcomp(c, e);
4984 case DictComp_kind:
4985 return compiler_dictcomp(c, e);
4986 case Yield_kind:
4987 if (c->u->u_ste->ste_type != FunctionBlock)
4988 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004989 if (e->v.Yield.value) {
4990 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 }
4992 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004993 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004995 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004997 case YieldFrom_kind:
4998 if (c->u->u_ste->ste_type != FunctionBlock)
4999 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005000
5001 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5002 return compiler_error(c, "'yield from' inside async function");
5003
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005004 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005005 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005006 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005007 ADDOP(c, YIELD_FROM);
5008 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005009 case Await_kind:
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005010 if (!(c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT)){
5011 if (c->u->u_ste->ste_type != FunctionBlock){
5012 return compiler_error(c, "'await' outside function");
5013 }
Yury Selivanov75445082015-05-11 22:57:16 -04005014
Victor Stinner331a6a52019-05-27 16:39:22 +02005015 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005016 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5017 return compiler_error(c, "'await' outside async function");
5018 }
5019 }
Yury Selivanov75445082015-05-11 22:57:16 -04005020
5021 VISIT(c, expr, e->v.Await.value);
5022 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005023 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005024 ADDOP(c, YIELD_FROM);
5025 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 case Compare_kind:
5027 return compiler_compare(c, e);
5028 case Call_kind:
5029 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005030 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005031 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005032 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005033 case JoinedStr_kind:
5034 return compiler_joined_str(c, e);
5035 case FormattedValue_kind:
5036 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 /* The following exprs can be assignment targets. */
5038 case Attribute_kind:
5039 if (e->v.Attribute.ctx != AugStore)
5040 VISIT(c, expr, e->v.Attribute.value);
5041 switch (e->v.Attribute.ctx) {
5042 case AugLoad:
5043 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005044 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 case Load:
5046 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5047 break;
5048 case AugStore:
5049 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005050 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 case Store:
5052 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5053 break;
5054 case Del:
5055 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5056 break;
5057 case Param:
5058 default:
5059 PyErr_SetString(PyExc_SystemError,
5060 "param invalid in attribute expression");
5061 return 0;
5062 }
5063 break;
5064 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005065 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 case Starred_kind:
5067 switch (e->v.Starred.ctx) {
5068 case Store:
5069 /* In all legitimate cases, the Starred node was already replaced
5070 * by compiler_list/compiler_tuple. XXX: is that okay? */
5071 return compiler_error(c,
5072 "starred assignment target must be in a list or tuple");
5073 default:
5074 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005075 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005077 break;
5078 case Slice_kind:
5079 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 case Name_kind:
5081 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5082 /* child nodes of List and Tuple will have expr_context set */
5083 case List_kind:
5084 return compiler_list(c, e);
5085 case Tuple_kind:
5086 return compiler_tuple(c, e);
5087 }
5088 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005089}
5090
5091static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005092compiler_visit_expr(struct compiler *c, expr_ty e)
5093{
5094 /* If expr e has a different line number than the last expr/stmt,
5095 set a new line number for the next instruction.
5096 */
5097 int old_lineno = c->u->u_lineno;
5098 int old_col_offset = c->u->u_col_offset;
5099 if (e->lineno != c->u->u_lineno) {
5100 c->u->u_lineno = e->lineno;
5101 c->u->u_lineno_set = 0;
5102 }
5103 /* Updating the column offset is always harmless. */
5104 c->u->u_col_offset = e->col_offset;
5105
5106 int res = compiler_visit_expr1(c, e);
5107
5108 if (old_lineno != c->u->u_lineno) {
5109 c->u->u_lineno = old_lineno;
5110 c->u->u_lineno_set = 0;
5111 }
5112 c->u->u_col_offset = old_col_offset;
5113 return res;
5114}
5115
5116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005117compiler_augassign(struct compiler *c, stmt_ty s)
5118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 expr_ty e = s->v.AugAssign.target;
5120 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 switch (e->kind) {
5125 case Attribute_kind:
5126 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005127 AugLoad, e->lineno, e->col_offset,
5128 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 if (auge == NULL)
5130 return 0;
5131 VISIT(c, expr, auge);
5132 VISIT(c, expr, s->v.AugAssign.value);
5133 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5134 auge->v.Attribute.ctx = AugStore;
5135 VISIT(c, expr, auge);
5136 break;
5137 case Subscript_kind:
5138 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005139 AugLoad, e->lineno, e->col_offset,
5140 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 if (auge == NULL)
5142 return 0;
5143 VISIT(c, expr, auge);
5144 VISIT(c, expr, s->v.AugAssign.value);
5145 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5146 auge->v.Subscript.ctx = AugStore;
5147 VISIT(c, expr, auge);
5148 break;
5149 case Name_kind:
5150 if (!compiler_nameop(c, e->v.Name.id, Load))
5151 return 0;
5152 VISIT(c, expr, s->v.AugAssign.value);
5153 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
5154 return compiler_nameop(c, e->v.Name.id, Store);
5155 default:
5156 PyErr_Format(PyExc_SystemError,
5157 "invalid node type (%d) for augmented assignment",
5158 e->kind);
5159 return 0;
5160 }
5161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005162}
5163
5164static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005165check_ann_expr(struct compiler *c, expr_ty e)
5166{
5167 VISIT(c, expr, e);
5168 ADDOP(c, POP_TOP);
5169 return 1;
5170}
5171
5172static int
5173check_annotation(struct compiler *c, stmt_ty s)
5174{
5175 /* Annotations are only evaluated in a module or class. */
5176 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5177 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5178 return check_ann_expr(c, s->v.AnnAssign.annotation);
5179 }
5180 return 1;
5181}
5182
5183static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005184check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005185{
5186 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005187 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005188 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005189 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005190 return 0;
5191 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005192 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5193 return 0;
5194 }
5195 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5196 return 0;
5197 }
5198 return 1;
5199 case Tuple_kind: {
5200 /* extended slice */
5201 asdl_seq *elts = e->v.Tuple.elts;
5202 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005203 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005204 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005205 return 0;
5206 }
5207 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005208 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005209 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005210 default:
5211 return check_ann_expr(c, e);
5212 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005213}
5214
5215static int
5216compiler_annassign(struct compiler *c, stmt_ty s)
5217{
5218 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005219 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220
5221 assert(s->kind == AnnAssign_kind);
5222
5223 /* We perform the actual assignment first. */
5224 if (s->v.AnnAssign.value) {
5225 VISIT(c, expr, s->v.AnnAssign.value);
5226 VISIT(c, expr, targ);
5227 }
5228 switch (targ->kind) {
5229 case Name_kind:
5230 /* If we have a simple name in a module or class, store annotation. */
5231 if (s->v.AnnAssign.simple &&
5232 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5233 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005234 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5235 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5236 }
5237 else {
5238 VISIT(c, expr, s->v.AnnAssign.annotation);
5239 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005240 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005241 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005242 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005243 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005244 }
5245 break;
5246 case Attribute_kind:
5247 if (!s->v.AnnAssign.value &&
5248 !check_ann_expr(c, targ->v.Attribute.value)) {
5249 return 0;
5250 }
5251 break;
5252 case Subscript_kind:
5253 if (!s->v.AnnAssign.value &&
5254 (!check_ann_expr(c, targ->v.Subscript.value) ||
5255 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5256 return 0;
5257 }
5258 break;
5259 default:
5260 PyErr_Format(PyExc_SystemError,
5261 "invalid node type (%d) for annotated assignment",
5262 targ->kind);
5263 return 0;
5264 }
5265 /* Annotation is evaluated last. */
5266 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5267 return 0;
5268 }
5269 return 1;
5270}
5271
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005272/* Raises a SyntaxError and returns 0.
5273 If something goes wrong, a different exception may be raised.
5274*/
5275
5276static int
5277compiler_error(struct compiler *c, const char *errstr)
5278{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005279 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005281
Victor Stinner14e461d2013-08-26 22:28:21 +02005282 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 if (!loc) {
5284 Py_INCREF(Py_None);
5285 loc = Py_None;
5286 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005287 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005288 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 if (!u)
5290 goto exit;
5291 v = Py_BuildValue("(zO)", errstr, u);
5292 if (!v)
5293 goto exit;
5294 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 Py_DECREF(loc);
5297 Py_XDECREF(u);
5298 Py_XDECREF(v);
5299 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005300}
5301
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005302/* Emits a SyntaxWarning and returns 1 on success.
5303 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5304 and returns 0.
5305*/
5306static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005307compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005308{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005309 va_list vargs;
5310#ifdef HAVE_STDARG_PROTOTYPES
5311 va_start(vargs, format);
5312#else
5313 va_start(vargs);
5314#endif
5315 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5316 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005317 if (msg == NULL) {
5318 return 0;
5319 }
5320 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5321 c->u->u_lineno, NULL, NULL) < 0)
5322 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005323 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005324 /* Replace the SyntaxWarning exception with a SyntaxError
5325 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005326 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005327 assert(PyUnicode_AsUTF8(msg) != NULL);
5328 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005329 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005330 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005331 return 0;
5332 }
5333 Py_DECREF(msg);
5334 return 1;
5335}
5336
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005337static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005338compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005339{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005340 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005342
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005343 if (ctx == Load) {
5344 if (!check_subscripter(c, e->v.Subscript.value)) {
5345 return 0;
5346 }
5347 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5348 return 0;
5349 }
5350 }
5351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 switch (ctx) {
5353 case AugLoad: /* fall through to Load */
5354 case Load: op = BINARY_SUBSCR; break;
5355 case AugStore:/* fall through to Store */
5356 case Store: op = STORE_SUBSCR; break;
5357 case Del: op = DELETE_SUBSCR; break;
5358 case Param:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005359 PyErr_SetString(PyExc_SystemError,
5360 "param invalid in subscript expression");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 return 0;
5362 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005363 if (ctx == AugStore) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 ADDOP(c, ROT_THREE);
5365 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005366 else {
5367 VISIT(c, expr, e->v.Subscript.value);
5368 VISIT(c, expr, e->v.Subscript.slice);
5369 if (ctx == AugLoad) {
5370 ADDOP(c, DUP_TOP_TWO);
5371 }
5372 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 ADDOP(c, op);
5374 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375}
5376
5377static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005378compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 int n = 2;
5381 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 /* only handles the cases where BUILD_SLICE is emitted */
5384 if (s->v.Slice.lower) {
5385 VISIT(c, expr, s->v.Slice.lower);
5386 }
5387 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005388 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 if (s->v.Slice.upper) {
5392 VISIT(c, expr, s->v.Slice.upper);
5393 }
5394 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005395 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 }
5397
5398 if (s->v.Slice.step) {
5399 n++;
5400 VISIT(c, expr, s->v.Slice.step);
5401 }
5402 ADDOP_I(c, BUILD_SLICE, n);
5403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404}
5405
Thomas Wouters89f507f2006-12-13 04:49:30 +00005406/* End of the compiler section, beginning of the assembler section */
5407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005409 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005410
5411 XXX must handle implicit jumps from one block to next
5412*/
5413
Thomas Wouters89f507f2006-12-13 04:49:30 +00005414struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 PyObject *a_bytecode; /* string containing bytecode */
5416 int a_offset; /* offset into bytecode */
5417 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005418 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 PyObject *a_lnotab; /* string containing lnotab */
5420 int a_lnotab_off; /* offset into lnotab */
5421 int a_lineno; /* last lineno of emitted instruction */
5422 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005423};
5424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425static void
T. Wouters99b54d62019-09-12 07:05:33 -07005426dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427{
T. Wouters99b54d62019-09-12 07:05:33 -07005428 int i, j;
5429
5430 /* Get rid of recursion for normal control flow.
5431 Since the number of blocks is limited, unused space in a_postorder
5432 (from a_nblocks to end) can be used as a stack for still not ordered
5433 blocks. */
5434 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005435 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005436 assert(a->a_nblocks < j);
5437 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 }
T. Wouters99b54d62019-09-12 07:05:33 -07005439 while (j < end) {
5440 b = a->a_postorder[j++];
5441 for (i = 0; i < b->b_iused; i++) {
5442 struct instr *instr = &b->b_instr[i];
5443 if (instr->i_jrel || instr->i_jabs)
5444 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005445 }
T. Wouters99b54d62019-09-12 07:05:33 -07005446 assert(a->a_nblocks < j);
5447 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005449}
5450
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005451Py_LOCAL_INLINE(void)
5452stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005454 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005455 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005456 assert(b->b_startdepth < 0);
5457 b->b_startdepth = depth;
5458 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005459 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005460}
5461
5462/* Find the flow path that needs the largest stack. We assume that
5463 * cycles in the flow graph have no net effect on the stack depth.
5464 */
5465static int
5466stackdepth(struct compiler *c)
5467{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005468 basicblock *b, *entryblock = NULL;
5469 basicblock **stack, **sp;
5470 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 b->b_startdepth = INT_MIN;
5473 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005474 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 }
5476 if (!entryblock)
5477 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5479 if (!stack) {
5480 PyErr_NoMemory();
5481 return -1;
5482 }
5483
5484 sp = stack;
5485 stackdepth_push(&sp, entryblock, 0);
5486 while (sp != stack) {
5487 b = *--sp;
5488 int depth = b->b_startdepth;
5489 assert(depth >= 0);
5490 basicblock *next = b->b_next;
5491 for (int i = 0; i < b->b_iused; i++) {
5492 struct instr *instr = &b->b_instr[i];
5493 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5494 if (effect == PY_INVALID_STACK_EFFECT) {
5495 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5496 Py_FatalError("PyCompile_OpcodeStackEffect()");
5497 }
5498 int new_depth = depth + effect;
5499 if (new_depth > maxdepth) {
5500 maxdepth = new_depth;
5501 }
5502 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5503 if (instr->i_jrel || instr->i_jabs) {
5504 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5505 assert(effect != PY_INVALID_STACK_EFFECT);
5506 int target_depth = depth + effect;
5507 if (target_depth > maxdepth) {
5508 maxdepth = target_depth;
5509 }
5510 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005511 stackdepth_push(&sp, instr->i_target, target_depth);
5512 }
5513 depth = new_depth;
5514 if (instr->i_opcode == JUMP_ABSOLUTE ||
5515 instr->i_opcode == JUMP_FORWARD ||
5516 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005517 instr->i_opcode == RAISE_VARARGS ||
5518 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005519 {
5520 /* remaining code is dead */
5521 next = NULL;
5522 break;
5523 }
5524 }
5525 if (next != NULL) {
5526 stackdepth_push(&sp, next, depth);
5527 }
5528 }
5529 PyObject_Free(stack);
5530 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005531}
5532
5533static int
5534assemble_init(struct assembler *a, int nblocks, int firstlineno)
5535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 memset(a, 0, sizeof(struct assembler));
5537 a->a_lineno = firstlineno;
5538 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5539 if (!a->a_bytecode)
5540 return 0;
5541 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5542 if (!a->a_lnotab)
5543 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005544 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 PyErr_NoMemory();
5546 return 0;
5547 }
T. Wouters99b54d62019-09-12 07:05:33 -07005548 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005550 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 PyErr_NoMemory();
5552 return 0;
5553 }
5554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555}
5556
5557static void
5558assemble_free(struct assembler *a)
5559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 Py_XDECREF(a->a_bytecode);
5561 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005562 if (a->a_postorder)
5563 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005564}
5565
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566static int
5567blocksize(basicblock *b)
5568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 int i;
5570 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005573 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005575}
5576
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005577/* Appends a pair to the end of the line number table, a_lnotab, representing
5578 the instruction's bytecode offset and line number. See
5579 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005580
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005581static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005582assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005585 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005587
Serhiy Storchakaab874002016-09-11 13:48:15 +03005588 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005593 if(d_bytecode == 0 && d_lineno == 0)
5594 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 if (d_bytecode > 255) {
5597 int j, nbytes, ncodes = d_bytecode / 255;
5598 nbytes = a->a_lnotab_off + 2 * ncodes;
5599 len = PyBytes_GET_SIZE(a->a_lnotab);
5600 if (nbytes >= len) {
5601 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5602 len = nbytes;
5603 else if (len <= INT_MAX / 2)
5604 len *= 2;
5605 else {
5606 PyErr_NoMemory();
5607 return 0;
5608 }
5609 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5610 return 0;
5611 }
5612 lnotab = (unsigned char *)
5613 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5614 for (j = 0; j < ncodes; j++) {
5615 *lnotab++ = 255;
5616 *lnotab++ = 0;
5617 }
5618 d_bytecode -= ncodes * 255;
5619 a->a_lnotab_off += ncodes * 2;
5620 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005621 assert(0 <= d_bytecode && d_bytecode <= 255);
5622
5623 if (d_lineno < -128 || 127 < d_lineno) {
5624 int j, nbytes, ncodes, k;
5625 if (d_lineno < 0) {
5626 k = -128;
5627 /* use division on positive numbers */
5628 ncodes = (-d_lineno) / 128;
5629 }
5630 else {
5631 k = 127;
5632 ncodes = d_lineno / 127;
5633 }
5634 d_lineno -= ncodes * k;
5635 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 nbytes = a->a_lnotab_off + 2 * ncodes;
5637 len = PyBytes_GET_SIZE(a->a_lnotab);
5638 if (nbytes >= len) {
5639 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5640 len = nbytes;
5641 else if (len <= INT_MAX / 2)
5642 len *= 2;
5643 else {
5644 PyErr_NoMemory();
5645 return 0;
5646 }
5647 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5648 return 0;
5649 }
5650 lnotab = (unsigned char *)
5651 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5652 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005653 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 d_bytecode = 0;
5655 for (j = 1; j < ncodes; j++) {
5656 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005657 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 a->a_lnotab_off += ncodes * 2;
5660 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005661 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 len = PyBytes_GET_SIZE(a->a_lnotab);
5664 if (a->a_lnotab_off + 2 >= len) {
5665 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5666 return 0;
5667 }
5668 lnotab = (unsigned char *)
5669 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 a->a_lnotab_off += 2;
5672 if (d_bytecode) {
5673 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005674 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 }
5676 else { /* First line of a block; def stmt, etc. */
5677 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005678 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 }
5680 a->a_lineno = i->i_lineno;
5681 a->a_lineno_off = a->a_offset;
5682 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005683}
5684
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005685/* assemble_emit()
5686 Extend the bytecode with a new instruction.
5687 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005688*/
5689
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005690static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005691assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005692{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005693 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005695 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005696
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005697 arg = i->i_oparg;
5698 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 if (i->i_lineno && !assemble_lnotab(a, i))
5700 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005701 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 if (len > PY_SSIZE_T_MAX / 2)
5703 return 0;
5704 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5705 return 0;
5706 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005707 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005709 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005711}
5712
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005713static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005714assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005717 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 /* Compute the size of each block and fixup jump args.
5721 Replace block pointer with position in bytecode. */
5722 do {
5723 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005724 for (i = a->a_nblocks - 1; i >= 0; i--) {
5725 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 bsize = blocksize(b);
5727 b->b_offset = totsize;
5728 totsize += bsize;
5729 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005730 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5732 bsize = b->b_offset;
5733 for (i = 0; i < b->b_iused; i++) {
5734 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005735 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 /* Relative jumps are computed relative to
5737 the instruction pointer after fetching
5738 the jump instruction.
5739 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 bsize += isize;
5741 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005743 if (instr->i_jrel) {
5744 instr->i_oparg -= bsize;
5745 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005746 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005747 if (instrsize(instr->i_oparg) != isize) {
5748 extended_arg_recompile = 1;
5749 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 }
5752 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 /* XXX: This is an awful hack that could hurt performance, but
5755 on the bright side it should work until we come up
5756 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 The issue is that in the first loop blocksize() is called
5759 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005760 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 So we loop until we stop seeing new EXTENDED_ARGs.
5764 The only EXTENDED_ARGs that could be popping up are
5765 ones in jump instructions. So this should converge
5766 fairly quickly.
5767 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005768 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005769}
5770
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005771static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005772dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005775 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 tuple = PyTuple_New(size);
5778 if (tuple == NULL)
5779 return NULL;
5780 while (PyDict_Next(dict, &pos, &k, &v)) {
5781 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005782 Py_INCREF(k);
5783 assert((i - offset) < size);
5784 assert((i - offset) >= 0);
5785 PyTuple_SET_ITEM(tuple, i - offset, k);
5786 }
5787 return tuple;
5788}
5789
5790static PyObject *
5791consts_dict_keys_inorder(PyObject *dict)
5792{
5793 PyObject *consts, *k, *v;
5794 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5795
5796 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5797 if (consts == NULL)
5798 return NULL;
5799 while (PyDict_Next(dict, &pos, &k, &v)) {
5800 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005801 /* The keys of the dictionary can be tuples wrapping a contant.
5802 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5803 * the object we want is always second. */
5804 if (PyTuple_CheckExact(k)) {
5805 k = PyTuple_GET_ITEM(k, 1);
5806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005808 assert(i < size);
5809 assert(i >= 0);
5810 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005812 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005813}
5814
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005815static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005816compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005819 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005821 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 if (ste->ste_nested)
5823 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005824 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005826 if (!ste->ste_generator && ste->ste_coroutine)
5827 flags |= CO_COROUTINE;
5828 if (ste->ste_generator && ste->ste_coroutine)
5829 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 if (ste->ste_varargs)
5831 flags |= CO_VARARGS;
5832 if (ste->ste_varkeywords)
5833 flags |= CO_VARKEYWORDS;
5834 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 /* (Only) inherit compilerflags in PyCF_MASK */
5837 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005838
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005839 if ((c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
5840 ste->ste_coroutine &&
5841 !ste->ste_generator) {
5842 flags |= CO_COROUTINE;
5843 }
5844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005846}
5847
INADA Naokic2e16072018-11-26 21:23:22 +09005848// Merge *tuple* with constant cache.
5849// Unlike merge_consts_recursive(), this function doesn't work recursively.
5850static int
5851merge_const_tuple(struct compiler *c, PyObject **tuple)
5852{
5853 assert(PyTuple_CheckExact(*tuple));
5854
5855 PyObject *key = _PyCode_ConstantKey(*tuple);
5856 if (key == NULL) {
5857 return 0;
5858 }
5859
5860 // t is borrowed reference
5861 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5862 Py_DECREF(key);
5863 if (t == NULL) {
5864 return 0;
5865 }
5866 if (t == key) { // tuple is new constant.
5867 return 1;
5868 }
5869
5870 PyObject *u = PyTuple_GET_ITEM(t, 1);
5871 Py_INCREF(u);
5872 Py_DECREF(*tuple);
5873 *tuple = u;
5874 return 1;
5875}
5876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005877static PyCodeObject *
5878makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 PyObject *tmp;
5881 PyCodeObject *co = NULL;
5882 PyObject *consts = NULL;
5883 PyObject *names = NULL;
5884 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 PyObject *name = NULL;
5886 PyObject *freevars = NULL;
5887 PyObject *cellvars = NULL;
5888 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005889 Py_ssize_t nlocals;
5890 int nlocals_int;
5891 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005892 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005893
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005894 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 names = dict_keys_inorder(c->u->u_names, 0);
5896 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5897 if (!consts || !names || !varnames)
5898 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5901 if (!cellvars)
5902 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005903 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 if (!freevars)
5905 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005906
INADA Naokic2e16072018-11-26 21:23:22 +09005907 if (!merge_const_tuple(c, &names) ||
5908 !merge_const_tuple(c, &varnames) ||
5909 !merge_const_tuple(c, &cellvars) ||
5910 !merge_const_tuple(c, &freevars))
5911 {
5912 goto error;
5913 }
5914
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005915 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005916 assert(nlocals < INT_MAX);
5917 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 flags = compute_code_flags(c);
5920 if (flags < 0)
5921 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5924 if (!bytecode)
5925 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5928 if (!tmp)
5929 goto error;
5930 Py_DECREF(consts);
5931 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005932 if (!merge_const_tuple(c, &consts)) {
5933 goto error;
5934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005936 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005937 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005938 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005939 maxdepth = stackdepth(c);
5940 if (maxdepth < 0) {
5941 goto error;
5942 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005943 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005944 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005945 maxdepth, flags, bytecode, consts, names,
5946 varnames, freevars, cellvars, c->c_filename,
5947 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005948 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 Py_XDECREF(consts);
5950 Py_XDECREF(names);
5951 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 Py_XDECREF(name);
5953 Py_XDECREF(freevars);
5954 Py_XDECREF(cellvars);
5955 Py_XDECREF(bytecode);
5956 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005957}
5958
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005959
5960/* For debugging purposes only */
5961#if 0
5962static void
5963dump_instr(const struct instr *i)
5964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 const char *jrel = i->i_jrel ? "jrel " : "";
5966 const char *jabs = i->i_jabs ? "jabs " : "";
5967 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005970 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005972 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5974 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005975}
5976
5977static void
5978dump_basicblock(const basicblock *b)
5979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 const char *seen = b->b_seen ? "seen " : "";
5981 const char *b_return = b->b_return ? "return " : "";
5982 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5983 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5984 if (b->b_instr) {
5985 int i;
5986 for (i = 0; i < b->b_iused; i++) {
5987 fprintf(stderr, " [%02d] ", i);
5988 dump_instr(b->b_instr + i);
5989 }
5990 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005991}
5992#endif
5993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005994static PyCodeObject *
5995assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 basicblock *b, *entryblock;
5998 struct assembler a;
5999 int i, j, nblocks;
6000 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 /* Make sure every block that falls off the end returns None.
6003 XXX NEXT_BLOCK() isn't quite right, because if the last
6004 block ends with a jump or return b_next shouldn't set.
6005 */
6006 if (!c->u->u_curblock->b_return) {
6007 NEXT_BLOCK(c);
6008 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006009 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 ADDOP(c, RETURN_VALUE);
6011 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006013 nblocks = 0;
6014 entryblock = NULL;
6015 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6016 nblocks++;
6017 entryblock = b;
6018 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006020 /* Set firstlineno if it wasn't explicitly set. */
6021 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006022 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6024 else
6025 c->u->u_firstlineno = 1;
6026 }
6027 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6028 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006029 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006031 /* Can't modify the bytecode after computing jump offsets. */
6032 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006033
T. Wouters99b54d62019-09-12 07:05:33 -07006034 /* Emit code in reverse postorder from dfs. */
6035 for (i = a.a_nblocks - 1; i >= 0; i--) {
6036 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006037 for (j = 0; j < b->b_iused; j++)
6038 if (!assemble_emit(&a, &b->b_instr[j]))
6039 goto error;
6040 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6043 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006044 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006048 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 assemble_free(&a);
6050 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006051}
Georg Brandl8334fd92010-12-04 10:26:46 +00006052
6053#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006054PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006055PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6056 PyArena *arena)
6057{
6058 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6059}