blob: dd14023fcc485e2472670220ffd9e23e4fb02547 [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
Pablo Galindo90235812020-03-15 04:29:22 +000044#define IS_TOP_LEVEL_AWAIT(c) ( \
45 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
46 && (c->u->u_ste->ste_type == ModuleBlock))
47
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000048struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 unsigned i_jabs : 1;
50 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
72 unsigned b_seen : 1;
73 /* b_return is true if a RETURN_VALUE opcode is inserted. */
74 unsigned b_return : 1;
75 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
78 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
Mark Shannonfee55262019-11-21 09:11:43 +000088enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
89 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000090
91struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 enum fblocktype fb_type;
93 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020094 /* (optional) type-specific exit or cleanup block */
95 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000096 /* (optional) additional information required for unwinding */
97 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000098};
99
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100enum {
101 COMPILER_SCOPE_MODULE,
102 COMPILER_SCOPE_CLASS,
103 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400104 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400105 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 COMPILER_SCOPE_COMPREHENSION,
107};
108
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109/* The following items change on entry and exit of code blocks.
110 They must be saved and restored when returning to a block.
111*/
112struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400116 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100117 int u_scope_type;
118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 /* The following fields are dicts that map objects to
120 the index of them in co_XXX. The index is used as
121 the argument for opcodes that refer to those collections.
122 */
123 PyObject *u_consts; /* all constants */
124 PyObject *u_names; /* all names */
125 PyObject *u_varnames; /* local variables */
126 PyObject *u_cellvars; /* cell variables */
127 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Victor Stinnerf8e32212013-11-19 23:56:34 +0100131 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100132 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100133 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 /* Pointer to the most recently allocated block. By following b_list
135 members, you can reach all early allocated blocks. */
136 basicblock *u_blocks;
137 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_nfblocks;
140 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 int u_firstlineno; /* the first lineno of the block */
143 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000144 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 int u_lineno_set; /* boolean to indicate whether instr
146 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147};
148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000151The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000153managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000154
155Note that we don't track recursion levels during compilation - the
156task of detecting and rejecting excessive levels of nesting is
157handled by the symbol analysis pass.
158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159*/
160
161struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200162 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 struct symtable *c_st;
164 PyFutureFeatures *c_future; /* pointer to module's __future__ */
165 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166
Georg Brandl8334fd92010-12-04 10:26:46 +0000167 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 int c_interactive; /* true if in interactive mode */
169 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100170 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
171 if this value is different from zero.
172 This can be used to temporarily visit
173 nodes without emitting bytecode to
174 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175
INADA Naokic2e16072018-11-26 21:23:22 +0900176 PyObject *c_const_cache; /* Python dict holding all constants,
177 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 struct compiler_unit *u; /* compiler state for current block */
179 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
180 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181};
182
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100183static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static void compiler_free(struct compiler *);
185static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500186static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100188static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200191static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
193
194static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
195static int compiler_visit_stmt(struct compiler *, stmt_ty);
196static int compiler_visit_keyword(struct compiler *, keyword_ty);
197static int compiler_visit_expr(struct compiler *, expr_ty);
198static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700199static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200200static int compiler_subscript(struct compiler *, expr_ty);
201static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202
Andy Lester76d58772020-03-10 21:18:12 -0500203static int inplace_binop(operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800204static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200205static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500207static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400208static int compiler_async_with(struct compiler *, stmt_ty, int);
209static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100210static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400212 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500213static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400214static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000215
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700216static int compiler_sync_comprehension_generator(
217 struct compiler *c,
218 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200219 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700220 expr_ty elt, expr_ty val, int type);
221
222static int compiler_async_comprehension_generator(
223 struct compiler *c,
224 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200225 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700226 expr_ty elt, expr_ty val, int type);
227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000229static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400231#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000234_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Name mangling: __private becomes _classname__private.
237 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200238 PyObject *result;
239 size_t nlen, plen, ipriv;
240 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 PyUnicode_READ_CHAR(ident, 0) != '_' ||
243 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_INCREF(ident);
245 return ident;
246 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200247 nlen = PyUnicode_GET_LENGTH(ident);
248 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 The only time a name with a dot can occur is when
252 we are compiling an import statement that has a
253 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 TODO(jhylton): Decide whether we want to support
256 mangling of the module name, e.g. __M.X.
257 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
259 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
260 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 Py_INCREF(ident);
262 return ident; /* Don't mangle __whatever__ */
263 }
264 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 ipriv = 0;
266 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
267 ipriv++;
268 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_INCREF(ident);
270 return ident; /* Don't mangle if class is just underscores */
271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200272 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000273
Antoine Pitrou55bff892013-04-06 21:21:04 +0200274 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
275 PyErr_SetString(PyExc_OverflowError,
276 "private identifier too large to be mangled");
277 return NULL;
278 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000279
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
281 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
282 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
283
284 result = PyUnicode_New(1 + nlen + plen, maxchar);
285 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200287 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
288 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200289 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
290 Py_DECREF(result);
291 return NULL;
292 }
293 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
294 Py_DECREF(result);
295 return NULL;
296 }
Victor Stinner8f825062012-04-27 13:55:39 +0200297 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000299}
300
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301static int
302compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000305
INADA Naokic2e16072018-11-26 21:23:22 +0900306 c->c_const_cache = PyDict_New();
307 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900309 }
310
311 c->c_stack = PyList_New(0);
312 if (!c->c_stack) {
313 Py_CLEAR(c->c_const_cache);
314 return 0;
315 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318}
319
320PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200321PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
322 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 struct compiler c;
325 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200326 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200328 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (!__doc__) {
331 __doc__ = PyUnicode_InternFromString("__doc__");
332 if (!__doc__)
333 return NULL;
334 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000335 if (!__annotations__) {
336 __annotations__ = PyUnicode_InternFromString("__annotations__");
337 if (!__annotations__)
338 return NULL;
339 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (!compiler_init(&c))
341 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200342 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 c.c_filename = filename;
344 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200345 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (c.c_future == NULL)
347 goto finally;
348 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 flags = &local_flags;
350 }
351 merged = c.c_future->ff_features | flags->cf_flags;
352 c.c_future->ff_features = merged;
353 flags->cf_flags = merged;
354 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200355 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100357 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200359 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900360 goto finally;
361 }
362
Victor Stinner14e461d2013-08-26 22:28:21 +0200363 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (c.c_st == NULL) {
365 if (!PyErr_Occurred())
366 PyErr_SetString(PyExc_SystemError, "no symtable");
367 goto finally;
368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
Thomas Wouters1175c432006-02-27 22:49:54 +0000372 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 compiler_free(&c);
374 assert(co || PyErr_Occurred());
375 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376}
377
378PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200379PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
380 int optimize, PyArena *arena)
381{
382 PyObject *filename;
383 PyCodeObject *co;
384 filename = PyUnicode_DecodeFSDefault(filename_str);
385 if (filename == NULL)
386 return NULL;
387 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
388 Py_DECREF(filename);
389 return co;
390
391}
392
393PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394PyNode_Compile(struct _node *n, const char *filename)
395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyCodeObject *co = NULL;
397 mod_ty mod;
398 PyArena *arena = PyArena_New();
399 if (!arena)
400 return NULL;
401 mod = PyAST_FromNode(n, NULL, filename, arena);
402 if (mod)
403 co = PyAST_Compile(mod, filename, NULL, arena);
404 PyArena_Free(arena);
405 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000406}
407
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000408static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (c->c_st)
412 PySymtable_Free(c->c_st);
413 if (c->c_future)
414 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200415 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900416 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000418}
419
Guido van Rossum79f25d91997-04-29 20:08:16 +0000420static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_ssize_t i, n;
424 PyObject *v, *k;
425 PyObject *dict = PyDict_New();
426 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 n = PyList_Size(list);
429 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100430 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (!v) {
432 Py_DECREF(dict);
433 return NULL;
434 }
435 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300436 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_DECREF(v);
438 Py_DECREF(dict);
439 return NULL;
440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_DECREF(v);
442 }
443 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444}
445
446/* Return new dict containing names from src that match scope(s).
447
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000448src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450values are integers, starting at offset and increasing by one for
451each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452*/
453
454static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100455dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000456{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700457 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500459 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 assert(offset >= 0);
462 if (dest == NULL)
463 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Meador Inge2ca63152012-07-18 14:20:11 -0500465 /* Sort the keys so that we have a deterministic order on the indexes
466 saved in the returned dictionary. These indexes are used as indexes
467 into the free and cell var storage. Therefore if they aren't
468 deterministic, then the generated bytecode is not deterministic.
469 */
470 sorted_keys = PyDict_Keys(src);
471 if (sorted_keys == NULL)
472 return NULL;
473 if (PyList_Sort(sorted_keys) != 0) {
474 Py_DECREF(sorted_keys);
475 return NULL;
476 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500477 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500478
479 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* XXX this should probably be a macro in symtable.h */
481 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500482 k = PyList_GET_ITEM(sorted_keys, key_i);
483 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 assert(PyLong_Check(v));
485 vi = PyLong_AS_LONG(v);
486 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300489 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(dest);
493 return NULL;
494 }
495 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300496 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500497 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_DECREF(item);
499 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return NULL;
501 }
502 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
504 }
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000507}
508
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509static void
510compiler_unit_check(struct compiler_unit *u)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 basicblock *block;
513 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700514 assert((uintptr_t)block != 0xcbcbcbcbU);
515 assert((uintptr_t)block != 0xfbfbfbfbU);
516 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (block->b_instr != NULL) {
518 assert(block->b_ialloc > 0);
519 assert(block->b_iused > 0);
520 assert(block->b_ialloc >= block->b_iused);
521 }
522 else {
523 assert (block->b_iused == 0);
524 assert (block->b_ialloc == 0);
525 }
526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527}
528
529static void
530compiler_unit_free(struct compiler_unit *u)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 compiler_unit_check(u);
535 b = u->u_blocks;
536 while (b != NULL) {
537 if (b->b_instr)
538 PyObject_Free((void *)b->b_instr);
539 next = b->b_list;
540 PyObject_Free((void *)b);
541 b = next;
542 }
543 Py_CLEAR(u->u_ste);
544 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400545 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_CLEAR(u->u_consts);
547 Py_CLEAR(u->u_names);
548 Py_CLEAR(u->u_varnames);
549 Py_CLEAR(u->u_freevars);
550 Py_CLEAR(u->u_cellvars);
551 Py_CLEAR(u->u_private);
552 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553}
554
555static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100556compiler_enter_scope(struct compiler *c, identifier name,
557 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100560 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
563 struct compiler_unit));
564 if (!u) {
565 PyErr_NoMemory();
566 return 0;
567 }
568 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100569 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100571 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 u->u_kwonlyargcount = 0;
573 u->u_ste = PySymtable_Lookup(c->c_st, key);
574 if (!u->u_ste) {
575 compiler_unit_free(u);
576 return 0;
577 }
578 Py_INCREF(name);
579 u->u_name = name;
580 u->u_varnames = list2dict(u->u_ste->ste_varnames);
581 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
582 if (!u->u_varnames || !u->u_cellvars) {
583 compiler_unit_free(u);
584 return 0;
585 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500586 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000587 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300589 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 int res;
591 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200592 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 name = _PyUnicode_FromId(&PyId___class__);
594 if (!name) {
595 compiler_unit_free(u);
596 return 0;
597 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300598 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500599 if (res < 0) {
600 compiler_unit_free(u);
601 return 0;
602 }
603 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200606 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (!u->u_freevars) {
608 compiler_unit_free(u);
609 return 0;
610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_blocks = NULL;
613 u->u_nfblocks = 0;
614 u->u_firstlineno = lineno;
615 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000616 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 u->u_lineno_set = 0;
618 u->u_consts = PyDict_New();
619 if (!u->u_consts) {
620 compiler_unit_free(u);
621 return 0;
622 }
623 u->u_names = PyDict_New();
624 if (!u->u_names) {
625 compiler_unit_free(u);
626 return 0;
627 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* Push the old compiler_unit on the stack. */
632 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400633 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
635 Py_XDECREF(capsule);
636 compiler_unit_free(u);
637 return 0;
638 }
639 Py_DECREF(capsule);
640 u->u_private = c->u->u_private;
641 Py_XINCREF(u->u_private);
642 }
643 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100646
647 block = compiler_new_block(c);
648 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100650 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000651
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400652 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
653 if (!compiler_set_qualname(c))
654 return 0;
655 }
656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658}
659
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000660static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000661compiler_exit_scope(struct compiler *c)
662{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100663 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 c->c_nestlevel--;
667 compiler_unit_free(c->u);
668 /* Restore c->u to the parent unit. */
669 n = PyList_GET_SIZE(c->c_stack) - 1;
670 if (n >= 0) {
671 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400672 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 assert(c->u);
674 /* we are deleting from a list so this really shouldn't fail */
675 if (PySequence_DelItem(c->c_stack, n) < 0)
676 Py_FatalError("compiler_exit_scope()");
677 compiler_unit_check(c->u);
678 }
679 else
680 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000682}
683
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684static int
685compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100686{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100687 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 _Py_static_string(dot_locals, ".<locals>");
689 Py_ssize_t stack_size;
690 struct compiler_unit *u = c->u;
691 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100692
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100694 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400695 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 if (stack_size > 1) {
697 int scope, force_global = 0;
698 struct compiler_unit *parent;
699 PyObject *mangled, *capsule;
700
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400701 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400702 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 assert(parent);
704
Yury Selivanov75445082015-05-11 22:57:16 -0400705 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
706 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
707 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400708 assert(u->u_name);
709 mangled = _Py_Mangle(parent->u_private, u->u_name);
710 if (!mangled)
711 return 0;
712 scope = PyST_GetScope(parent->u_ste, mangled);
713 Py_DECREF(mangled);
714 assert(scope != GLOBAL_IMPLICIT);
715 if (scope == GLOBAL_EXPLICIT)
716 force_global = 1;
717 }
718
719 if (!force_global) {
720 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400721 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400722 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
723 dot_locals_str = _PyUnicode_FromId(&dot_locals);
724 if (dot_locals_str == NULL)
725 return 0;
726 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
727 if (base == NULL)
728 return 0;
729 }
730 else {
731 Py_INCREF(parent->u_qualname);
732 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400733 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100734 }
735 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400736
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400737 if (base != NULL) {
738 dot_str = _PyUnicode_FromId(&dot);
739 if (dot_str == NULL) {
740 Py_DECREF(base);
741 return 0;
742 }
743 name = PyUnicode_Concat(base, dot_str);
744 Py_DECREF(base);
745 if (name == NULL)
746 return 0;
747 PyUnicode_Append(&name, u->u_name);
748 if (name == NULL)
749 return 0;
750 }
751 else {
752 Py_INCREF(u->u_name);
753 name = u->u_name;
754 }
755 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100756
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400757 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100758}
759
Eric V. Smith235a6f02015-09-19 14:51:32 -0400760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000761/* Allocate a new block and return a pointer to it.
762 Returns NULL on error.
763*/
764
765static basicblock *
766compiler_new_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *b;
769 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 u = c->u;
772 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
773 if (b == NULL) {
774 PyErr_NoMemory();
775 return NULL;
776 }
777 memset((void *)b, 0, sizeof(basicblock));
778 /* Extend the singly linked list of blocks with new block. */
779 b->b_list = u->u_blocks;
780 u->u_blocks = b;
781 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782}
783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785compiler_next_block(struct compiler *c)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 basicblock *block = compiler_new_block(c);
788 if (block == NULL)
789 return NULL;
790 c->u->u_curblock->b_next = block;
791 c->u->u_curblock = block;
792 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
795static basicblock *
796compiler_use_next_block(struct compiler *c, basicblock *block)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 assert(block != NULL);
799 c->u->u_curblock->b_next = block;
800 c->u->u_curblock = block;
801 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000802}
803
804/* Returns the offset of the next instruction in the current block's
805 b_instr array. Resizes the b_instr as necessary.
806 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000807*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808
809static int
Andy Lester76d58772020-03-10 21:18:12 -0500810compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 assert(b != NULL);
813 if (b->b_instr == NULL) {
814 b->b_instr = (struct instr *)PyObject_Malloc(
815 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
816 if (b->b_instr == NULL) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc = DEFAULT_BLOCK_SIZE;
821 memset((char *)b->b_instr, 0,
822 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
823 }
824 else if (b->b_iused == b->b_ialloc) {
825 struct instr *tmp;
826 size_t oldsize, newsize;
827 oldsize = b->b_ialloc * sizeof(struct instr);
828 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000829
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700830 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyErr_NoMemory();
832 return -1;
833 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (newsize == 0) {
836 PyErr_NoMemory();
837 return -1;
838 }
839 b->b_ialloc <<= 1;
840 tmp = (struct instr *)PyObject_Realloc(
841 (void *)b->b_instr, newsize);
842 if (tmp == NULL) {
843 PyErr_NoMemory();
844 return -1;
845 }
846 b->b_instr = tmp;
847 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
848 }
849 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850}
851
Christian Heimes2202f872008-02-06 14:31:34 +0000852/* Set the i_lineno member of the instruction at offset off if the
853 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854 already been set. If it has been set, the call has no effect.
855
Christian Heimes2202f872008-02-06 14:31:34 +0000856 The line number is reset in the following cases:
857 - when entering a new scope
858 - on each statement
859 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200860 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000861 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000862*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000864static void
865compiler_set_lineno(struct compiler *c, int off)
866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 basicblock *b;
868 if (c->u->u_lineno_set)
869 return;
870 c->u->u_lineno_set = 1;
871 b = c->u->u_curblock;
872 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873}
874
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200875/* Return the stack effect of opcode with argument oparg.
876
877 Some opcodes have different stack effect when jump to the target and
878 when not jump. The 'jump' parameter specifies the case:
879
880 * 0 -- when not jump
881 * 1 -- when jump
882 * -1 -- maximal
883 */
884/* XXX Make the stack effect of WITH_CLEANUP_START and
885 WITH_CLEANUP_FINISH deterministic. */
886static int
887stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300890 case NOP:
891 case EXTENDED_ARG:
892 return 0;
893
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200894 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case POP_TOP:
896 return -1;
897 case ROT_TWO:
898 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200899 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return 0;
901 case DUP_TOP:
902 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000903 case DUP_TOP_TWO:
904 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000905
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200906 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case UNARY_POSITIVE:
908 case UNARY_NEGATIVE:
909 case UNARY_NOT:
910 case UNARY_INVERT:
911 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case SET_ADD:
914 case LIST_APPEND:
915 return -1;
916 case MAP_ADD:
917 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000918
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200919 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 case BINARY_POWER:
921 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400922 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 case BINARY_MODULO:
924 case BINARY_ADD:
925 case BINARY_SUBTRACT:
926 case BINARY_SUBSCR:
927 case BINARY_FLOOR_DIVIDE:
928 case BINARY_TRUE_DIVIDE:
929 return -1;
930 case INPLACE_FLOOR_DIVIDE:
931 case INPLACE_TRUE_DIVIDE:
932 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case INPLACE_ADD:
935 case INPLACE_SUBTRACT:
936 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400937 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case INPLACE_MODULO:
939 return -1;
940 case STORE_SUBSCR:
941 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case DELETE_SUBSCR:
943 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 case BINARY_LSHIFT:
946 case BINARY_RSHIFT:
947 case BINARY_AND:
948 case BINARY_XOR:
949 case BINARY_OR:
950 return -1;
951 case INPLACE_POWER:
952 return -1;
953 case GET_ITER:
954 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case PRINT_EXPR:
957 return -1;
958 case LOAD_BUILD_CLASS:
959 return 1;
960 case INPLACE_LSHIFT:
961 case INPLACE_RSHIFT:
962 case INPLACE_AND:
963 case INPLACE_XOR:
964 case INPLACE_OR:
965 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200968 /* 1 in the normal flow.
969 * Restore the stack position and push 6 values before jumping to
970 * the handler if an exception be raised. */
971 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case RETURN_VALUE:
973 return -1;
974 case IMPORT_STAR:
975 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700976 case SETUP_ANNOTATIONS:
977 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case YIELD_VALUE:
979 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500980 case YIELD_FROM:
981 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case POP_BLOCK:
983 return 0;
984 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200985 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case STORE_NAME:
988 return -1;
989 case DELETE_NAME:
990 return 0;
991 case UNPACK_SEQUENCE:
992 return oparg-1;
993 case UNPACK_EX:
994 return (oparg&0xFF) + (oparg>>8);
995 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200996 /* -1 at end of iterator, 1 if continue iterating. */
997 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case STORE_ATTR:
1000 return -2;
1001 case DELETE_ATTR:
1002 return -1;
1003 case STORE_GLOBAL:
1004 return -1;
1005 case DELETE_GLOBAL:
1006 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case LOAD_CONST:
1008 return 1;
1009 case LOAD_NAME:
1010 return 1;
1011 case BUILD_TUPLE:
1012 case BUILD_LIST:
1013 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001014 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return 1-oparg;
1016 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001017 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001018 case BUILD_CONST_KEY_MAP:
1019 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_ATTR:
1021 return 0;
1022 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001023 case IS_OP:
1024 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001026 case JUMP_IF_NOT_EXC_MATCH:
1027 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case IMPORT_NAME:
1029 return -1;
1030 case IMPORT_FROM:
1031 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case JUMP_ABSOLUTE:
1036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001038 case JUMP_IF_TRUE_OR_POP:
1039 case JUMP_IF_FALSE_OR_POP:
1040 return jump ? 0 : -1;
1041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case POP_JUMP_IF_FALSE:
1043 case POP_JUMP_IF_TRUE:
1044 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case LOAD_GLOBAL:
1047 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001049 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001051 /* 0 in the normal flow.
1052 * Restore the stack position and push 6 values before jumping to
1053 * the handler if an exception be raised. */
1054 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001055 case RERAISE:
1056 return -3;
1057
1058 case WITH_EXCEPT_START:
1059 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case LOAD_FAST:
1062 return 1;
1063 case STORE_FAST:
1064 return -1;
1065 case DELETE_FAST:
1066 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case RAISE_VARARGS:
1069 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001070
1071 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001073 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001074 case CALL_METHOD:
1075 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001077 return -oparg-1;
1078 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001079 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001080 case MAKE_FUNCTION:
1081 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1082 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case BUILD_SLICE:
1084 if (oparg == 3)
1085 return -2;
1086 else
1087 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001089 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 case LOAD_CLOSURE:
1091 return 1;
1092 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001093 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 return 1;
1095 case STORE_DEREF:
1096 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001097 case DELETE_DEREF:
1098 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001099
1100 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001101 case GET_AWAITABLE:
1102 return 0;
1103 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001104 /* 0 in the normal flow.
1105 * Restore the stack position to the position before the result
1106 * of __aenter__ and push 6 values before jumping to the handler
1107 * if an exception be raised. */
1108 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001109 case BEFORE_ASYNC_WITH:
1110 return 1;
1111 case GET_AITER:
1112 return 0;
1113 case GET_ANEXT:
1114 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001115 case GET_YIELD_FROM_ITER:
1116 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001117 case END_ASYNC_FOR:
1118 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001119 case FORMAT_VALUE:
1120 /* If there's a fmt_spec on the stack, we go from 2->1,
1121 else 1->1. */
1122 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001123 case LOAD_METHOD:
1124 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001125 case LOAD_ASSERTION_ERROR:
1126 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001127 case LIST_TO_TUPLE:
1128 return 0;
1129 case LIST_EXTEND:
1130 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001131 case DICT_MERGE:
1132 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001133 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001135 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Larry Hastings3a907972013-11-23 14:49:22 -08001137 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138}
1139
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001140int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001141PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1142{
1143 return stack_effect(opcode, oparg, jump);
1144}
1145
1146int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001147PyCompile_OpcodeStackEffect(int opcode, int oparg)
1148{
1149 return stack_effect(opcode, oparg, -1);
1150}
1151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152/* Add an opcode with no argument.
1153 Returns 0 on failure, 1 on success.
1154*/
1155
1156static int
1157compiler_addop(struct compiler *c, int opcode)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 basicblock *b;
1160 struct instr *i;
1161 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001162 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001163 if (c->c_do_not_emit_bytecode) {
1164 return 1;
1165 }
Andy Lester76d58772020-03-10 21:18:12 -05001166 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 if (off < 0)
1168 return 0;
1169 b = c->u->u_curblock;
1170 i = &b->b_instr[off];
1171 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001172 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (opcode == RETURN_VALUE)
1174 b->b_return = 1;
1175 compiler_set_lineno(c, off);
1176 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177}
1178
Victor Stinnerf8e32212013-11-19 23:56:34 +01001179static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001180compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001185 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001187 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001189 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001190 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001191 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 return -1;
1194 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001195 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_DECREF(v);
1197 return -1;
1198 }
1199 Py_DECREF(v);
1200 }
1201 else
1202 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 return arg;
1204}
1205
INADA Naokic2e16072018-11-26 21:23:22 +09001206// Merge const *o* recursively and return constant key object.
1207static PyObject*
1208merge_consts_recursive(struct compiler *c, PyObject *o)
1209{
1210 // None and Ellipsis are singleton, and key is the singleton.
1211 // No need to merge object and key.
1212 if (o == Py_None || o == Py_Ellipsis) {
1213 Py_INCREF(o);
1214 return o;
1215 }
1216
1217 PyObject *key = _PyCode_ConstantKey(o);
1218 if (key == NULL) {
1219 return NULL;
1220 }
1221
1222 // t is borrowed reference
1223 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1224 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001225 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001226 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001227 Py_DECREF(key);
1228 return t;
1229 }
1230
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001232 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001234 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001235 Py_ssize_t len = PyTuple_GET_SIZE(o);
1236 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001237 PyObject *item = PyTuple_GET_ITEM(o, i);
1238 PyObject *u = merge_consts_recursive(c, item);
1239 if (u == NULL) {
1240 Py_DECREF(key);
1241 return NULL;
1242 }
1243
1244 // See _PyCode_ConstantKey()
1245 PyObject *v; // borrowed
1246 if (PyTuple_CheckExact(u)) {
1247 v = PyTuple_GET_ITEM(u, 1);
1248 }
1249 else {
1250 v = u;
1251 }
1252 if (v != item) {
1253 Py_INCREF(v);
1254 PyTuple_SET_ITEM(o, i, v);
1255 Py_DECREF(item);
1256 }
1257
1258 Py_DECREF(u);
1259 }
1260 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001262 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001263 // constant keys.
1264 // See _PyCode_ConstantKey() for detail.
1265 assert(PyTuple_CheckExact(key));
1266 assert(PyTuple_GET_SIZE(key) == 2);
1267
1268 Py_ssize_t len = PySet_GET_SIZE(o);
1269 if (len == 0) { // empty frozenset should not be re-created.
1270 return key;
1271 }
1272 PyObject *tuple = PyTuple_New(len);
1273 if (tuple == NULL) {
1274 Py_DECREF(key);
1275 return NULL;
1276 }
1277 Py_ssize_t i = 0, pos = 0;
1278 PyObject *item;
1279 Py_hash_t hash;
1280 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1281 PyObject *k = merge_consts_recursive(c, item);
1282 if (k == NULL) {
1283 Py_DECREF(tuple);
1284 Py_DECREF(key);
1285 return NULL;
1286 }
1287 PyObject *u;
1288 if (PyTuple_CheckExact(k)) {
1289 u = PyTuple_GET_ITEM(k, 1);
1290 Py_INCREF(u);
1291 Py_DECREF(k);
1292 }
1293 else {
1294 u = k;
1295 }
1296 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1297 i++;
1298 }
1299
1300 // Instead of rewriting o, we create new frozenset and embed in the
1301 // key tuple. Caller should get merged frozenset from the key tuple.
1302 PyObject *new = PyFrozenSet_New(tuple);
1303 Py_DECREF(tuple);
1304 if (new == NULL) {
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 assert(PyTuple_GET_ITEM(key, 1) == o);
1309 Py_DECREF(o);
1310 PyTuple_SET_ITEM(key, 1, new);
1311 }
INADA Naokic2e16072018-11-26 21:23:22 +09001312
1313 return key;
1314}
1315
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316static Py_ssize_t
1317compiler_add_const(struct compiler *c, PyObject *o)
1318{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001319 if (c->c_do_not_emit_bytecode) {
1320 return 0;
1321 }
1322
INADA Naokic2e16072018-11-26 21:23:22 +09001323 PyObject *key = merge_consts_recursive(c, o);
1324 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001326 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001327
Andy Lester76d58772020-03-10 21:18:12 -05001328 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001329 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331}
1332
1333static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001334compiler_addop_load_const(struct compiler *c, PyObject *o)
1335{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001336 if (c->c_do_not_emit_bytecode) {
1337 return 1;
1338 }
1339
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001340 Py_ssize_t arg = compiler_add_const(c, o);
1341 if (arg < 0)
1342 return 0;
1343 return compiler_addop_i(c, LOAD_CONST, arg);
1344}
1345
1346static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001350 if (c->c_do_not_emit_bytecode) {
1351 return 1;
1352 }
1353
Andy Lester76d58772020-03-10 21:18:12 -05001354 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 return compiler_addop_i(c, opcode, arg);
1358}
1359
1360static int
1361compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001364 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001365
1366 if (c->c_do_not_emit_bytecode) {
1367 return 1;
1368 }
1369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1371 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001372 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001373 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001374 Py_DECREF(mangled);
1375 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001376 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 return compiler_addop_i(c, opcode, arg);
1378}
1379
1380/* Add an opcode with an integer argument.
1381 Returns 0 on failure, 1 on success.
1382*/
1383
1384static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001385compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 struct instr *i;
1388 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001389
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001390 if (c->c_do_not_emit_bytecode) {
1391 return 1;
1392 }
1393
Victor Stinner2ad474b2016-03-01 23:34:47 +01001394 /* oparg value is unsigned, but a signed C int is usually used to store
1395 it in the C code (like Python/ceval.c).
1396
1397 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1398
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001399 The argument of a concrete bytecode instruction is limited to 8-bit.
1400 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1401 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001402 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001403
Andy Lester76d58772020-03-10 21:18:12 -05001404 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (off < 0)
1406 return 0;
1407 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001408 i->i_opcode = opcode;
1409 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 compiler_set_lineno(c, off);
1411 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412}
1413
1414static int
1415compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 struct instr *i;
1418 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001420 if (c->c_do_not_emit_bytecode) {
1421 return 1;
1422 }
1423
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001424 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001426 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (off < 0)
1428 return 0;
1429 i = &c->u->u_curblock->b_instr[off];
1430 i->i_opcode = opcode;
1431 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (absolute)
1433 i->i_jabs = 1;
1434 else
1435 i->i_jrel = 1;
1436 compiler_set_lineno(c, off);
1437 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438}
1439
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001440/* NEXT_BLOCK() creates an implicit jump from the current block
1441 to the new block.
1442
1443 The returns inside this macro make it impossible to decref objects
1444 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (compiler_next_block((C)) == NULL) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
1451#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) \
1453 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454}
1455
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (!compiler_addop((C), (OP))) { \
1458 compiler_exit_scope(c); \
1459 return 0; \
1460 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001461}
1462
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001463#define ADDOP_LOAD_CONST(C, O) { \
1464 if (!compiler_addop_load_const((C), (O))) \
1465 return 0; \
1466}
1467
1468/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1469#define ADDOP_LOAD_CONST_NEW(C, O) { \
1470 PyObject *__new_const = (O); \
1471 if (__new_const == NULL) { \
1472 return 0; \
1473 } \
1474 if (!compiler_addop_load_const((C), __new_const)) { \
1475 Py_DECREF(__new_const); \
1476 return 0; \
1477 } \
1478 Py_DECREF(__new_const); \
1479}
1480
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1483 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484}
1485
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001486/* Same as ADDOP_O, but steals a reference. */
1487#define ADDOP_N(C, OP, O, TYPE) { \
1488 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1489 Py_DECREF((O)); \
1490 return 0; \
1491 } \
1492 Py_DECREF((O)); \
1493}
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_addop_i((C), (OP), (O))) \
1502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
1505#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_addop_j((C), (OP), (O), 1)) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
1510#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!compiler_addop_j((C), (OP), (O), 0)) \
1512 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513}
1514
Mark Shannon9af0e472020-01-14 10:12:45 +00001515
1516#define ADDOP_COMPARE(C, CMP) { \
1517 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1518 return 0; \
1519}
1520
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1522 the ASDL name to synthesize the name of the C type and the visit function.
1523*/
1524
1525#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!compiler_visit_ ## TYPE((C), (V))) \
1527 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528}
1529
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001530#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (!compiler_visit_ ## TYPE((C), (V))) { \
1532 compiler_exit_scope(c); \
1533 return 0; \
1534 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001535}
1536
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (!compiler_visit_slice((C), (V), (CTX))) \
1539 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540}
1541
1542#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 int _i; \
1544 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1545 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1546 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1547 if (!compiler_visit_ ## TYPE((C), elt)) \
1548 return 0; \
1549 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550}
1551
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001552#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 int _i; \
1554 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1555 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1556 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1557 if (!compiler_visit_ ## TYPE((C), elt)) { \
1558 compiler_exit_scope(c); \
1559 return 0; \
1560 } \
1561 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001562}
1563
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001564/* These macros allows to check only for errors and not emmit bytecode
1565 * while visiting nodes.
1566*/
1567
1568#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1569 c->c_do_not_emit_bytecode++;
1570
1571#define END_DO_NOT_EMIT_BYTECODE \
1572 c->c_do_not_emit_bytecode--; \
1573}
1574
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001575/* Search if variable annotations are present statically in a block. */
1576
1577static int
1578find_ann(asdl_seq *stmts)
1579{
1580 int i, j, res = 0;
1581 stmt_ty st;
1582
1583 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1584 st = (stmt_ty)asdl_seq_GET(stmts, i);
1585 switch (st->kind) {
1586 case AnnAssign_kind:
1587 return 1;
1588 case For_kind:
1589 res = find_ann(st->v.For.body) ||
1590 find_ann(st->v.For.orelse);
1591 break;
1592 case AsyncFor_kind:
1593 res = find_ann(st->v.AsyncFor.body) ||
1594 find_ann(st->v.AsyncFor.orelse);
1595 break;
1596 case While_kind:
1597 res = find_ann(st->v.While.body) ||
1598 find_ann(st->v.While.orelse);
1599 break;
1600 case If_kind:
1601 res = find_ann(st->v.If.body) ||
1602 find_ann(st->v.If.orelse);
1603 break;
1604 case With_kind:
1605 res = find_ann(st->v.With.body);
1606 break;
1607 case AsyncWith_kind:
1608 res = find_ann(st->v.AsyncWith.body);
1609 break;
1610 case Try_kind:
1611 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1612 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1613 st->v.Try.handlers, j);
1614 if (find_ann(handler->v.ExceptHandler.body)) {
1615 return 1;
1616 }
1617 }
1618 res = find_ann(st->v.Try.body) ||
1619 find_ann(st->v.Try.finalbody) ||
1620 find_ann(st->v.Try.orelse);
1621 break;
1622 default:
1623 res = 0;
1624 }
1625 if (res) {
1626 break;
1627 }
1628 }
1629 return res;
1630}
1631
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001632/*
1633 * Frame block handling functions
1634 */
1635
1636static int
1637compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001638 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001639{
1640 struct fblockinfo *f;
1641 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1642 PyErr_SetString(PyExc_SyntaxError,
1643 "too many statically nested blocks");
1644 return 0;
1645 }
1646 f = &c->u->u_fblock[c->u->u_nfblocks++];
1647 f->fb_type = t;
1648 f->fb_block = b;
1649 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001650 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001651 return 1;
1652}
1653
1654static void
1655compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1656{
1657 struct compiler_unit *u = c->u;
1658 assert(u->u_nfblocks > 0);
1659 u->u_nfblocks--;
1660 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1661 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1662}
1663
Mark Shannonfee55262019-11-21 09:11:43 +00001664static int
1665compiler_call_exit_with_nones(struct compiler *c) {
1666 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1667 ADDOP(c, DUP_TOP);
1668 ADDOP(c, DUP_TOP);
1669 ADDOP_I(c, CALL_FUNCTION, 3);
1670 return 1;
1671}
1672
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001673/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001674 * popping the blocks will be restored afterwards, unless another
1675 * return, break or continue is found. In which case, the TOS will
1676 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001677 */
1678static int
1679compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1680 int preserve_tos)
1681{
1682 switch (info->fb_type) {
1683 case WHILE_LOOP:
1684 return 1;
1685
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001686 case FOR_LOOP:
1687 /* Pop the iterator */
1688 if (preserve_tos) {
1689 ADDOP(c, ROT_TWO);
1690 }
1691 ADDOP(c, POP_TOP);
1692 return 1;
1693
1694 case EXCEPT:
1695 ADDOP(c, POP_BLOCK);
1696 return 1;
1697
1698 case FINALLY_TRY:
1699 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001700 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001701 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1702 return 0;
1703 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001704 }
Mark Shannon88dce262019-12-30 09:53:36 +00001705 /* Emit the finally block, restoring the line number when done */
1706 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001707 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001708 c->u->u_lineno = saved_lineno;
1709 c->u->u_lineno_set = 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001710 if (preserve_tos) {
1711 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001712 }
1713 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001714
Mark Shannonfee55262019-11-21 09:11:43 +00001715 case FINALLY_END:
1716 if (preserve_tos) {
1717 ADDOP(c, ROT_FOUR);
1718 }
1719 ADDOP(c, POP_TOP);
1720 ADDOP(c, POP_TOP);
1721 ADDOP(c, POP_TOP);
1722 if (preserve_tos) {
1723 ADDOP(c, ROT_FOUR);
1724 }
1725 ADDOP(c, POP_EXCEPT);
1726 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001727
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001728 case WITH:
1729 case ASYNC_WITH:
1730 ADDOP(c, POP_BLOCK);
1731 if (preserve_tos) {
1732 ADDOP(c, ROT_TWO);
1733 }
Mark Shannonfee55262019-11-21 09:11:43 +00001734 if(!compiler_call_exit_with_nones(c)) {
1735 return 0;
1736 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 if (info->fb_type == ASYNC_WITH) {
1738 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001739 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001740 ADDOP(c, YIELD_FROM);
1741 }
Mark Shannonfee55262019-11-21 09:11:43 +00001742 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001743 return 1;
1744
1745 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001746 if (info->fb_datum) {
1747 ADDOP(c, POP_BLOCK);
1748 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 if (preserve_tos) {
1750 ADDOP(c, ROT_FOUR);
1751 }
Mark Shannonfee55262019-11-21 09:11:43 +00001752 ADDOP(c, POP_EXCEPT);
1753 if (info->fb_datum) {
1754 ADDOP_LOAD_CONST(c, Py_None);
1755 compiler_nameop(c, info->fb_datum, Store);
1756 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001757 }
Mark Shannonfee55262019-11-21 09:11:43 +00001758 return 1;
1759
1760 case POP_VALUE:
1761 if (preserve_tos) {
1762 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001763 }
Mark Shannonfee55262019-11-21 09:11:43 +00001764 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001765 return 1;
1766 }
1767 Py_UNREACHABLE();
1768}
1769
Mark Shannonfee55262019-11-21 09:11:43 +00001770/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1771static int
1772compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1773 if (c->u->u_nfblocks == 0) {
1774 return 1;
1775 }
1776 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1777 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1778 *loop = top;
1779 return 1;
1780 }
1781 struct fblockinfo copy = *top;
1782 c->u->u_nfblocks--;
1783 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1784 return 0;
1785 }
1786 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1787 return 0;
1788 }
1789 c->u->u_fblock[c->u->u_nfblocks] = copy;
1790 c->u->u_nfblocks++;
1791 return 1;
1792}
1793
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001794/* Compile a sequence of statements, checking for a docstring
1795 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796
1797static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001798compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001800 int i = 0;
1801 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001802 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001803
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001804 /* Set current line number to the line number of first statement.
1805 This way line number for SETUP_ANNOTATIONS will always
1806 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301807 If body is empty, then lineno will be set later in assemble. */
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001808 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1809 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001810 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001811 c->u->u_lineno = st->lineno;
1812 }
1813 /* Every annotated class and module should have __annotations__. */
1814 if (find_ann(stmts)) {
1815 ADDOP(c, SETUP_ANNOTATIONS);
1816 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001817 if (!asdl_seq_LEN(stmts))
1818 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001819 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001820 if (c->c_optimize < 2) {
1821 docstring = _PyAST_GetDocString(stmts);
1822 if (docstring) {
1823 i = 1;
1824 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1825 assert(st->kind == Expr_kind);
1826 VISIT(c, expr, st->v.Expr.value);
1827 if (!compiler_nameop(c, __doc__, Store))
1828 return 0;
1829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001831 for (; i < asdl_seq_LEN(stmts); i++)
1832 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834}
1835
1836static PyCodeObject *
1837compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyCodeObject *co;
1840 int addNone = 1;
1841 static PyObject *module;
1842 if (!module) {
1843 module = PyUnicode_InternFromString("<module>");
1844 if (!module)
1845 return NULL;
1846 }
1847 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001848 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return NULL;
1850 switch (mod->kind) {
1851 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001852 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 compiler_exit_scope(c);
1854 return 0;
1855 }
1856 break;
1857 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001858 if (find_ann(mod->v.Interactive.body)) {
1859 ADDOP(c, SETUP_ANNOTATIONS);
1860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 c->c_interactive = 1;
1862 VISIT_SEQ_IN_SCOPE(c, stmt,
1863 mod->v.Interactive.body);
1864 break;
1865 case Expression_kind:
1866 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1867 addNone = 0;
1868 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 default:
1870 PyErr_Format(PyExc_SystemError,
1871 "module kind %d should not be possible",
1872 mod->kind);
1873 return 0;
1874 }
1875 co = assemble(c, addNone);
1876 compiler_exit_scope(c);
1877 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001878}
1879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880/* The test for LOCAL must come before the test for FREE in order to
1881 handle classes where name is both local and free. The local var is
1882 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001883*/
1884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885static int
1886get_ref_type(struct compiler *c, PyObject *name)
1887{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001888 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001889 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001890 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001891 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001892 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (scope == 0) {
1894 char buf[350];
1895 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001896 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001898 PyUnicode_AsUTF8(name),
1899 PyUnicode_AsUTF8(c->u->u_name),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1902 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1903 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 );
1905 Py_FatalError(buf);
1906 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_lookup_arg(PyObject *dict, PyObject *name)
1913{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 PyObject *v;
1915 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001917 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001918 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001924 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 if (qualname == NULL)
1926 qualname = co->co_name;
1927
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 if (free) {
1929 for (i = 0; i < free; ++i) {
1930 /* Bypass com_addop_varname because it will generate
1931 LOAD_DEREF but LOAD_CLOSURE is needed.
1932 */
1933 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1934 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001936 /* Special case: If a class contains a method with a
1937 free variable that has the same name as a method,
1938 the name will be considered free *and* local in the
1939 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001940 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 */
1942 reftype = get_ref_type(c, name);
1943 if (reftype == CELL)
1944 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1945 else /* (reftype == FREE) */
1946 arg = compiler_lookup_arg(c->u->u_freevars, name);
1947 if (arg == -1) {
1948 fprintf(stderr,
1949 "lookup %s in %s %d %d\n"
1950 "freevars of %s: %s\n",
1951 PyUnicode_AsUTF8(PyObject_Repr(name)),
1952 PyUnicode_AsUTF8(c->u->u_name),
1953 reftype, arg,
1954 PyUnicode_AsUTF8(co->co_name),
1955 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1956 Py_FatalError("compiler_make_closure()");
1957 }
1958 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 flags |= 0x08;
1961 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001963 ADDOP_LOAD_CONST(c, (PyObject*)co);
1964 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967}
1968
1969static int
1970compiler_decorators(struct compiler *c, asdl_seq* decos)
1971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (!decos)
1975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1978 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1979 }
1980 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981}
1982
1983static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001984compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001986{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001987 /* Push a dict of keyword-only default values.
1988
1989 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1990 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 int i;
1992 PyObject *keys = NULL;
1993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1995 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1996 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1997 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001998 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001999 if (!mangled) {
2000 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 if (keys == NULL) {
2003 keys = PyList_New(1);
2004 if (keys == NULL) {
2005 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002006 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002007 }
2008 PyList_SET_ITEM(keys, 0, mangled);
2009 }
2010 else {
2011 int res = PyList_Append(keys, mangled);
2012 Py_DECREF(mangled);
2013 if (res == -1) {
2014 goto error;
2015 }
2016 }
2017 if (!compiler_visit_expr(c, default_)) {
2018 goto error;
2019 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
2021 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 if (keys != NULL) {
2023 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2024 PyObject *keys_tuple = PyList_AsTuple(keys);
2025 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002026 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002027 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028 assert(default_count > 0);
2029 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 }
2031 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002032 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002033 }
2034
2035error:
2036 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002037 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002038}
2039
2040static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002041compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2042{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002043 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002044 return 1;
2045}
2046
2047static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002048compiler_visit_argannotation(struct compiler *c, identifier id,
2049 expr_ty annotation, PyObject *names)
2050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002052 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002053 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2054 VISIT(c, annexpr, annotation)
2055 }
2056 else {
2057 VISIT(c, expr, annotation);
2058 }
Victor Stinner065efc32014-02-18 22:07:56 +01002059 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002062 if (PyList_Append(names, mangled) < 0) {
2063 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002065 }
2066 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002068 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002069}
2070
2071static int
2072compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2073 PyObject *names)
2074{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 for (i = 0; i < asdl_seq_LEN(args); i++) {
2077 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002078 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 c,
2080 arg->arg,
2081 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002082 names))
2083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002086}
2087
2088static int
2089compiler_visit_annotations(struct compiler *c, arguments_ty args,
2090 expr_ty returns)
2091{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002092 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002093 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002094
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002095 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 */
2097 static identifier return_str;
2098 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002099 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 names = PyList_New(0);
2101 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002102 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002103
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002104 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002106 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2107 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002108 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002109 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002110 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002112 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002114 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002115 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002116 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (!return_str) {
2120 return_str = PyUnicode_InternFromString("return");
2121 if (!return_str)
2122 goto error;
2123 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002124 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 goto error;
2126 }
2127
2128 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002130 PyObject *keytuple = PyList_AsTuple(names);
2131 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002132 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002133 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002134 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002136 else {
2137 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002140
2141error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002143 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002144}
2145
2146static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002147compiler_visit_defaults(struct compiler *c, arguments_ty args)
2148{
2149 VISIT_SEQ(c, expr, args->defaults);
2150 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2151 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152}
2153
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154static Py_ssize_t
2155compiler_default_arguments(struct compiler *c, arguments_ty args)
2156{
2157 Py_ssize_t funcflags = 0;
2158 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002159 if (!compiler_visit_defaults(c, args))
2160 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002161 funcflags |= 0x01;
2162 }
2163 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002164 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002165 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002166 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002167 return -1;
2168 }
2169 else if (res > 0) {
2170 funcflags |= 0x02;
2171 }
2172 }
2173 return funcflags;
2174}
2175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176static int
Yury Selivanov75445082015-05-11 22:57:16 -04002177compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002180 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002181 arguments_ty args;
2182 expr_ty returns;
2183 identifier name;
2184 asdl_seq* decos;
2185 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002186 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002187 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002188 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002189 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190
Yury Selivanov75445082015-05-11 22:57:16 -04002191 if (is_async) {
2192 assert(s->kind == AsyncFunctionDef_kind);
2193
2194 args = s->v.AsyncFunctionDef.args;
2195 returns = s->v.AsyncFunctionDef.returns;
2196 decos = s->v.AsyncFunctionDef.decorator_list;
2197 name = s->v.AsyncFunctionDef.name;
2198 body = s->v.AsyncFunctionDef.body;
2199
2200 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2201 } else {
2202 assert(s->kind == FunctionDef_kind);
2203
2204 args = s->v.FunctionDef.args;
2205 returns = s->v.FunctionDef.returns;
2206 decos = s->v.FunctionDef.decorator_list;
2207 name = s->v.FunctionDef.name;
2208 body = s->v.FunctionDef.body;
2209
2210 scope_type = COMPILER_SCOPE_FUNCTION;
2211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (!compiler_decorators(c, decos))
2214 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002215
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002216 firstlineno = s->lineno;
2217 if (asdl_seq_LEN(decos)) {
2218 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2219 }
2220
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002221 funcflags = compiler_default_arguments(c, args);
2222 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002224 }
2225
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002226 annotations = compiler_visit_annotations(c, args, returns);
2227 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002228 return 0;
2229 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002230 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002231 funcflags |= 0x04;
2232 }
2233
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002234 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002235 return 0;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237
INADA Naokicb41b272017-02-23 00:31:59 +09002238 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002239 if (c->c_optimize < 2) {
2240 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002241 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002242 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 compiler_exit_scope(c);
2244 return 0;
2245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002248 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002250 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002252 qualname = c->u->u_qualname;
2253 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002255 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002256 Py_XDECREF(qualname);
2257 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002261 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002262 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 /* decorators */
2266 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2267 ADDOP_I(c, CALL_FUNCTION, 1);
2268 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269
Yury Selivanov75445082015-05-11 22:57:16 -04002270 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271}
2272
2273static int
2274compiler_class(struct compiler *c, stmt_ty s)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyCodeObject *co;
2277 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002278 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (!compiler_decorators(c, decos))
2282 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002283
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002284 firstlineno = s->lineno;
2285 if (asdl_seq_LEN(decos)) {
2286 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2287 }
2288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* ultimately generate code for:
2290 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2291 where:
2292 <func> is a function/closure created from the class body;
2293 it has a single argument (__locals__) where the dict
2294 (or MutableSequence) representing the locals is passed
2295 <name> is the class name
2296 <bases> is the positional arguments and *varargs argument
2297 <keywords> is the keyword arguments and **kwds argument
2298 This borrows from compiler_call.
2299 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002302 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002303 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return 0;
2305 /* this block represents what we do in the new scope */
2306 {
2307 /* use the class name for name mangling */
2308 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002309 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* load (global) __name__ ... */
2311 str = PyUnicode_InternFromString("__name__");
2312 if (!str || !compiler_nameop(c, str, Load)) {
2313 Py_XDECREF(str);
2314 compiler_exit_scope(c);
2315 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 Py_DECREF(str);
2318 /* ... and store it as __module__ */
2319 str = PyUnicode_InternFromString("__module__");
2320 if (!str || !compiler_nameop(c, str, Store)) {
2321 Py_XDECREF(str);
2322 compiler_exit_scope(c);
2323 return 0;
2324 }
2325 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002326 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002327 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002328 str = PyUnicode_InternFromString("__qualname__");
2329 if (!str || !compiler_nameop(c, str, Store)) {
2330 Py_XDECREF(str);
2331 compiler_exit_scope(c);
2332 return 0;
2333 }
2334 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002336 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 compiler_exit_scope(c);
2338 return 0;
2339 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002340 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002341 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002342 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002343 str = PyUnicode_InternFromString("__class__");
2344 if (str == NULL) {
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 i = compiler_lookup_arg(c->u->u_cellvars, str);
2349 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002350 if (i < 0) {
2351 compiler_exit_scope(c);
2352 return 0;
2353 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002354 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002357 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002358 str = PyUnicode_InternFromString("__classcell__");
2359 if (!str || !compiler_nameop(c, str, Store)) {
2360 Py_XDECREF(str);
2361 compiler_exit_scope(c);
2362 return 0;
2363 }
2364 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002366 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002367 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002368 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002369 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002370 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002371 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* create the code object */
2373 co = assemble(c, 1);
2374 }
2375 /* leave the new scope */
2376 compiler_exit_scope(c);
2377 if (co == NULL)
2378 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* 2. load the 'build_class' function */
2381 ADDOP(c, LOAD_BUILD_CLASS);
2382
2383 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002384 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 Py_DECREF(co);
2386
2387 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002388 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389
2390 /* 5. generate the rest of the code for the call */
2391 if (!compiler_call_helper(c, 2,
2392 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002393 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return 0;
2395
2396 /* 6. apply decorators */
2397 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2398 ADDOP_I(c, CALL_FUNCTION, 1);
2399 }
2400
2401 /* 7. store into <name> */
2402 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2403 return 0;
2404 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405}
2406
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002407/* Return 0 if the expression is a constant value except named singletons.
2408 Return 1 otherwise. */
2409static int
2410check_is_arg(expr_ty e)
2411{
2412 if (e->kind != Constant_kind) {
2413 return 1;
2414 }
2415 PyObject *value = e->v.Constant.value;
2416 return (value == Py_None
2417 || value == Py_False
2418 || value == Py_True
2419 || value == Py_Ellipsis);
2420}
2421
2422/* Check operands of identity chacks ("is" and "is not").
2423 Emit a warning if any operand is a constant except named singletons.
2424 Return 0 on error.
2425 */
2426static int
2427check_compare(struct compiler *c, expr_ty e)
2428{
2429 Py_ssize_t i, n;
2430 int left = check_is_arg(e->v.Compare.left);
2431 n = asdl_seq_LEN(e->v.Compare.ops);
2432 for (i = 0; i < n; i++) {
2433 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2434 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2435 if (op == Is || op == IsNot) {
2436 if (!right || !left) {
2437 const char *msg = (op == Is)
2438 ? "\"is\" with a literal. Did you mean \"==\"?"
2439 : "\"is not\" with a literal. Did you mean \"!=\"?";
2440 return compiler_warn(c, msg);
2441 }
2442 }
2443 left = right;
2444 }
2445 return 1;
2446}
2447
Mark Shannon9af0e472020-01-14 10:12:45 +00002448static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449{
Mark Shannon9af0e472020-01-14 10:12:45 +00002450 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002451 switch (op) {
2452 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002453 cmp = Py_EQ;
2454 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002455 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002456 cmp = Py_NE;
2457 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002458 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002459 cmp = Py_LT;
2460 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 cmp = Py_LE;
2463 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002464 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 cmp = Py_GT;
2466 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 cmp = Py_GE;
2469 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002471 ADDOP_I(c, IS_OP, 0);
2472 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 ADDOP_I(c, IS_OP, 1);
2475 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002477 ADDOP_I(c, CONTAINS_OP, 0);
2478 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 ADDOP_I(c, CONTAINS_OP, 1);
2481 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002484 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002485 ADDOP_I(c, COMPARE_OP, cmp);
2486 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487}
2488
Mark Shannon9af0e472020-01-14 10:12:45 +00002489
2490
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491static int
2492compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2493{
2494 switch (e->kind) {
2495 case UnaryOp_kind:
2496 if (e->v.UnaryOp.op == Not)
2497 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2498 /* fallback to general implementation */
2499 break;
2500 case BoolOp_kind: {
2501 asdl_seq *s = e->v.BoolOp.values;
2502 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2503 assert(n >= 0);
2504 int cond2 = e->v.BoolOp.op == Or;
2505 basicblock *next2 = next;
2506 if (!cond2 != !cond) {
2507 next2 = compiler_new_block(c);
2508 if (next2 == NULL)
2509 return 0;
2510 }
2511 for (i = 0; i < n; ++i) {
2512 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2513 return 0;
2514 }
2515 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2516 return 0;
2517 if (next2 != next)
2518 compiler_use_next_block(c, next2);
2519 return 1;
2520 }
2521 case IfExp_kind: {
2522 basicblock *end, *next2;
2523 end = compiler_new_block(c);
2524 if (end == NULL)
2525 return 0;
2526 next2 = compiler_new_block(c);
2527 if (next2 == NULL)
2528 return 0;
2529 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2530 return 0;
2531 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2532 return 0;
2533 ADDOP_JREL(c, JUMP_FORWARD, end);
2534 compiler_use_next_block(c, next2);
2535 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2536 return 0;
2537 compiler_use_next_block(c, end);
2538 return 1;
2539 }
2540 case Compare_kind: {
2541 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2542 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002543 if (!check_compare(c, e)) {
2544 return 0;
2545 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 basicblock *cleanup = compiler_new_block(c);
2547 if (cleanup == NULL)
2548 return 0;
2549 VISIT(c, expr, e->v.Compare.left);
2550 for (i = 0; i < n; i++) {
2551 VISIT(c, expr,
2552 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2553 ADDOP(c, DUP_TOP);
2554 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002555 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002556 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2557 NEXT_BLOCK(c);
2558 }
2559 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002560 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002561 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2562 basicblock *end = compiler_new_block(c);
2563 if (end == NULL)
2564 return 0;
2565 ADDOP_JREL(c, JUMP_FORWARD, end);
2566 compiler_use_next_block(c, cleanup);
2567 ADDOP(c, POP_TOP);
2568 if (!cond) {
2569 ADDOP_JREL(c, JUMP_FORWARD, next);
2570 }
2571 compiler_use_next_block(c, end);
2572 return 1;
2573 }
2574 /* fallback to general implementation */
2575 break;
2576 }
2577 default:
2578 /* fallback to general implementation */
2579 break;
2580 }
2581
2582 /* general implementation */
2583 VISIT(c, expr, e);
2584 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2585 return 1;
2586}
2587
2588static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002589compiler_ifexp(struct compiler *c, expr_ty e)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 basicblock *end, *next;
2592
2593 assert(e->kind == IfExp_kind);
2594 end = compiler_new_block(c);
2595 if (end == NULL)
2596 return 0;
2597 next = compiler_new_block(c);
2598 if (next == NULL)
2599 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002600 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2601 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 VISIT(c, expr, e->v.IfExp.body);
2603 ADDOP_JREL(c, JUMP_FORWARD, end);
2604 compiler_use_next_block(c, next);
2605 VISIT(c, expr, e->v.IfExp.orelse);
2606 compiler_use_next_block(c, end);
2607 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002608}
2609
2610static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611compiler_lambda(struct compiler *c, expr_ty e)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002614 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002616 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 arguments_ty args = e->v.Lambda.args;
2618 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 if (!name) {
2621 name = PyUnicode_InternFromString("<lambda>");
2622 if (!name)
2623 return 0;
2624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002626 funcflags = compiler_default_arguments(c, args);
2627 if (funcflags == -1) {
2628 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002630
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002631 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002632 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* Make None the first constant, so the lambda can't have a
2636 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002637 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002641 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2643 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2644 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002645 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
2647 else {
2648 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002649 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002651 qualname = c->u->u_qualname;
2652 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002654 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002657 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002658 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 Py_DECREF(co);
2660
2661 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662}
2663
2664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665compiler_if(struct compiler *c, stmt_ty s)
2666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 basicblock *end, *next;
2668 int constant;
2669 assert(s->kind == If_kind);
2670 end = compiler_new_block(c);
2671 if (end == NULL)
2672 return 0;
2673
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002674 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002675 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 * constant = 1: "if 1", "if 2", ...
2677 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002678 if (constant == 0) {
2679 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002681 END_DO_NOT_EMIT_BYTECODE
2682 if (s->v.If.orelse) {
2683 VISIT_SEQ(c, stmt, s->v.If.orelse);
2684 }
2685 } else if (constant == 1) {
2686 VISIT_SEQ(c, stmt, s->v.If.body);
2687 if (s->v.If.orelse) {
2688 BEGIN_DO_NOT_EMIT_BYTECODE
2689 VISIT_SEQ(c, stmt, s->v.If.orelse);
2690 END_DO_NOT_EMIT_BYTECODE
2691 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002693 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 next = compiler_new_block(c);
2695 if (next == NULL)
2696 return 0;
2697 }
Mark Shannonfee55262019-11-21 09:11:43 +00002698 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002700 }
2701 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002702 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002703 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002705 if (asdl_seq_LEN(s->v.If.orelse)) {
2706 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 compiler_use_next_block(c, next);
2708 VISIT_SEQ(c, stmt, s->v.If.orelse);
2709 }
2710 }
2711 compiler_use_next_block(c, end);
2712 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713}
2714
2715static int
2716compiler_for(struct compiler *c, stmt_ty s)
2717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 start = compiler_new_block(c);
2721 cleanup = compiler_new_block(c);
2722 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002723 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002725 }
2726 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 VISIT(c, expr, s->v.For.iter);
2730 ADDOP(c, GET_ITER);
2731 compiler_use_next_block(c, start);
2732 ADDOP_JREL(c, FOR_ITER, cleanup);
2733 VISIT(c, expr, s->v.For.target);
2734 VISIT_SEQ(c, stmt, s->v.For.body);
2735 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2736 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002737
2738 compiler_pop_fblock(c, FOR_LOOP, start);
2739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 VISIT_SEQ(c, stmt, s->v.For.orelse);
2741 compiler_use_next_block(c, end);
2742 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743}
2744
Yury Selivanov75445082015-05-11 22:57:16 -04002745
2746static int
2747compiler_async_for(struct compiler *c, stmt_ty s)
2748{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002749 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002750 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002751 c->u->u_ste->ste_coroutine = 1;
2752 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002753 return compiler_error(c, "'async for' outside async function");
2754 }
2755
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002756 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002757 except = compiler_new_block(c);
2758 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002759
Mark Shannonfee55262019-11-21 09:11:43 +00002760 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002761 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002762 }
Yury Selivanov75445082015-05-11 22:57:16 -04002763 VISIT(c, expr, s->v.AsyncFor.iter);
2764 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002765
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002767 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002768 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002769 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002770 /* SETUP_FINALLY to guard the __anext__ call */
2771 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002772 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002773 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002774 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002776
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002777 /* Success block for __anext__ */
2778 VISIT(c, expr, s->v.AsyncFor.target);
2779 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2780 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2781
2782 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002783
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002784 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002785 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002786 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002787
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002788 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002789 VISIT_SEQ(c, stmt, s->v.For.orelse);
2790
2791 compiler_use_next_block(c, end);
2792
2793 return 1;
2794}
2795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796static int
2797compiler_while(struct compiler *c, stmt_ty s)
2798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002800 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002803 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002804 // Push a dummy block so the VISIT_SEQ knows that we are
2805 // inside a while loop so it can correctly evaluate syntax
2806 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002807 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002808 return 0;
2809 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002810 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002811 // Remove the dummy block now that is not needed.
2812 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002813 END_DO_NOT_EMIT_BYTECODE
2814 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return 1;
2818 }
2819 loop = compiler_new_block(c);
2820 end = compiler_new_block(c);
2821 if (constant == -1) {
2822 anchor = compiler_new_block(c);
2823 if (anchor == NULL)
2824 return 0;
2825 }
2826 if (loop == NULL || end == NULL)
2827 return 0;
2828 if (s->v.While.orelse) {
2829 orelse = compiler_new_block(c);
2830 if (orelse == NULL)
2831 return 0;
2832 }
2833 else
2834 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002837 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 return 0;
2839 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002840 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2841 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 }
2843 VISIT_SEQ(c, stmt, s->v.While.body);
2844 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* XXX should the two POP instructions be in a separate block
2847 if there is no else clause ?
2848 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002850 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002852 compiler_pop_fblock(c, WHILE_LOOP, loop);
2853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (orelse != NULL) /* what if orelse is just pass? */
2855 VISIT_SEQ(c, stmt, s->v.While.orelse);
2856 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
2860
2861static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002864 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002865 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002866 if (c->u->u_ste->ste_type != FunctionBlock)
2867 return compiler_error(c, "'return' outside function");
2868 if (s->v.Return.value != NULL &&
2869 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2870 {
2871 return compiler_error(
2872 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002874 if (preserve_tos) {
2875 VISIT(c, expr, s->v.Return.value);
2876 }
Mark Shannonfee55262019-11-21 09:11:43 +00002877 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2878 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002880 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 }
2882 else if (!preserve_tos) {
2883 VISIT(c, expr, s->v.Return.value);
2884 }
2885 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888}
2889
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890static int
2891compiler_break(struct compiler *c)
2892{
Mark Shannonfee55262019-11-21 09:11:43 +00002893 struct fblockinfo *loop = NULL;
2894 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2895 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896 }
Mark Shannonfee55262019-11-21 09:11:43 +00002897 if (loop == NULL) {
2898 return compiler_error(c, "'break' outside loop");
2899 }
2900 if (!compiler_unwind_fblock(c, loop, 0)) {
2901 return 0;
2902 }
2903 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2904 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002905}
2906
2907static int
2908compiler_continue(struct compiler *c)
2909{
Mark Shannonfee55262019-11-21 09:11:43 +00002910 struct fblockinfo *loop = NULL;
2911 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2912 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002913 }
Mark Shannonfee55262019-11-21 09:11:43 +00002914 if (loop == NULL) {
2915 return compiler_error(c, "'continue' not properly in loop");
2916 }
2917 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2918 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002919}
2920
2921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923
2924 SETUP_FINALLY L
2925 <code for body>
2926 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002927 <code for finalbody>
2928 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002929 L:
2930 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002931 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 The special instructions use the block stack. Each block
2934 stack entry contains the instruction that created it (here
2935 SETUP_FINALLY), the level of the value stack at the time the
2936 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 Pushes the current value stack level and the label
2940 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002945 when a SETUP_FINALLY entry is found, the raised and the caught
2946 exceptions are pushed onto the value stack (and the exception
2947 condition is cleared), and the interpreter jumps to the label
2948 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949*/
2950
2951static int
2952compiler_try_finally(struct compiler *c, stmt_ty s)
2953{
Mark Shannonfee55262019-11-21 09:11:43 +00002954 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 body = compiler_new_block(c);
2957 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002958 exit = compiler_new_block(c);
2959 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002962 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 ADDOP_JREL(c, SETUP_FINALLY, end);
2964 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002965 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002967 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2968 if (!compiler_try_except(c, s))
2969 return 0;
2970 }
2971 else {
2972 VISIT_SEQ(c, stmt, s->v.Try.body);
2973 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002975 compiler_pop_fblock(c, FINALLY_TRY, body);
2976 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2977 ADDOP_JREL(c, JUMP_FORWARD, exit);
2978 /* `finally` block */
2979 compiler_use_next_block(c, end);
2980 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2981 return 0;
2982 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2983 compiler_pop_fblock(c, FINALLY_END, end);
2984 ADDOP(c, RERAISE);
2985 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987}
2988
2989/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002990 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 (The contents of the value stack is shown in [], with the top
2992 at the right; 'tb' is trace-back info, 'val' the exception's
2993 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994
2995 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002996 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 [] <code for S>
2998 [] POP_BLOCK
2999 [] JUMP_FORWARD L0
3000
3001 [tb, val, exc] L1: DUP )
3002 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003003 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 [tb, val, exc] POP
3005 [tb, val] <assign to V1> (or POP if no V1)
3006 [tb] POP
3007 [] <code for S1>
3008 JUMP_FORWARD L0
3009
3010 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011 .............................etc.......................
3012
Mark Shannonfee55262019-11-21 09:11:43 +00003013 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014
3015 [] L0: <next statement>
3016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 Of course, parts are not generated if Vi or Ei is not present.
3018*/
3019static int
3020compiler_try_except(struct compiler *c, stmt_ty s)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003023 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 body = compiler_new_block(c);
3026 except = compiler_new_block(c);
3027 orelse = compiler_new_block(c);
3028 end = compiler_new_block(c);
3029 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3030 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003031 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003033 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003035 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 ADDOP(c, POP_BLOCK);
3037 compiler_pop_fblock(c, EXCEPT, body);
3038 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 compiler_use_next_block(c, except);
3041 for (i = 0; i < n; i++) {
3042 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003043 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 if (!handler->v.ExceptHandler.type && i < n-1)
3045 return compiler_error(c, "default 'except:' must be last");
3046 c->u->u_lineno_set = 0;
3047 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003048 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 except = compiler_new_block(c);
3050 if (except == NULL)
3051 return 0;
3052 if (handler->v.ExceptHandler.type) {
3053 ADDOP(c, DUP_TOP);
3054 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003055 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 }
3057 ADDOP(c, POP_TOP);
3058 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003059 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003060
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 cleanup_end = compiler_new_block(c);
3062 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003063 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003064 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003065 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3068 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 /*
3071 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003072 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003074 try:
3075 # body
3076 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003077 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003078 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 /* second try: */
3082 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3083 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003084 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 /* second # body */
3088 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003089 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003090 ADDOP(c, POP_BLOCK);
3091 ADDOP(c, POP_EXCEPT);
3092 /* name = None; del name */
3093 ADDOP_LOAD_CONST(c, Py_None);
3094 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3095 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3096 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Mark Shannonfee55262019-11-21 09:11:43 +00003098 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003101 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003102 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003104 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105
Mark Shannonfee55262019-11-21 09:11:43 +00003106 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 }
3108 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003112 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Guido van Rossumb940e112007-01-10 16:19:56 +00003115 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003116 ADDOP(c, POP_TOP);
3117 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003118 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003121 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003122 ADDOP(c, POP_EXCEPT);
3123 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 compiler_use_next_block(c, except);
3126 }
Mark Shannonfee55262019-11-21 09:11:43 +00003127 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003129 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 compiler_use_next_block(c, end);
3131 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132}
3133
3134static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003135compiler_try(struct compiler *c, stmt_ty s) {
3136 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3137 return compiler_try_finally(c, s);
3138 else
3139 return compiler_try_except(c, s);
3140}
3141
3142
3143static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144compiler_import_as(struct compiler *c, identifier name, identifier asname)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* The IMPORT_NAME opcode was already generated. This function
3147 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003150 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003152 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3153 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003154 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003155 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003156 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003158 while (1) {
3159 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003161 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003162 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003163 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003164 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003166 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003167 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003168 if (dot == -1) {
3169 break;
3170 }
3171 ADDOP(c, ROT_TWO);
3172 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003174 if (!compiler_nameop(c, asname, Store)) {
3175 return 0;
3176 }
3177 ADDOP(c, POP_TOP);
3178 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 }
3180 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
3184compiler_import(struct compiler *c, stmt_ty s)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 /* The Import node stores a module name like a.b.c as a single
3187 string. This is convenient for all cases except
3188 import a.b.c as d
3189 where we need to parse that string to extract the individual
3190 module names.
3191 XXX Perhaps change the representation to make this case simpler?
3192 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003193 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 for (i = 0; i < n; i++) {
3196 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3197 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003199 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3200 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 if (alias->asname) {
3204 r = compiler_import_as(c, alias->name, alias->asname);
3205 if (!r)
3206 return r;
3207 }
3208 else {
3209 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003210 Py_ssize_t dot = PyUnicode_FindChar(
3211 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003212 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003213 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003214 if (tmp == NULL)
3215 return 0;
3216 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003218 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 Py_DECREF(tmp);
3220 }
3221 if (!r)
3222 return r;
3223 }
3224 }
3225 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226}
3227
3228static int
3229compiler_from_import(struct compiler *c, stmt_ty s)
3230{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003231 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003232 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 if (!empty_string) {
3236 empty_string = PyUnicode_FromString("");
3237 if (!empty_string)
3238 return 0;
3239 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003241 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003242
3243 names = PyTuple_New(n);
3244 if (!names)
3245 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 /* build up the names */
3248 for (i = 0; i < n; i++) {
3249 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3250 Py_INCREF(alias->name);
3251 PyTuple_SET_ITEM(names, i, alias->name);
3252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003255 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 Py_DECREF(names);
3257 return compiler_error(c, "from __future__ imports must occur "
3258 "at the beginning of the file");
3259 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003260 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 if (s->v.ImportFrom.module) {
3263 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3264 }
3265 else {
3266 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3267 }
3268 for (i = 0; i < n; i++) {
3269 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3270 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003272 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 assert(n == 1);
3274 ADDOP(c, IMPORT_STAR);
3275 return 1;
3276 }
3277
3278 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3279 store_name = alias->name;
3280 if (alias->asname)
3281 store_name = alias->asname;
3282
3283 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 return 0;
3285 }
3286 }
3287 /* remove imported module */
3288 ADDOP(c, POP_TOP);
3289 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290}
3291
3292static int
3293compiler_assert(struct compiler *c, stmt_ty s)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296
Georg Brandl8334fd92010-12-04 10:26:46 +00003297 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003300 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3301 {
3302 if (!compiler_warn(c, "assertion is always true, "
3303 "perhaps remove parentheses?"))
3304 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003305 return 0;
3306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 end = compiler_new_block(c);
3309 if (end == NULL)
3310 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003311 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3312 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003313 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (s->v.Assert.msg) {
3315 VISIT(c, expr, s->v.Assert.msg);
3316 ADDOP_I(c, CALL_FUNCTION, 1);
3317 }
3318 ADDOP_I(c, RAISE_VARARGS, 1);
3319 compiler_use_next_block(c, end);
3320 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321}
3322
3323static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003324compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3325{
3326 if (c->c_interactive && c->c_nestlevel <= 1) {
3327 VISIT(c, expr, value);
3328 ADDOP(c, PRINT_EXPR);
3329 return 1;
3330 }
3331
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003332 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003333 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003334 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003335 }
3336
3337 VISIT(c, expr, value);
3338 ADDOP(c, POP_TOP);
3339 return 1;
3340}
3341
3342static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343compiler_visit_stmt(struct compiler *c, stmt_ty s)
3344{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003345 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 /* Always assign a lineno to the next instruction for a stmt. */
3348 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003349 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 switch (s->kind) {
3353 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003354 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case ClassDef_kind:
3356 return compiler_class(c, s);
3357 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003358 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 case Delete_kind:
3360 VISIT_SEQ(c, expr, s->v.Delete.targets)
3361 break;
3362 case Assign_kind:
3363 n = asdl_seq_LEN(s->v.Assign.targets);
3364 VISIT(c, expr, s->v.Assign.value);
3365 for (i = 0; i < n; i++) {
3366 if (i < n - 1)
3367 ADDOP(c, DUP_TOP);
3368 VISIT(c, expr,
3369 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3370 }
3371 break;
3372 case AugAssign_kind:
3373 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003374 case AnnAssign_kind:
3375 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 case For_kind:
3377 return compiler_for(c, s);
3378 case While_kind:
3379 return compiler_while(c, s);
3380 case If_kind:
3381 return compiler_if(c, s);
3382 case Raise_kind:
3383 n = 0;
3384 if (s->v.Raise.exc) {
3385 VISIT(c, expr, s->v.Raise.exc);
3386 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003387 if (s->v.Raise.cause) {
3388 VISIT(c, expr, s->v.Raise.cause);
3389 n++;
3390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003392 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003394 case Try_kind:
3395 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 case Assert_kind:
3397 return compiler_assert(c, s);
3398 case Import_kind:
3399 return compiler_import(c, s);
3400 case ImportFrom_kind:
3401 return compiler_from_import(c, s);
3402 case Global_kind:
3403 case Nonlocal_kind:
3404 break;
3405 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003406 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 case Pass_kind:
3408 break;
3409 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003410 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 case Continue_kind:
3412 return compiler_continue(c);
3413 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003414 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003415 case AsyncFunctionDef_kind:
3416 return compiler_function(c, s, 1);
3417 case AsyncWith_kind:
3418 return compiler_async_with(c, s, 0);
3419 case AsyncFor_kind:
3420 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 }
Yury Selivanov75445082015-05-11 22:57:16 -04003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424}
3425
3426static int
3427unaryop(unaryop_ty op)
3428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 switch (op) {
3430 case Invert:
3431 return UNARY_INVERT;
3432 case Not:
3433 return UNARY_NOT;
3434 case UAdd:
3435 return UNARY_POSITIVE;
3436 case USub:
3437 return UNARY_NEGATIVE;
3438 default:
3439 PyErr_Format(PyExc_SystemError,
3440 "unary op %d should not be possible", op);
3441 return 0;
3442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
Andy Lester76d58772020-03-10 21:18:12 -05003446binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 switch (op) {
3449 case Add:
3450 return BINARY_ADD;
3451 case Sub:
3452 return BINARY_SUBTRACT;
3453 case Mult:
3454 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003455 case MatMult:
3456 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 case Div:
3458 return BINARY_TRUE_DIVIDE;
3459 case Mod:
3460 return BINARY_MODULO;
3461 case Pow:
3462 return BINARY_POWER;
3463 case LShift:
3464 return BINARY_LSHIFT;
3465 case RShift:
3466 return BINARY_RSHIFT;
3467 case BitOr:
3468 return BINARY_OR;
3469 case BitXor:
3470 return BINARY_XOR;
3471 case BitAnd:
3472 return BINARY_AND;
3473 case FloorDiv:
3474 return BINARY_FLOOR_DIVIDE;
3475 default:
3476 PyErr_Format(PyExc_SystemError,
3477 "binary op %d should not be possible", op);
3478 return 0;
3479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480}
3481
3482static int
Andy Lester76d58772020-03-10 21:18:12 -05003483inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 switch (op) {
3486 case Add:
3487 return INPLACE_ADD;
3488 case Sub:
3489 return INPLACE_SUBTRACT;
3490 case Mult:
3491 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003492 case MatMult:
3493 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 case Div:
3495 return INPLACE_TRUE_DIVIDE;
3496 case Mod:
3497 return INPLACE_MODULO;
3498 case Pow:
3499 return INPLACE_POWER;
3500 case LShift:
3501 return INPLACE_LSHIFT;
3502 case RShift:
3503 return INPLACE_RSHIFT;
3504 case BitOr:
3505 return INPLACE_OR;
3506 case BitXor:
3507 return INPLACE_XOR;
3508 case BitAnd:
3509 return INPLACE_AND;
3510 case FloorDiv:
3511 return INPLACE_FLOOR_DIVIDE;
3512 default:
3513 PyErr_Format(PyExc_SystemError,
3514 "inplace binary op %d should not be possible", op);
3515 return 0;
3516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517}
3518
3519static int
3520compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3521{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003522 int op, scope;
3523 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 PyObject *dict = c->u->u_names;
3527 PyObject *mangled;
3528 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003530 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3531 !_PyUnicode_EqualToASCIIString(name, "True") &&
3532 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003533
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003534 mangled = _Py_Mangle(c->u->u_private, name);
3535 if (!mangled)
3536 return 0;
3537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 op = 0;
3539 optype = OP_NAME;
3540 scope = PyST_GetScope(c->u->u_ste, mangled);
3541 switch (scope) {
3542 case FREE:
3543 dict = c->u->u_freevars;
3544 optype = OP_DEREF;
3545 break;
3546 case CELL:
3547 dict = c->u->u_cellvars;
3548 optype = OP_DEREF;
3549 break;
3550 case LOCAL:
3551 if (c->u->u_ste->ste_type == FunctionBlock)
3552 optype = OP_FAST;
3553 break;
3554 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003555 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 optype = OP_GLOBAL;
3557 break;
3558 case GLOBAL_EXPLICIT:
3559 optype = OP_GLOBAL;
3560 break;
3561 default:
3562 /* scope can be 0 */
3563 break;
3564 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003567 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 switch (optype) {
3570 case OP_DEREF:
3571 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003572 case Load:
3573 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3574 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003575 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003576 op = STORE_DEREF;
3577 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 case AugLoad:
3579 case AugStore:
3580 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003581 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003583 PyErr_Format(PyExc_SystemError,
3584 "expr_context kind %d should not be possible",
3585 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 return 0;
3587 }
3588 break;
3589 case OP_FAST:
3590 switch (ctx) {
3591 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003592 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003593 op = STORE_FAST;
3594 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 case Del: op = DELETE_FAST; break;
3596 case AugLoad:
3597 case AugStore:
3598 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003600 PyErr_Format(PyExc_SystemError,
3601 "expr_context kind %d should not be possible",
3602 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 return 0;
3604 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003605 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 return 1;
3607 case OP_GLOBAL:
3608 switch (ctx) {
3609 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003610 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003611 op = STORE_GLOBAL;
3612 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 case Del: op = DELETE_GLOBAL; break;
3614 case AugLoad:
3615 case AugStore:
3616 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003618 PyErr_Format(PyExc_SystemError,
3619 "expr_context kind %d should not be possible",
3620 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 return 0;
3622 }
3623 break;
3624 case OP_NAME:
3625 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003626 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003627 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003628 op = STORE_NAME;
3629 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 case Del: op = DELETE_NAME; break;
3631 case AugLoad:
3632 case AugStore:
3633 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003635 PyErr_Format(PyExc_SystemError,
3636 "expr_context kind %d should not be possible",
3637 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 return 0;
3639 }
3640 break;
3641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003644 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 Py_DECREF(mangled);
3646 if (arg < 0)
3647 return 0;
3648 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649}
3650
3651static int
3652compiler_boolop(struct compiler *c, expr_ty e)
3653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003655 int jumpi;
3656 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 assert(e->kind == BoolOp_kind);
3660 if (e->v.BoolOp.op == And)
3661 jumpi = JUMP_IF_FALSE_OR_POP;
3662 else
3663 jumpi = JUMP_IF_TRUE_OR_POP;
3664 end = compiler_new_block(c);
3665 if (end == NULL)
3666 return 0;
3667 s = e->v.BoolOp.values;
3668 n = asdl_seq_LEN(s) - 1;
3669 assert(n >= 0);
3670 for (i = 0; i < n; ++i) {
3671 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3672 ADDOP_JABS(c, jumpi, end);
3673 }
3674 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3675 compiler_use_next_block(c, end);
3676 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677}
3678
3679static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003680starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3681 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003682{
3683 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003684 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 if (n > 2 && are_all_items_const(elts, 0, n)) {
3686 PyObject *folded = PyTuple_New(n);
3687 if (folded == NULL) {
3688 return 0;
3689 }
3690 PyObject *val;
3691 for (i = 0; i < n; i++) {
3692 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3693 Py_INCREF(val);
3694 PyTuple_SET_ITEM(folded, i, val);
3695 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003696 if (tuple) {
3697 ADDOP_LOAD_CONST_NEW(c, folded);
3698 } else {
3699 if (add == SET_ADD) {
3700 Py_SETREF(folded, PyFrozenSet_New(folded));
3701 if (folded == NULL) {
3702 return 0;
3703 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003704 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003705 ADDOP_I(c, build, pushed);
3706 ADDOP_LOAD_CONST_NEW(c, folded);
3707 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003708 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003709 return 1;
3710 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003711
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003712 for (i = 0; i < n; i++) {
3713 expr_ty elt = asdl_seq_GET(elts, i);
3714 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003715 seen_star = 1;
3716 }
3717 }
3718 if (seen_star) {
3719 seen_star = 0;
3720 for (i = 0; i < n; i++) {
3721 expr_ty elt = asdl_seq_GET(elts, i);
3722 if (elt->kind == Starred_kind) {
3723 if (seen_star == 0) {
3724 ADDOP_I(c, build, i+pushed);
3725 seen_star = 1;
3726 }
3727 VISIT(c, expr, elt->v.Starred.value);
3728 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003730 else {
3731 VISIT(c, expr, elt);
3732 if (seen_star) {
3733 ADDOP_I(c, add, 1);
3734 }
3735 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003737 assert(seen_star);
3738 if (tuple) {
3739 ADDOP(c, LIST_TO_TUPLE);
3740 }
3741 }
3742 else {
3743 for (i = 0; i < n; i++) {
3744 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003745 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003746 }
3747 if (tuple) {
3748 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3749 } else {
3750 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 }
3752 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 return 1;
3754}
3755
3756static int
3757assignment_helper(struct compiler *c, asdl_seq *elts)
3758{
3759 Py_ssize_t n = asdl_seq_LEN(elts);
3760 Py_ssize_t i;
3761 int seen_star = 0;
3762 for (i = 0; i < n; i++) {
3763 expr_ty elt = asdl_seq_GET(elts, i);
3764 if (elt->kind == Starred_kind && !seen_star) {
3765 if ((i >= (1 << 8)) ||
3766 (n-i-1 >= (INT_MAX >> 8)))
3767 return compiler_error(c,
3768 "too many expressions in "
3769 "star-unpacking assignment");
3770 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3771 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003772 }
3773 else if (elt->kind == Starred_kind) {
3774 return compiler_error(c,
3775 "two starred expressions in assignment");
3776 }
3777 }
3778 if (!seen_star) {
3779 ADDOP_I(c, UNPACK_SEQUENCE, n);
3780 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003781 for (i = 0; i < n; i++) {
3782 expr_ty elt = asdl_seq_GET(elts, i);
3783 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3784 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 return 1;
3786}
3787
3788static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789compiler_list(struct compiler *c, expr_ty e)
3790{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003792 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003793 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003796 return starunpack_helper(c, elts, 0, BUILD_LIST,
3797 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 else
3800 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802}
3803
3804static int
3805compiler_tuple(struct compiler *c, expr_ty e)
3806{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003807 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003808 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 return assignment_helper(c, elts);
3810 }
3811 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003812 return starunpack_helper(c, elts, 0, BUILD_LIST,
3813 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003814 }
3815 else
3816 VISIT_SEQ(c, expr, elts);
3817 return 1;
3818}
3819
3820static int
3821compiler_set(struct compiler *c, expr_ty e)
3822{
Mark Shannon13bc1392020-01-23 09:25:17 +00003823 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3824 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003825}
3826
3827static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003828are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3829{
3830 Py_ssize_t i;
3831 for (i = begin; i < end; i++) {
3832 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003833 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003834 return 0;
3835 }
3836 return 1;
3837}
3838
3839static int
3840compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3841{
3842 Py_ssize_t i, n = end - begin;
3843 PyObject *keys, *key;
3844 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3845 for (i = begin; i < end; i++) {
3846 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3847 }
3848 keys = PyTuple_New(n);
3849 if (keys == NULL) {
3850 return 0;
3851 }
3852 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003853 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003854 Py_INCREF(key);
3855 PyTuple_SET_ITEM(keys, i - begin, key);
3856 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003857 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003858 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3859 }
3860 else {
3861 for (i = begin; i < end; i++) {
3862 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3863 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3864 }
3865 ADDOP_I(c, BUILD_MAP, n);
3866 }
3867 return 1;
3868}
3869
3870static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871compiler_dict(struct compiler *c, expr_ty e)
3872{
Victor Stinner976bb402016-03-23 11:36:19 +01003873 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003874 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003875 int is_unpacking = 0;
3876 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003877 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 elements = 0;
3879 for (i = 0; i < n; i++) {
3880 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003881 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003882 if (elements) {
3883 if (!compiler_subdict(c, e, i - elements, i)) {
3884 return 0;
3885 }
3886 if (have_dict) {
3887 ADDOP_I(c, DICT_UPDATE, 1);
3888 }
3889 have_dict = 1;
3890 elements = 0;
3891 }
3892 if (have_dict == 0) {
3893 ADDOP_I(c, BUILD_MAP, 0);
3894 have_dict = 1;
3895 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003896 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003897 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003898 }
3899 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003900 if (elements == 0xFFFF) {
3901 if (!compiler_subdict(c, e, i - elements, i)) {
3902 return 0;
3903 }
3904 if (have_dict) {
3905 ADDOP_I(c, DICT_UPDATE, 1);
3906 }
3907 have_dict = 1;
3908 elements = 0;
3909 }
3910 else {
3911 elements++;
3912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 }
3914 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003915 if (elements) {
3916 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003917 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003918 }
3919 if (have_dict) {
3920 ADDOP_I(c, DICT_UPDATE, 1);
3921 }
3922 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003923 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003924 if (!have_dict) {
3925 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 }
3927 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928}
3929
3930static int
3931compiler_compare(struct compiler *c, expr_ty e)
3932{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003933 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003935 if (!check_compare(c, e)) {
3936 return 0;
3937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003939 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3940 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3941 if (n == 0) {
3942 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003943 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003944 }
3945 else {
3946 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 if (cleanup == NULL)
3948 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003949 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 VISIT(c, expr,
3951 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003952 ADDOP(c, DUP_TOP);
3953 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003954 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003955 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3956 NEXT_BLOCK(c);
3957 }
3958 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003959 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 basicblock *end = compiler_new_block(c);
3961 if (end == NULL)
3962 return 0;
3963 ADDOP_JREL(c, JUMP_FORWARD, end);
3964 compiler_use_next_block(c, cleanup);
3965 ADDOP(c, ROT_TWO);
3966 ADDOP(c, POP_TOP);
3967 compiler_use_next_block(c, end);
3968 }
3969 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970}
3971
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003972static PyTypeObject *
3973infer_type(expr_ty e)
3974{
3975 switch (e->kind) {
3976 case Tuple_kind:
3977 return &PyTuple_Type;
3978 case List_kind:
3979 case ListComp_kind:
3980 return &PyList_Type;
3981 case Dict_kind:
3982 case DictComp_kind:
3983 return &PyDict_Type;
3984 case Set_kind:
3985 case SetComp_kind:
3986 return &PySet_Type;
3987 case GeneratorExp_kind:
3988 return &PyGen_Type;
3989 case Lambda_kind:
3990 return &PyFunction_Type;
3991 case JoinedStr_kind:
3992 case FormattedValue_kind:
3993 return &PyUnicode_Type;
3994 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003995 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003996 default:
3997 return NULL;
3998 }
3999}
4000
4001static int
4002check_caller(struct compiler *c, expr_ty e)
4003{
4004 switch (e->kind) {
4005 case Constant_kind:
4006 case Tuple_kind:
4007 case List_kind:
4008 case ListComp_kind:
4009 case Dict_kind:
4010 case DictComp_kind:
4011 case Set_kind:
4012 case SetComp_kind:
4013 case GeneratorExp_kind:
4014 case JoinedStr_kind:
4015 case FormattedValue_kind:
4016 return compiler_warn(c, "'%.200s' object is not callable; "
4017 "perhaps you missed a comma?",
4018 infer_type(e)->tp_name);
4019 default:
4020 return 1;
4021 }
4022}
4023
4024static int
4025check_subscripter(struct compiler *c, expr_ty e)
4026{
4027 PyObject *v;
4028
4029 switch (e->kind) {
4030 case Constant_kind:
4031 v = e->v.Constant.value;
4032 if (!(v == Py_None || v == Py_Ellipsis ||
4033 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4034 PyAnySet_Check(v)))
4035 {
4036 return 1;
4037 }
4038 /* fall through */
4039 case Set_kind:
4040 case SetComp_kind:
4041 case GeneratorExp_kind:
4042 case Lambda_kind:
4043 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4044 "perhaps you missed a comma?",
4045 infer_type(e)->tp_name);
4046 default:
4047 return 1;
4048 }
4049}
4050
4051static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004052check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004053{
4054 PyObject *v;
4055
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004056 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004057 if (index_type == NULL
4058 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4059 || index_type == &PySlice_Type) {
4060 return 1;
4061 }
4062
4063 switch (e->kind) {
4064 case Constant_kind:
4065 v = e->v.Constant.value;
4066 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4067 return 1;
4068 }
4069 /* fall through */
4070 case Tuple_kind:
4071 case List_kind:
4072 case ListComp_kind:
4073 case JoinedStr_kind:
4074 case FormattedValue_kind:
4075 return compiler_warn(c, "%.200s indices must be integers or slices, "
4076 "not %.200s; "
4077 "perhaps you missed a comma?",
4078 infer_type(e)->tp_name,
4079 index_type->tp_name);
4080 default:
4081 return 1;
4082 }
4083}
4084
Zackery Spytz97f5de02019-03-22 01:30:32 -06004085// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004086static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004087maybe_optimize_method_call(struct compiler *c, expr_ty e)
4088{
4089 Py_ssize_t argsl, i;
4090 expr_ty meth = e->v.Call.func;
4091 asdl_seq *args = e->v.Call.args;
4092
4093 /* Check that the call node is an attribute access, and that
4094 the call doesn't have keyword parameters. */
4095 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4096 asdl_seq_LEN(e->v.Call.keywords))
4097 return -1;
4098
4099 /* Check that there are no *varargs types of arguments. */
4100 argsl = asdl_seq_LEN(args);
4101 for (i = 0; i < argsl; i++) {
4102 expr_ty elt = asdl_seq_GET(args, i);
4103 if (elt->kind == Starred_kind) {
4104 return -1;
4105 }
4106 }
4107
4108 /* Alright, we can optimize the code. */
4109 VISIT(c, expr, meth->v.Attribute.value);
4110 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4111 VISIT_SEQ(c, expr, e->v.Call.args);
4112 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4113 return 1;
4114}
4115
4116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117compiler_call(struct compiler *c, expr_ty e)
4118{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004119 int ret = maybe_optimize_method_call(c, e);
4120 if (ret >= 0) {
4121 return ret;
4122 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004123 if (!check_caller(c, e->v.Call.func)) {
4124 return 0;
4125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 VISIT(c, expr, e->v.Call.func);
4127 return compiler_call_helper(c, 0,
4128 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004129 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004130}
4131
Eric V. Smith235a6f02015-09-19 14:51:32 -04004132static int
4133compiler_joined_str(struct compiler *c, expr_ty e)
4134{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004135 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004136 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4137 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004138 return 1;
4139}
4140
Eric V. Smitha78c7952015-11-03 12:45:05 -05004141/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004142static int
4143compiler_formatted_value(struct compiler *c, expr_ty e)
4144{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004145 /* Our oparg encodes 2 pieces of information: the conversion
4146 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004147
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004148 Convert the conversion char to 3 bits:
4149 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004150 !s : 001 0x1 FVC_STR
4151 !r : 010 0x2 FVC_REPR
4152 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153
Eric V. Smitha78c7952015-11-03 12:45:05 -05004154 next bit is whether or not we have a format spec:
4155 yes : 100 0x4
4156 no : 000 0x0
4157 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004159 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004161
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004162 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004163 VISIT(c, expr, e->v.FormattedValue.value);
4164
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004165 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004166 case 's': oparg = FVC_STR; break;
4167 case 'r': oparg = FVC_REPR; break;
4168 case 'a': oparg = FVC_ASCII; break;
4169 case -1: oparg = FVC_NONE; break;
4170 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004171 PyErr_Format(PyExc_SystemError,
4172 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004173 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004175 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004176 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004177 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004178 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004179 }
4180
Eric V. Smitha78c7952015-11-03 12:45:05 -05004181 /* And push our opcode and oparg */
4182 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004183
Eric V. Smith235a6f02015-09-19 14:51:32 -04004184 return 1;
4185}
4186
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004187static int
4188compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4189{
4190 Py_ssize_t i, n = end - begin;
4191 keyword_ty kw;
4192 PyObject *keys, *key;
4193 assert(n > 0);
4194 if (n > 1) {
4195 for (i = begin; i < end; i++) {
4196 kw = asdl_seq_GET(keywords, i);
4197 VISIT(c, expr, kw->value);
4198 }
4199 keys = PyTuple_New(n);
4200 if (keys == NULL) {
4201 return 0;
4202 }
4203 for (i = begin; i < end; i++) {
4204 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4205 Py_INCREF(key);
4206 PyTuple_SET_ITEM(keys, i - begin, key);
4207 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004208 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004209 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4210 }
4211 else {
4212 /* a for loop only executes once */
4213 for (i = begin; i < end; i++) {
4214 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004215 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004216 VISIT(c, expr, kw->value);
4217 }
4218 ADDOP_I(c, BUILD_MAP, n);
4219 }
4220 return 1;
4221}
4222
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004223/* shared code between compiler_call and compiler_class */
4224static int
4225compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004226 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004227 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004228 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004229{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004230 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004231
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004232 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004233 nkwelts = asdl_seq_LEN(keywords);
4234
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004235 for (i = 0; i < nelts; i++) {
4236 expr_ty elt = asdl_seq_GET(args, i);
4237 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004238 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004239 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004240 }
4241 for (i = 0; i < nkwelts; i++) {
4242 keyword_ty kw = asdl_seq_GET(keywords, i);
4243 if (kw->arg == NULL) {
4244 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004247
Mark Shannon13bc1392020-01-23 09:25:17 +00004248 /* No * or ** args, so can use faster calling sequence */
4249 for (i = 0; i < nelts; i++) {
4250 expr_ty elt = asdl_seq_GET(args, i);
4251 assert(elt->kind != Starred_kind);
4252 VISIT(c, expr, elt);
4253 }
4254 if (nkwelts) {
4255 PyObject *names;
4256 VISIT_SEQ(c, keyword, keywords);
4257 names = PyTuple_New(nkwelts);
4258 if (names == NULL) {
4259 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004260 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004261 for (i = 0; i < nkwelts; i++) {
4262 keyword_ty kw = asdl_seq_GET(keywords, i);
4263 Py_INCREF(kw->arg);
4264 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004265 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004266 ADDOP_LOAD_CONST_NEW(c, names);
4267 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4268 return 1;
4269 }
4270 else {
4271 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4272 return 1;
4273 }
4274
4275ex_call:
4276
4277 /* Do positional arguments. */
4278 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4279 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4280 }
4281 else if (starunpack_helper(c, args, n, BUILD_LIST,
4282 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4283 return 0;
4284 }
4285 /* Then keyword arguments */
4286 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004287 /* Has a new dict been pushed */
4288 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004289
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004290 nseen = 0; /* the number of keyword arguments on the stack following */
4291 for (i = 0; i < nkwelts; i++) {
4292 keyword_ty kw = asdl_seq_GET(keywords, i);
4293 if (kw->arg == NULL) {
4294 /* A keyword argument unpacking. */
4295 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004296 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004297 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004298 }
4299 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004300 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004301 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004302 if (!have_dict) {
4303 ADDOP_I(c, BUILD_MAP, 0);
4304 have_dict = 1;
4305 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004306 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004307 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004308 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004309 else {
4310 nseen++;
4311 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004312 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004313 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004314 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004316 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004317 }
4318 if (have_dict) {
4319 ADDOP_I(c, DICT_MERGE, 1);
4320 }
4321 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004322 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004323 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004325 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4326 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004327}
4328
Nick Coghlan650f0d02007-04-15 12:05:43 +00004329
4330/* List and set comprehensions and generator expressions work by creating a
4331 nested function to perform the actual iteration. This means that the
4332 iteration variables don't leak into the current scope.
4333 The defined function is called immediately following its definition, with the
4334 result of that call being the result of the expression.
4335 The LC/SC version returns the populated container, while the GE version is
4336 flagged in symtable.c as a generator, so it returns the generator object
4337 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004338
4339 Possible cleanups:
4340 - iterate over the generator sequence instead of using recursion
4341*/
4342
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345compiler_comprehension_generator(struct compiler *c,
4346 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004347 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004350 comprehension_ty gen;
4351 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4352 if (gen->is_async) {
4353 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004354 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355 } else {
4356 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004357 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004358 }
4359}
4360
4361static int
4362compiler_sync_comprehension_generator(struct compiler *c,
4363 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004364 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004365 expr_ty elt, expr_ty val, int type)
4366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 /* generate code for the iterator, then each of the ifs,
4368 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 comprehension_ty gen;
4371 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004372 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 start = compiler_new_block(c);
4375 skip = compiler_new_block(c);
4376 if_cleanup = compiler_new_block(c);
4377 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4380 anchor == NULL)
4381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 if (gen_index == 0) {
4386 /* Receive outermost iter as an implicit argument */
4387 c->u->u_argcount = 1;
4388 ADDOP_I(c, LOAD_FAST, 0);
4389 }
4390 else {
4391 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004392 /* Fast path for the temporary variable assignment idiom:
4393 for y in [f(x)]
4394 */
4395 asdl_seq *elts;
4396 switch (gen->iter->kind) {
4397 case List_kind:
4398 elts = gen->iter->v.List.elts;
4399 break;
4400 case Tuple_kind:
4401 elts = gen->iter->v.Tuple.elts;
4402 break;
4403 default:
4404 elts = NULL;
4405 }
4406 if (asdl_seq_LEN(elts) == 1) {
4407 expr_ty elt = asdl_seq_GET(elts, 0);
4408 if (elt->kind != Starred_kind) {
4409 VISIT(c, expr, elt);
4410 start = NULL;
4411 }
4412 }
4413 if (start) {
4414 VISIT(c, expr, gen->iter);
4415 ADDOP(c, GET_ITER);
4416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004418 if (start) {
4419 depth++;
4420 compiler_use_next_block(c, start);
4421 ADDOP_JREL(c, FOR_ITER, anchor);
4422 NEXT_BLOCK(c);
4423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 /* XXX this needs to be cleaned up...a lot! */
4427 n = asdl_seq_LEN(gen->ifs);
4428 for (i = 0; i < n; i++) {
4429 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004430 if (!compiler_jump_if(c, e, if_cleanup, 0))
4431 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 NEXT_BLOCK(c);
4433 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (++gen_index < asdl_seq_LEN(generators))
4436 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004437 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 elt, val, type))
4439 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 /* only append after the last for generator */
4442 if (gen_index >= asdl_seq_LEN(generators)) {
4443 /* comprehension specific code */
4444 switch (type) {
4445 case COMP_GENEXP:
4446 VISIT(c, expr, elt);
4447 ADDOP(c, YIELD_VALUE);
4448 ADDOP(c, POP_TOP);
4449 break;
4450 case COMP_LISTCOMP:
4451 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004452 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 break;
4454 case COMP_SETCOMP:
4455 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004456 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 break;
4458 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004459 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004462 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004463 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 break;
4465 default:
4466 return 0;
4467 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 compiler_use_next_block(c, skip);
4470 }
4471 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004472 if (start) {
4473 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4474 compiler_use_next_block(c, anchor);
4475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476
4477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004478}
4479
4480static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004481compiler_async_comprehension_generator(struct compiler *c,
4482 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004483 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 expr_ty elt, expr_ty val, int type)
4485{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004487 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004489 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004493 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494 return 0;
4495 }
4496
4497 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4498
4499 if (gen_index == 0) {
4500 /* Receive outermost iter as an implicit argument */
4501 c->u->u_argcount = 1;
4502 ADDOP_I(c, LOAD_FAST, 0);
4503 }
4504 else {
4505 /* Sub-iter - calculate on the fly */
4506 VISIT(c, expr, gen->iter);
4507 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 }
4509
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004510 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004511
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004512 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004513 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004514 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004515 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004517 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004518
4519 n = asdl_seq_LEN(gen->ifs);
4520 for (i = 0; i < n; i++) {
4521 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004522 if (!compiler_jump_if(c, e, if_cleanup, 0))
4523 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 NEXT_BLOCK(c);
4525 }
4526
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004527 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 if (++gen_index < asdl_seq_LEN(generators))
4529 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004530 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 elt, val, type))
4532 return 0;
4533
4534 /* only append after the last for generator */
4535 if (gen_index >= asdl_seq_LEN(generators)) {
4536 /* comprehension specific code */
4537 switch (type) {
4538 case COMP_GENEXP:
4539 VISIT(c, expr, elt);
4540 ADDOP(c, YIELD_VALUE);
4541 ADDOP(c, POP_TOP);
4542 break;
4543 case COMP_LISTCOMP:
4544 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004545 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 break;
4547 case COMP_SETCOMP:
4548 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004549 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 break;
4551 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004552 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004555 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004556 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 break;
4558 default:
4559 return 0;
4560 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 }
4562 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004563 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4564
4565 compiler_use_next_block(c, except);
4566 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004567
4568 return 1;
4569}
4570
4571static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004572compiler_comprehension(struct compiler *c, expr_ty e, int type,
4573 identifier name, asdl_seq *generators, expr_ty elt,
4574 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004577 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004578 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 int is_async_function = c->u->u_ste->ste_coroutine;
4580 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004581
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004582 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004583
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004584 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4585 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004586 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004588 }
4589
4590 is_async_generator = c->u->u_ste->ste_coroutine;
4591
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004592 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004593 compiler_error(c, "asynchronous comprehension outside of "
4594 "an asynchronous function");
4595 goto error_in_scope;
4596 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 if (type != COMP_GENEXP) {
4599 int op;
4600 switch (type) {
4601 case COMP_LISTCOMP:
4602 op = BUILD_LIST;
4603 break;
4604 case COMP_SETCOMP:
4605 op = BUILD_SET;
4606 break;
4607 case COMP_DICTCOMP:
4608 op = BUILD_MAP;
4609 break;
4610 default:
4611 PyErr_Format(PyExc_SystemError,
4612 "unknown comprehension type %d", type);
4613 goto error_in_scope;
4614 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 ADDOP_I(c, op, 0);
4617 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004618
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004619 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 val, type))
4621 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 if (type != COMP_GENEXP) {
4624 ADDOP(c, RETURN_VALUE);
4625 }
4626
4627 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004628 qualname = c->u->u_qualname;
4629 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004631 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 goto error;
4633
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004634 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004636 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 Py_DECREF(co);
4638
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004639 VISIT(c, expr, outermost->iter);
4640
4641 if (outermost->is_async) {
4642 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004643 } else {
4644 ADDOP(c, GET_ITER);
4645 }
4646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004648
4649 if (is_async_generator && type != COMP_GENEXP) {
4650 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004651 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004652 ADDOP(c, YIELD_FROM);
4653 }
4654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004656error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004658error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004659 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 Py_XDECREF(co);
4661 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004662}
4663
4664static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004665compiler_genexp(struct compiler *c, expr_ty e)
4666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 static identifier name;
4668 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004669 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 if (!name)
4671 return 0;
4672 }
4673 assert(e->kind == GeneratorExp_kind);
4674 return compiler_comprehension(c, e, COMP_GENEXP, name,
4675 e->v.GeneratorExp.generators,
4676 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004677}
4678
4679static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004680compiler_listcomp(struct compiler *c, expr_ty e)
4681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 static identifier name;
4683 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004684 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 if (!name)
4686 return 0;
4687 }
4688 assert(e->kind == ListComp_kind);
4689 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4690 e->v.ListComp.generators,
4691 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004692}
4693
4694static int
4695compiler_setcomp(struct compiler *c, expr_ty e)
4696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 static identifier name;
4698 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004699 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 if (!name)
4701 return 0;
4702 }
4703 assert(e->kind == SetComp_kind);
4704 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4705 e->v.SetComp.generators,
4706 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004707}
4708
4709
4710static int
4711compiler_dictcomp(struct compiler *c, expr_ty e)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 static identifier name;
4714 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004715 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!name)
4717 return 0;
4718 }
4719 assert(e->kind == DictComp_kind);
4720 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4721 e->v.DictComp.generators,
4722 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004723}
4724
4725
4726static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004727compiler_visit_keyword(struct compiler *c, keyword_ty k)
4728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 VISIT(c, expr, k->value);
4730 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004731}
4732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004734 whether they are true or false.
4735
4736 Return values: 1 for true, 0 for false, -1 for non-constant.
4737 */
4738
4739static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004740expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004741{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004742 if (e->kind == Constant_kind) {
4743 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004744 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004745 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004746}
4747
Mark Shannonfee55262019-11-21 09:11:43 +00004748static int
4749compiler_with_except_finish(struct compiler *c) {
4750 basicblock *exit;
4751 exit = compiler_new_block(c);
4752 if (exit == NULL)
4753 return 0;
4754 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4755 ADDOP(c, RERAISE);
4756 compiler_use_next_block(c, exit);
4757 ADDOP(c, POP_TOP);
4758 ADDOP(c, POP_TOP);
4759 ADDOP(c, POP_TOP);
4760 ADDOP(c, POP_EXCEPT);
4761 ADDOP(c, POP_TOP);
4762 return 1;
4763}
Yury Selivanov75445082015-05-11 22:57:16 -04004764
4765/*
4766 Implements the async with statement.
4767
4768 The semantics outlined in that PEP are as follows:
4769
4770 async with EXPR as VAR:
4771 BLOCK
4772
4773 It is implemented roughly as:
4774
4775 context = EXPR
4776 exit = context.__aexit__ # not calling it
4777 value = await context.__aenter__()
4778 try:
4779 VAR = value # if VAR present in the syntax
4780 BLOCK
4781 finally:
4782 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004783 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004784 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004785 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004786 if not (await exit(*exc)):
4787 raise
4788 */
4789static int
4790compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4791{
Mark Shannonfee55262019-11-21 09:11:43 +00004792 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004793 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4794
4795 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004796 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004797 c->u->u_ste->ste_coroutine = 1;
4798 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004799 return compiler_error(c, "'async with' outside async function");
4800 }
Yury Selivanov75445082015-05-11 22:57:16 -04004801
4802 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004803 final = compiler_new_block(c);
4804 exit = compiler_new_block(c);
4805 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004806 return 0;
4807
4808 /* Evaluate EXPR */
4809 VISIT(c, expr, item->context_expr);
4810
4811 ADDOP(c, BEFORE_ASYNC_WITH);
4812 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004813 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004814 ADDOP(c, YIELD_FROM);
4815
Mark Shannonfee55262019-11-21 09:11:43 +00004816 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004817
4818 /* SETUP_ASYNC_WITH pushes a finally block. */
4819 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004820 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004821 return 0;
4822 }
4823
4824 if (item->optional_vars) {
4825 VISIT(c, expr, item->optional_vars);
4826 }
4827 else {
4828 /* Discard result from context.__aenter__() */
4829 ADDOP(c, POP_TOP);
4830 }
4831
4832 pos++;
4833 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4834 /* BLOCK code */
4835 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4836 else if (!compiler_async_with(c, s, pos))
4837 return 0;
4838
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004839 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004840 ADDOP(c, POP_BLOCK);
4841 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004842
Mark Shannonfee55262019-11-21 09:11:43 +00004843 /* For successful outcome:
4844 * call __exit__(None, None, None)
4845 */
4846 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004847 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004848 ADDOP(c, GET_AWAITABLE);
4849 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4850 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004851
Mark Shannonfee55262019-11-21 09:11:43 +00004852 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004853
Mark Shannonfee55262019-11-21 09:11:43 +00004854 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4855
4856 /* For exceptional outcome: */
4857 compiler_use_next_block(c, final);
4858
4859 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004860 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004861 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004862 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004863 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004864
Mark Shannonfee55262019-11-21 09:11:43 +00004865compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004866 return 1;
4867}
4868
4869
Guido van Rossumc2e20742006-02-27 22:32:47 +00004870/*
4871 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004872 with EXPR as VAR:
4873 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004874 is implemented as:
4875 <code for EXPR>
4876 SETUP_WITH E
4877 <code to store to VAR> or POP_TOP
4878 <code for BLOCK>
4879 LOAD_CONST (None, None, None)
4880 CALL_FUNCTION_EX 0
4881 JUMP_FORWARD EXIT
4882 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4883 POP_JUMP_IF_TRUE T:
4884 RERAISE
4885 T: POP_TOP * 3 (remove exception from stack)
4886 POP_EXCEPT
4887 POP_TOP
4888 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004889 */
Mark Shannonfee55262019-11-21 09:11:43 +00004890
Guido van Rossumc2e20742006-02-27 22:32:47 +00004891static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004892compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004893{
Mark Shannonfee55262019-11-21 09:11:43 +00004894 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004895 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004896
4897 assert(s->kind == With_kind);
4898
Guido van Rossumc2e20742006-02-27 22:32:47 +00004899 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004900 final = compiler_new_block(c);
4901 exit = compiler_new_block(c);
4902 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004903 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004904
Thomas Wouters477c8d52006-05-27 19:21:47 +00004905 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004906 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004907 /* Will push bound __exit__ */
4908 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004909
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004910 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004912 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004913 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004914 }
4915
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004916 if (item->optional_vars) {
4917 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004918 }
4919 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004921 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004922 }
4923
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004924 pos++;
4925 if (pos == asdl_seq_LEN(s->v.With.items))
4926 /* BLOCK code */
4927 VISIT_SEQ(c, stmt, s->v.With.body)
4928 else if (!compiler_with(c, s, pos))
4929 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004930
Guido van Rossumc2e20742006-02-27 22:32:47 +00004931 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004932 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004933
Mark Shannonfee55262019-11-21 09:11:43 +00004934 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004935
Mark Shannonfee55262019-11-21 09:11:43 +00004936 /* For successful outcome:
4937 * call __exit__(None, None, None)
4938 */
4939 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004940 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004941 ADDOP(c, POP_TOP);
4942 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943
Mark Shannonfee55262019-11-21 09:11:43 +00004944 /* For exceptional outcome: */
4945 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004946
Mark Shannonfee55262019-11-21 09:11:43 +00004947 ADDOP(c, WITH_EXCEPT_START);
4948 compiler_with_except_finish(c);
4949
4950 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004951 return 1;
4952}
4953
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004954static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004955compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004958 case NamedExpr_kind:
4959 VISIT(c, expr, e->v.NamedExpr.value);
4960 ADDOP(c, DUP_TOP);
4961 VISIT(c, expr, e->v.NamedExpr.target);
4962 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 case BoolOp_kind:
4964 return compiler_boolop(c, e);
4965 case BinOp_kind:
4966 VISIT(c, expr, e->v.BinOp.left);
4967 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004968 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004969 break;
4970 case UnaryOp_kind:
4971 VISIT(c, expr, e->v.UnaryOp.operand);
4972 ADDOP(c, unaryop(e->v.UnaryOp.op));
4973 break;
4974 case Lambda_kind:
4975 return compiler_lambda(c, e);
4976 case IfExp_kind:
4977 return compiler_ifexp(c, e);
4978 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004979 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004981 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 case GeneratorExp_kind:
4983 return compiler_genexp(c, e);
4984 case ListComp_kind:
4985 return compiler_listcomp(c, e);
4986 case SetComp_kind:
4987 return compiler_setcomp(c, e);
4988 case DictComp_kind:
4989 return compiler_dictcomp(c, e);
4990 case Yield_kind:
4991 if (c->u->u_ste->ste_type != FunctionBlock)
4992 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004993 if (e->v.Yield.value) {
4994 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 }
4996 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004997 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004999 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005001 case YieldFrom_kind:
5002 if (c->u->u_ste->ste_type != FunctionBlock)
5003 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005004
5005 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5006 return compiler_error(c, "'yield from' inside async function");
5007
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005008 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005009 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005010 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005011 ADDOP(c, YIELD_FROM);
5012 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005013 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005014 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005015 if (c->u->u_ste->ste_type != FunctionBlock){
5016 return compiler_error(c, "'await' outside function");
5017 }
Yury Selivanov75445082015-05-11 22:57:16 -04005018
Victor Stinner331a6a52019-05-27 16:39:22 +02005019 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005020 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5021 return compiler_error(c, "'await' outside async function");
5022 }
5023 }
Yury Selivanov75445082015-05-11 22:57:16 -04005024
5025 VISIT(c, expr, e->v.Await.value);
5026 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005027 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005028 ADDOP(c, YIELD_FROM);
5029 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 case Compare_kind:
5031 return compiler_compare(c, e);
5032 case Call_kind:
5033 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005034 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005035 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005036 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005037 case JoinedStr_kind:
5038 return compiler_joined_str(c, e);
5039 case FormattedValue_kind:
5040 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 /* The following exprs can be assignment targets. */
5042 case Attribute_kind:
5043 if (e->v.Attribute.ctx != AugStore)
5044 VISIT(c, expr, e->v.Attribute.value);
5045 switch (e->v.Attribute.ctx) {
5046 case AugLoad:
5047 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005048 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 case Load:
5050 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5051 break;
5052 case AugStore:
5053 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005054 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 case Store:
5056 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5057 break;
5058 case Del:
5059 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5060 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03005062 PyErr_Format(PyExc_SystemError,
5063 "expr_context kind %d should not be possible",
5064 e->v.Attribute.ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 return 0;
5066 }
5067 break;
5068 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005069 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 case Starred_kind:
5071 switch (e->v.Starred.ctx) {
5072 case Store:
5073 /* In all legitimate cases, the Starred node was already replaced
5074 * by compiler_list/compiler_tuple. XXX: is that okay? */
5075 return compiler_error(c,
5076 "starred assignment target must be in a list or tuple");
5077 default:
5078 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005079 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005081 break;
5082 case Slice_kind:
5083 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 case Name_kind:
5085 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5086 /* child nodes of List and Tuple will have expr_context set */
5087 case List_kind:
5088 return compiler_list(c, e);
5089 case Tuple_kind:
5090 return compiler_tuple(c, e);
5091 }
5092 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005093}
5094
5095static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005096compiler_visit_expr(struct compiler *c, expr_ty e)
5097{
5098 /* If expr e has a different line number than the last expr/stmt,
5099 set a new line number for the next instruction.
5100 */
5101 int old_lineno = c->u->u_lineno;
5102 int old_col_offset = c->u->u_col_offset;
5103 if (e->lineno != c->u->u_lineno) {
5104 c->u->u_lineno = e->lineno;
5105 c->u->u_lineno_set = 0;
5106 }
5107 /* Updating the column offset is always harmless. */
5108 c->u->u_col_offset = e->col_offset;
5109
5110 int res = compiler_visit_expr1(c, e);
5111
5112 if (old_lineno != c->u->u_lineno) {
5113 c->u->u_lineno = old_lineno;
5114 c->u->u_lineno_set = 0;
5115 }
5116 c->u->u_col_offset = old_col_offset;
5117 return res;
5118}
5119
5120static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121compiler_augassign(struct compiler *c, stmt_ty s)
5122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 expr_ty e = s->v.AugAssign.target;
5124 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 switch (e->kind) {
5129 case Attribute_kind:
5130 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005131 AugLoad, e->lineno, e->col_offset,
5132 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 if (auge == NULL)
5134 return 0;
5135 VISIT(c, expr, auge);
5136 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005137 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 auge->v.Attribute.ctx = AugStore;
5139 VISIT(c, expr, auge);
5140 break;
5141 case Subscript_kind:
5142 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005143 AugLoad, e->lineno, e->col_offset,
5144 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 if (auge == NULL)
5146 return 0;
5147 VISIT(c, expr, auge);
5148 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005149 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 auge->v.Subscript.ctx = AugStore;
5151 VISIT(c, expr, auge);
5152 break;
5153 case Name_kind:
5154 if (!compiler_nameop(c, e->v.Name.id, Load))
5155 return 0;
5156 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005157 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 return compiler_nameop(c, e->v.Name.id, Store);
5159 default:
5160 PyErr_Format(PyExc_SystemError,
5161 "invalid node type (%d) for augmented assignment",
5162 e->kind);
5163 return 0;
5164 }
5165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005166}
5167
5168static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005169check_ann_expr(struct compiler *c, expr_ty e)
5170{
5171 VISIT(c, expr, e);
5172 ADDOP(c, POP_TOP);
5173 return 1;
5174}
5175
5176static int
5177check_annotation(struct compiler *c, stmt_ty s)
5178{
5179 /* Annotations are only evaluated in a module or class. */
5180 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5181 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5182 return check_ann_expr(c, s->v.AnnAssign.annotation);
5183 }
5184 return 1;
5185}
5186
5187static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005188check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005189{
5190 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005191 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005192 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005193 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005194 return 0;
5195 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005196 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5197 return 0;
5198 }
5199 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5200 return 0;
5201 }
5202 return 1;
5203 case Tuple_kind: {
5204 /* extended slice */
5205 asdl_seq *elts = e->v.Tuple.elts;
5206 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005207 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005208 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005209 return 0;
5210 }
5211 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005212 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005213 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005214 default:
5215 return check_ann_expr(c, e);
5216 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005217}
5218
5219static int
5220compiler_annassign(struct compiler *c, stmt_ty s)
5221{
5222 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005223 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005224
5225 assert(s->kind == AnnAssign_kind);
5226
5227 /* We perform the actual assignment first. */
5228 if (s->v.AnnAssign.value) {
5229 VISIT(c, expr, s->v.AnnAssign.value);
5230 VISIT(c, expr, targ);
5231 }
5232 switch (targ->kind) {
5233 case Name_kind:
5234 /* If we have a simple name in a module or class, store annotation. */
5235 if (s->v.AnnAssign.simple &&
5236 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5237 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005238 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5239 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5240 }
5241 else {
5242 VISIT(c, expr, s->v.AnnAssign.annotation);
5243 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005244 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005245 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005246 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005247 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005248 }
5249 break;
5250 case Attribute_kind:
5251 if (!s->v.AnnAssign.value &&
5252 !check_ann_expr(c, targ->v.Attribute.value)) {
5253 return 0;
5254 }
5255 break;
5256 case Subscript_kind:
5257 if (!s->v.AnnAssign.value &&
5258 (!check_ann_expr(c, targ->v.Subscript.value) ||
5259 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5260 return 0;
5261 }
5262 break;
5263 default:
5264 PyErr_Format(PyExc_SystemError,
5265 "invalid node type (%d) for annotated assignment",
5266 targ->kind);
5267 return 0;
5268 }
5269 /* Annotation is evaluated last. */
5270 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5271 return 0;
5272 }
5273 return 1;
5274}
5275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005276/* Raises a SyntaxError and returns 0.
5277 If something goes wrong, a different exception may be raised.
5278*/
5279
5280static int
5281compiler_error(struct compiler *c, const char *errstr)
5282{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005283 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005285
Victor Stinner14e461d2013-08-26 22:28:21 +02005286 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 if (!loc) {
5288 Py_INCREF(Py_None);
5289 loc = Py_None;
5290 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005291 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005292 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 if (!u)
5294 goto exit;
5295 v = Py_BuildValue("(zO)", errstr, u);
5296 if (!v)
5297 goto exit;
5298 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 Py_DECREF(loc);
5301 Py_XDECREF(u);
5302 Py_XDECREF(v);
5303 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005304}
5305
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005306/* Emits a SyntaxWarning and returns 1 on success.
5307 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5308 and returns 0.
5309*/
5310static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005311compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005312{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005313 va_list vargs;
5314#ifdef HAVE_STDARG_PROTOTYPES
5315 va_start(vargs, format);
5316#else
5317 va_start(vargs);
5318#endif
5319 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5320 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005321 if (msg == NULL) {
5322 return 0;
5323 }
5324 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5325 c->u->u_lineno, NULL, NULL) < 0)
5326 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005327 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005328 /* Replace the SyntaxWarning exception with a SyntaxError
5329 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005330 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005331 assert(PyUnicode_AsUTF8(msg) != NULL);
5332 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005333 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005334 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005335 return 0;
5336 }
5337 Py_DECREF(msg);
5338 return 1;
5339}
5340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005341static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005342compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005343{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005344 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005347 if (ctx == Load) {
5348 if (!check_subscripter(c, e->v.Subscript.value)) {
5349 return 0;
5350 }
5351 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5352 return 0;
5353 }
5354 }
5355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 switch (ctx) {
5357 case AugLoad: /* fall through to Load */
5358 case Load: op = BINARY_SUBSCR; break;
5359 case AugStore:/* fall through to Store */
5360 case Store: op = STORE_SUBSCR; break;
5361 case Del: op = DELETE_SUBSCR; break;
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03005362 default:
5363 PyErr_Format(PyExc_SystemError,
5364 "expr_context kind %d should not be possible",
5365 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 return 0;
5367 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005368 if (ctx == AugStore) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 ADDOP(c, ROT_THREE);
5370 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005371 else {
5372 VISIT(c, expr, e->v.Subscript.value);
5373 VISIT(c, expr, e->v.Subscript.slice);
5374 if (ctx == AugLoad) {
5375 ADDOP(c, DUP_TOP_TWO);
5376 }
5377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 ADDOP(c, op);
5379 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380}
5381
5382static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005383compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 int n = 2;
5386 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 /* only handles the cases where BUILD_SLICE is emitted */
5389 if (s->v.Slice.lower) {
5390 VISIT(c, expr, s->v.Slice.lower);
5391 }
5392 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005393 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 if (s->v.Slice.upper) {
5397 VISIT(c, expr, s->v.Slice.upper);
5398 }
5399 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005400 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 }
5402
5403 if (s->v.Slice.step) {
5404 n++;
5405 VISIT(c, expr, s->v.Slice.step);
5406 }
5407 ADDOP_I(c, BUILD_SLICE, n);
5408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409}
5410
Thomas Wouters89f507f2006-12-13 04:49:30 +00005411/* End of the compiler section, beginning of the assembler section */
5412
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005413/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005414 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005415
5416 XXX must handle implicit jumps from one block to next
5417*/
5418
Thomas Wouters89f507f2006-12-13 04:49:30 +00005419struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 PyObject *a_bytecode; /* string containing bytecode */
5421 int a_offset; /* offset into bytecode */
5422 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005423 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 PyObject *a_lnotab; /* string containing lnotab */
5425 int a_lnotab_off; /* offset into lnotab */
5426 int a_lineno; /* last lineno of emitted instruction */
5427 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005428};
5429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430static void
T. Wouters99b54d62019-09-12 07:05:33 -07005431dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005432{
T. Wouters99b54d62019-09-12 07:05:33 -07005433 int i, j;
5434
5435 /* Get rid of recursion for normal control flow.
5436 Since the number of blocks is limited, unused space in a_postorder
5437 (from a_nblocks to end) can be used as a stack for still not ordered
5438 blocks. */
5439 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005440 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005441 assert(a->a_nblocks < j);
5442 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 }
T. Wouters99b54d62019-09-12 07:05:33 -07005444 while (j < end) {
5445 b = a->a_postorder[j++];
5446 for (i = 0; i < b->b_iused; i++) {
5447 struct instr *instr = &b->b_instr[i];
5448 if (instr->i_jrel || instr->i_jabs)
5449 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005450 }
T. Wouters99b54d62019-09-12 07:05:33 -07005451 assert(a->a_nblocks < j);
5452 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005453 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005454}
5455
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005456Py_LOCAL_INLINE(void)
5457stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005459 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005460 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005461 assert(b->b_startdepth < 0);
5462 b->b_startdepth = depth;
5463 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005465}
5466
5467/* Find the flow path that needs the largest stack. We assume that
5468 * cycles in the flow graph have no net effect on the stack depth.
5469 */
5470static int
5471stackdepth(struct compiler *c)
5472{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005473 basicblock *b, *entryblock = NULL;
5474 basicblock **stack, **sp;
5475 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 b->b_startdepth = INT_MIN;
5478 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005479 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 }
5481 if (!entryblock)
5482 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005483 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5484 if (!stack) {
5485 PyErr_NoMemory();
5486 return -1;
5487 }
5488
5489 sp = stack;
5490 stackdepth_push(&sp, entryblock, 0);
5491 while (sp != stack) {
5492 b = *--sp;
5493 int depth = b->b_startdepth;
5494 assert(depth >= 0);
5495 basicblock *next = b->b_next;
5496 for (int i = 0; i < b->b_iused; i++) {
5497 struct instr *instr = &b->b_instr[i];
5498 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5499 if (effect == PY_INVALID_STACK_EFFECT) {
5500 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5501 Py_FatalError("PyCompile_OpcodeStackEffect()");
5502 }
5503 int new_depth = depth + effect;
5504 if (new_depth > maxdepth) {
5505 maxdepth = new_depth;
5506 }
5507 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5508 if (instr->i_jrel || instr->i_jabs) {
5509 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5510 assert(effect != PY_INVALID_STACK_EFFECT);
5511 int target_depth = depth + effect;
5512 if (target_depth > maxdepth) {
5513 maxdepth = target_depth;
5514 }
5515 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005516 stackdepth_push(&sp, instr->i_target, target_depth);
5517 }
5518 depth = new_depth;
5519 if (instr->i_opcode == JUMP_ABSOLUTE ||
5520 instr->i_opcode == JUMP_FORWARD ||
5521 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005522 instr->i_opcode == RAISE_VARARGS ||
5523 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005524 {
5525 /* remaining code is dead */
5526 next = NULL;
5527 break;
5528 }
5529 }
5530 if (next != NULL) {
5531 stackdepth_push(&sp, next, depth);
5532 }
5533 }
5534 PyObject_Free(stack);
5535 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536}
5537
5538static int
5539assemble_init(struct assembler *a, int nblocks, int firstlineno)
5540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 memset(a, 0, sizeof(struct assembler));
5542 a->a_lineno = firstlineno;
5543 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5544 if (!a->a_bytecode)
5545 return 0;
5546 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5547 if (!a->a_lnotab)
5548 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005549 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005550 PyErr_NoMemory();
5551 return 0;
5552 }
T. Wouters99b54d62019-09-12 07:05:33 -07005553 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005555 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 PyErr_NoMemory();
5557 return 0;
5558 }
5559 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005560}
5561
5562static void
5563assemble_free(struct assembler *a)
5564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 Py_XDECREF(a->a_bytecode);
5566 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005567 if (a->a_postorder)
5568 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005569}
5570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571static int
5572blocksize(basicblock *b)
5573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 int i;
5575 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005578 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005580}
5581
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005582/* Appends a pair to the end of the line number table, a_lnotab, representing
5583 the instruction's bytecode offset and line number. See
5584 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005585
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005586static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005587assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005589 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005590 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005592
Serhiy Storchakaab874002016-09-11 13:48:15 +03005593 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 if(d_bytecode == 0 && d_lineno == 0)
5599 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 if (d_bytecode > 255) {
5602 int j, nbytes, ncodes = d_bytecode / 255;
5603 nbytes = a->a_lnotab_off + 2 * ncodes;
5604 len = PyBytes_GET_SIZE(a->a_lnotab);
5605 if (nbytes >= len) {
5606 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5607 len = nbytes;
5608 else if (len <= INT_MAX / 2)
5609 len *= 2;
5610 else {
5611 PyErr_NoMemory();
5612 return 0;
5613 }
5614 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5615 return 0;
5616 }
5617 lnotab = (unsigned char *)
5618 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5619 for (j = 0; j < ncodes; j++) {
5620 *lnotab++ = 255;
5621 *lnotab++ = 0;
5622 }
5623 d_bytecode -= ncodes * 255;
5624 a->a_lnotab_off += ncodes * 2;
5625 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005626 assert(0 <= d_bytecode && d_bytecode <= 255);
5627
5628 if (d_lineno < -128 || 127 < d_lineno) {
5629 int j, nbytes, ncodes, k;
5630 if (d_lineno < 0) {
5631 k = -128;
5632 /* use division on positive numbers */
5633 ncodes = (-d_lineno) / 128;
5634 }
5635 else {
5636 k = 127;
5637 ncodes = d_lineno / 127;
5638 }
5639 d_lineno -= ncodes * k;
5640 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 nbytes = a->a_lnotab_off + 2 * ncodes;
5642 len = PyBytes_GET_SIZE(a->a_lnotab);
5643 if (nbytes >= len) {
5644 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5645 len = nbytes;
5646 else if (len <= INT_MAX / 2)
5647 len *= 2;
5648 else {
5649 PyErr_NoMemory();
5650 return 0;
5651 }
5652 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5653 return 0;
5654 }
5655 lnotab = (unsigned char *)
5656 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5657 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005658 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 d_bytecode = 0;
5660 for (j = 1; j < ncodes; j++) {
5661 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005662 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 a->a_lnotab_off += ncodes * 2;
5665 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005666 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 len = PyBytes_GET_SIZE(a->a_lnotab);
5669 if (a->a_lnotab_off + 2 >= len) {
5670 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5671 return 0;
5672 }
5673 lnotab = (unsigned char *)
5674 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 a->a_lnotab_off += 2;
5677 if (d_bytecode) {
5678 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005679 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 }
5681 else { /* First line of a block; def stmt, etc. */
5682 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005683 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 }
5685 a->a_lineno = i->i_lineno;
5686 a->a_lineno_off = a->a_offset;
5687 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005688}
5689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005690/* assemble_emit()
5691 Extend the bytecode with a new instruction.
5692 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005693*/
5694
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005695static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005696assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005697{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005698 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005700 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005701
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005702 arg = i->i_oparg;
5703 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 if (i->i_lineno && !assemble_lnotab(a, i))
5705 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005706 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 if (len > PY_SSIZE_T_MAX / 2)
5708 return 0;
5709 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5710 return 0;
5711 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005712 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005714 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005716}
5717
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005718static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005719assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005722 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 /* Compute the size of each block and fixup jump args.
5726 Replace block pointer with position in bytecode. */
5727 do {
5728 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005729 for (i = a->a_nblocks - 1; i >= 0; i--) {
5730 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 bsize = blocksize(b);
5732 b->b_offset = totsize;
5733 totsize += bsize;
5734 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005735 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5737 bsize = b->b_offset;
5738 for (i = 0; i < b->b_iused; i++) {
5739 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005740 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 /* Relative jumps are computed relative to
5742 the instruction pointer after fetching
5743 the jump instruction.
5744 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005745 bsize += isize;
5746 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005747 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005748 if (instr->i_jrel) {
5749 instr->i_oparg -= bsize;
5750 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005751 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005752 if (instrsize(instr->i_oparg) != isize) {
5753 extended_arg_recompile = 1;
5754 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 }
5757 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 /* XXX: This is an awful hack that could hurt performance, but
5760 on the bright side it should work until we come up
5761 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 The issue is that in the first loop blocksize() is called
5764 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005765 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 So we loop until we stop seeing new EXTENDED_ARGs.
5769 The only EXTENDED_ARGs that could be popping up are
5770 ones in jump instructions. So this should converge
5771 fairly quickly.
5772 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005773 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005774}
5775
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005776static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005777dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005780 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 tuple = PyTuple_New(size);
5783 if (tuple == NULL)
5784 return NULL;
5785 while (PyDict_Next(dict, &pos, &k, &v)) {
5786 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005787 Py_INCREF(k);
5788 assert((i - offset) < size);
5789 assert((i - offset) >= 0);
5790 PyTuple_SET_ITEM(tuple, i - offset, k);
5791 }
5792 return tuple;
5793}
5794
5795static PyObject *
5796consts_dict_keys_inorder(PyObject *dict)
5797{
5798 PyObject *consts, *k, *v;
5799 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5800
5801 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5802 if (consts == NULL)
5803 return NULL;
5804 while (PyDict_Next(dict, &pos, &k, &v)) {
5805 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005806 /* The keys of the dictionary can be tuples wrapping a contant.
5807 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5808 * the object we want is always second. */
5809 if (PyTuple_CheckExact(k)) {
5810 k = PyTuple_GET_ITEM(k, 1);
5811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005813 assert(i < size);
5814 assert(i >= 0);
5815 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005817 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005818}
5819
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005820static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005821compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005824 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005826 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 if (ste->ste_nested)
5828 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005829 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005831 if (!ste->ste_generator && ste->ste_coroutine)
5832 flags |= CO_COROUTINE;
5833 if (ste->ste_generator && ste->ste_coroutine)
5834 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 if (ste->ste_varargs)
5836 flags |= CO_VARARGS;
5837 if (ste->ste_varkeywords)
5838 flags |= CO_VARKEYWORDS;
5839 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 /* (Only) inherit compilerflags in PyCF_MASK */
5842 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005843
Pablo Galindo90235812020-03-15 04:29:22 +00005844 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005845 ste->ste_coroutine &&
5846 !ste->ste_generator) {
5847 flags |= CO_COROUTINE;
5848 }
5849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005850 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005851}
5852
INADA Naokic2e16072018-11-26 21:23:22 +09005853// Merge *tuple* with constant cache.
5854// Unlike merge_consts_recursive(), this function doesn't work recursively.
5855static int
5856merge_const_tuple(struct compiler *c, PyObject **tuple)
5857{
5858 assert(PyTuple_CheckExact(*tuple));
5859
5860 PyObject *key = _PyCode_ConstantKey(*tuple);
5861 if (key == NULL) {
5862 return 0;
5863 }
5864
5865 // t is borrowed reference
5866 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5867 Py_DECREF(key);
5868 if (t == NULL) {
5869 return 0;
5870 }
5871 if (t == key) { // tuple is new constant.
5872 return 1;
5873 }
5874
5875 PyObject *u = PyTuple_GET_ITEM(t, 1);
5876 Py_INCREF(u);
5877 Py_DECREF(*tuple);
5878 *tuple = u;
5879 return 1;
5880}
5881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005882static PyCodeObject *
5883makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 PyObject *tmp;
5886 PyCodeObject *co = NULL;
5887 PyObject *consts = NULL;
5888 PyObject *names = NULL;
5889 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 PyObject *name = NULL;
5891 PyObject *freevars = NULL;
5892 PyObject *cellvars = NULL;
5893 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005894 Py_ssize_t nlocals;
5895 int nlocals_int;
5896 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005897 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005898
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005899 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 names = dict_keys_inorder(c->u->u_names, 0);
5901 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5902 if (!consts || !names || !varnames)
5903 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005905 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5906 if (!cellvars)
5907 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005908 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 if (!freevars)
5910 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005911
INADA Naokic2e16072018-11-26 21:23:22 +09005912 if (!merge_const_tuple(c, &names) ||
5913 !merge_const_tuple(c, &varnames) ||
5914 !merge_const_tuple(c, &cellvars) ||
5915 !merge_const_tuple(c, &freevars))
5916 {
5917 goto error;
5918 }
5919
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005920 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005921 assert(nlocals < INT_MAX);
5922 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 flags = compute_code_flags(c);
5925 if (flags < 0)
5926 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5929 if (!bytecode)
5930 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5933 if (!tmp)
5934 goto error;
5935 Py_DECREF(consts);
5936 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005937 if (!merge_const_tuple(c, &consts)) {
5938 goto error;
5939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005941 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005942 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005943 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005944 maxdepth = stackdepth(c);
5945 if (maxdepth < 0) {
5946 goto error;
5947 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005948 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005949 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005950 maxdepth, flags, bytecode, consts, names,
5951 varnames, freevars, cellvars, c->c_filename,
5952 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005953 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005954 Py_XDECREF(consts);
5955 Py_XDECREF(names);
5956 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 Py_XDECREF(name);
5958 Py_XDECREF(freevars);
5959 Py_XDECREF(cellvars);
5960 Py_XDECREF(bytecode);
5961 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005962}
5963
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005964
5965/* For debugging purposes only */
5966#if 0
5967static void
5968dump_instr(const struct instr *i)
5969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005970 const char *jrel = i->i_jrel ? "jrel " : "";
5971 const char *jabs = i->i_jabs ? "jabs " : "";
5972 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005975 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005976 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5979 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005980}
5981
5982static void
5983dump_basicblock(const basicblock *b)
5984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 const char *seen = b->b_seen ? "seen " : "";
5986 const char *b_return = b->b_return ? "return " : "";
5987 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5988 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5989 if (b->b_instr) {
5990 int i;
5991 for (i = 0; i < b->b_iused; i++) {
5992 fprintf(stderr, " [%02d] ", i);
5993 dump_instr(b->b_instr + i);
5994 }
5995 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005996}
5997#endif
5998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005999static PyCodeObject *
6000assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 basicblock *b, *entryblock;
6003 struct assembler a;
6004 int i, j, nblocks;
6005 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 /* Make sure every block that falls off the end returns None.
6008 XXX NEXT_BLOCK() isn't quite right, because if the last
6009 block ends with a jump or return b_next shouldn't set.
6010 */
6011 if (!c->u->u_curblock->b_return) {
6012 NEXT_BLOCK(c);
6013 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006014 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 ADDOP(c, RETURN_VALUE);
6016 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 nblocks = 0;
6019 entryblock = NULL;
6020 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6021 nblocks++;
6022 entryblock = b;
6023 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 /* Set firstlineno if it wasn't explicitly set. */
6026 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006027 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6029 else
6030 c->u->u_firstlineno = 1;
6031 }
6032 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6033 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006034 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006036 /* Can't modify the bytecode after computing jump offsets. */
6037 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006038
T. Wouters99b54d62019-09-12 07:05:33 -07006039 /* Emit code in reverse postorder from dfs. */
6040 for (i = a.a_nblocks - 1; i >= 0; i--) {
6041 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 for (j = 0; j < b->b_iused; j++)
6043 if (!assemble_emit(&a, &b->b_instr[j]))
6044 goto error;
6045 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6048 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006049 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006050 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006052 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006053 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006054 assemble_free(&a);
6055 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006056}
Georg Brandl8334fd92010-12-04 10:26:46 +00006057
6058#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006059PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006060PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6061 PyArena *arena)
6062{
6063 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6064}