blob: 4a9b511961e5ee0e4dd34698bcfc25335de6962a [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
Ammar Askare92d3932020-01-15 11:48:40 -050026#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Pablo Galindo90235812020-03-15 04:29:22 +000043#define IS_TOP_LEVEL_AWAIT(c) ( \
44 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
45 && (c->u->u_ste->ste_type == ModuleBlock))
46
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 /* b_return is true if a RETURN_VALUE opcode is inserted. */
71 unsigned b_return : 1;
72 /* depth of stack upon entry of block, computed by stackdepth() */
73 int b_startdepth;
74 /* instruction offset for block, computed by assemble_jump_offsets() */
75 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076} basicblock;
77
78/* fblockinfo tracks the current frame block.
79
Jeremy Hyltone9357b22006-03-01 15:47:05 +000080A frame block is used to handle loops, try/except, and try/finally.
81It's called a frame block to distinguish it from a basic block in the
82compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000083*/
84
Mark Shannonfee55262019-11-21 09:11:43 +000085enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
86 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087
88struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 enum fblocktype fb_type;
90 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020091 /* (optional) type-specific exit or cleanup block */
92 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000093 /* (optional) additional information required for unwinding */
94 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095};
96
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097enum {
98 COMPILER_SCOPE_MODULE,
99 COMPILER_SCOPE_CLASS,
100 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400101 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400102 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100103 COMPILER_SCOPE_COMPREHENSION,
104};
105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106/* The following items change on entry and exit of code blocks.
107 They must be saved and restored when returning to a block.
108*/
109struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400113 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100114 int u_scope_type;
115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 /* The following fields are dicts that map objects to
117 the index of them in co_XXX. The index is used as
118 the argument for opcodes that refer to those collections.
119 */
120 PyObject *u_consts; /* all constants */
121 PyObject *u_names; /* all names */
122 PyObject *u_varnames; /* local variables */
123 PyObject *u_cellvars; /* cell variables */
124 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127
Victor Stinnerf8e32212013-11-19 23:56:34 +0100128 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100129 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100130 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 /* Pointer to the most recently allocated block. By following b_list
132 members, you can reach all early allocated blocks. */
133 basicblock *u_blocks;
134 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_nfblocks;
137 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_firstlineno; /* the first lineno of the block */
140 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000141 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142};
143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000148managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000149
150Note that we don't track recursion levels during compilation - the
151task of detecting and rejecting excessive levels of nesting is
152handled by the symbol analysis pass.
153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000154*/
155
156struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200157 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 struct symtable *c_st;
159 PyFutureFeatures *c_future; /* pointer to module's __future__ */
160 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161
Georg Brandl8334fd92010-12-04 10:26:46 +0000162 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 int c_interactive; /* true if in interactive mode */
164 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100165 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
166 if this value is different from zero.
167 This can be used to temporarily visit
168 nodes without emitting bytecode to
169 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170
INADA Naokic2e16072018-11-26 21:23:22 +0900171 PyObject *c_const_cache; /* Python dict holding all constants,
172 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 struct compiler_unit *u; /* compiler state for current block */
174 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
175 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176};
177
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100178static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static void compiler_free(struct compiler *);
180static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500181static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000182static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100183static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200186static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
188
189static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
190static int compiler_visit_stmt(struct compiler *, stmt_ty);
191static int compiler_visit_keyword(struct compiler *, keyword_ty);
192static int compiler_visit_expr(struct compiler *, expr_ty);
193static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700194static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200195static int compiler_subscript(struct compiler *, expr_ty);
196static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197
Andy Lester76d58772020-03-10 21:18:12 -0500198static int inplace_binop(operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800199static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200200static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500202static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400203static int compiler_async_with(struct compiler *, stmt_ty, int);
204static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100205static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400207 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500208static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400209static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000210
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700211static int compiler_sync_comprehension_generator(
212 struct compiler *c,
213 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200214 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700215 expr_ty elt, expr_ty val, int type);
216
217static int compiler_async_comprehension_generator(
218 struct compiler *c,
219 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200220 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700221 expr_ty elt, expr_ty val, int type);
222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000224static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400226#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 /* Name mangling: __private becomes _classname__private.
232 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200233 PyObject *result;
234 size_t nlen, plen, ipriv;
235 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200237 PyUnicode_READ_CHAR(ident, 0) != '_' ||
238 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_INCREF(ident);
240 return ident;
241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 nlen = PyUnicode_GET_LENGTH(ident);
243 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 The only time a name with a dot can occur is when
247 we are compiling an import statement that has a
248 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 TODO(jhylton): Decide whether we want to support
251 mangling of the module name, e.g. __M.X.
252 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200253 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
254 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
255 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle __whatever__ */
258 }
259 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200260 ipriv = 0;
261 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
262 ipriv++;
263 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 Py_INCREF(ident);
265 return ident; /* Don't mangle if class is just underscores */
266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000268
Antoine Pitrou55bff892013-04-06 21:21:04 +0200269 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
270 PyErr_SetString(PyExc_OverflowError,
271 "private identifier too large to be mangled");
272 return NULL;
273 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
276 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
277 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
278
279 result = PyUnicode_New(1 + nlen + plen, maxchar);
280 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
283 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200284 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
285 Py_DECREF(result);
286 return NULL;
287 }
288 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
289 Py_DECREF(result);
290 return NULL;
291 }
Victor Stinner8f825062012-04-27 13:55:39 +0200292 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200293 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000294}
295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296static int
297compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000300
INADA Naokic2e16072018-11-26 21:23:22 +0900301 c->c_const_cache = PyDict_New();
302 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900304 }
305
306 c->c_stack = PyList_New(0);
307 if (!c->c_stack) {
308 Py_CLEAR(c->c_const_cache);
309 return 0;
310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313}
314
315PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200316PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
317 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 struct compiler c;
320 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200321 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!__doc__) {
325 __doc__ = PyUnicode_InternFromString("__doc__");
326 if (!__doc__)
327 return NULL;
328 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000329 if (!__annotations__) {
330 __annotations__ = PyUnicode_InternFromString("__annotations__");
331 if (!__annotations__)
332 return NULL;
333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!compiler_init(&c))
335 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200336 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 c.c_filename = filename;
338 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200339 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (c.c_future == NULL)
341 goto finally;
342 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 flags = &local_flags;
344 }
345 merged = c.c_future->ff_features | flags->cf_flags;
346 c.c_future->ff_features = merged;
347 flags->cf_flags = merged;
348 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200349 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100351 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352
Pablo Galindod112c602020-03-18 23:02:09 +0000353 _PyASTOptimizeState state;
354 state.optimize = c.c_optimize;
355 state.ff_features = merged;
356
357 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900358 goto finally;
359 }
360
Victor Stinner14e461d2013-08-26 22:28:21 +0200361 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (c.c_st == NULL) {
363 if (!PyErr_Occurred())
364 PyErr_SetString(PyExc_SystemError, "no symtable");
365 goto finally;
366 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Thomas Wouters1175c432006-02-27 22:49:54 +0000370 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 compiler_free(&c);
372 assert(co || PyErr_Occurred());
373 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374}
375
376PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200377PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
378 int optimize, PyArena *arena)
379{
380 PyObject *filename;
381 PyCodeObject *co;
382 filename = PyUnicode_DecodeFSDefault(filename_str);
383 if (filename == NULL)
384 return NULL;
385 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
386 Py_DECREF(filename);
387 return co;
388
389}
390
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000391static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (c->c_st)
395 PySymtable_Free(c->c_st);
396 if (c->c_future)
397 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200398 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900399 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000401}
402
Guido van Rossum79f25d91997-04-29 20:08:16 +0000403static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 Py_ssize_t i, n;
407 PyObject *v, *k;
408 PyObject *dict = PyDict_New();
409 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 n = PyList_Size(list);
412 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100413 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (!v) {
415 Py_DECREF(dict);
416 return NULL;
417 }
418 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300419 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_DECREF(v);
421 Py_DECREF(dict);
422 return NULL;
423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 Py_DECREF(v);
425 }
426 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427}
428
429/* Return new dict containing names from src that match scope(s).
430
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000431src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433values are integers, starting at offset and increasing by one for
434each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435*/
436
437static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100438dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700440 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500442 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(offset >= 0);
445 if (dest == NULL)
446 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000447
Meador Inge2ca63152012-07-18 14:20:11 -0500448 /* Sort the keys so that we have a deterministic order on the indexes
449 saved in the returned dictionary. These indexes are used as indexes
450 into the free and cell var storage. Therefore if they aren't
451 deterministic, then the generated bytecode is not deterministic.
452 */
453 sorted_keys = PyDict_Keys(src);
454 if (sorted_keys == NULL)
455 return NULL;
456 if (PyList_Sort(sorted_keys) != 0) {
457 Py_DECREF(sorted_keys);
458 return NULL;
459 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500460 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500461
462 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* XXX this should probably be a macro in symtable.h */
464 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500465 k = PyList_GET_ITEM(sorted_keys, key_i);
466 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 assert(PyLong_Check(v));
468 vi = PyLong_AS_LONG(v);
469 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300472 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500474 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_DECREF(dest);
476 return NULL;
477 }
478 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300479 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500480 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_DECREF(item);
482 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
484 }
485 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 }
487 }
Meador Inge2ca63152012-07-18 14:20:11 -0500488 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000490}
491
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492static void
493compiler_unit_check(struct compiler_unit *u)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 basicblock *block;
496 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700497 assert((uintptr_t)block != 0xcbcbcbcbU);
498 assert((uintptr_t)block != 0xfbfbfbfbU);
499 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (block->b_instr != NULL) {
501 assert(block->b_ialloc > 0);
502 assert(block->b_iused > 0);
503 assert(block->b_ialloc >= block->b_iused);
504 }
505 else {
506 assert (block->b_iused == 0);
507 assert (block->b_ialloc == 0);
508 }
509 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000510}
511
512static void
513compiler_unit_free(struct compiler_unit *u)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 compiler_unit_check(u);
518 b = u->u_blocks;
519 while (b != NULL) {
520 if (b->b_instr)
521 PyObject_Free((void *)b->b_instr);
522 next = b->b_list;
523 PyObject_Free((void *)b);
524 b = next;
525 }
526 Py_CLEAR(u->u_ste);
527 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400528 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 Py_CLEAR(u->u_consts);
530 Py_CLEAR(u->u_names);
531 Py_CLEAR(u->u_varnames);
532 Py_CLEAR(u->u_freevars);
533 Py_CLEAR(u->u_cellvars);
534 Py_CLEAR(u->u_private);
535 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100539compiler_enter_scope(struct compiler *c, identifier name,
540 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100543 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
Andy Lester7668a8b2020-03-24 23:26:44 -0500545 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 struct compiler_unit));
547 if (!u) {
548 PyErr_NoMemory();
549 return 0;
550 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100551 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100553 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 u->u_kwonlyargcount = 0;
555 u->u_ste = PySymtable_Lookup(c->c_st, key);
556 if (!u->u_ste) {
557 compiler_unit_free(u);
558 return 0;
559 }
560 Py_INCREF(name);
561 u->u_name = name;
562 u->u_varnames = list2dict(u->u_ste->ste_varnames);
563 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
564 if (!u->u_varnames || !u->u_cellvars) {
565 compiler_unit_free(u);
566 return 0;
567 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000569 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500570 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300571 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 int res;
573 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200574 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 name = _PyUnicode_FromId(&PyId___class__);
576 if (!name) {
577 compiler_unit_free(u);
578 return 0;
579 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300580 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500581 if (res < 0) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200588 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!u->u_freevars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 u->u_blocks = NULL;
595 u->u_nfblocks = 0;
596 u->u_firstlineno = lineno;
597 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000598 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 u->u_consts = PyDict_New();
600 if (!u->u_consts) {
601 compiler_unit_free(u);
602 return 0;
603 }
604 u->u_names = PyDict_New();
605 if (!u->u_names) {
606 compiler_unit_free(u);
607 return 0;
608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Push the old compiler_unit on the stack. */
613 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400614 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
616 Py_XDECREF(capsule);
617 compiler_unit_free(u);
618 return 0;
619 }
620 Py_DECREF(capsule);
621 u->u_private = c->u->u_private;
622 Py_XINCREF(u->u_private);
623 }
624 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100627
628 block = compiler_new_block(c);
629 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400633 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
634 if (!compiler_set_qualname(c))
635 return 0;
636 }
637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639}
640
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000641static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642compiler_exit_scope(struct compiler *c)
643{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100644 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel--;
648 compiler_unit_free(c->u);
649 /* Restore c->u to the parent unit. */
650 n = PyList_GET_SIZE(c->c_stack) - 1;
651 if (n >= 0) {
652 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400653 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(c->u);
655 /* we are deleting from a list so this really shouldn't fail */
656 if (PySequence_DelItem(c->c_stack, n) < 0)
657 Py_FatalError("compiler_exit_scope()");
658 compiler_unit_check(c->u);
659 }
660 else
661 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663}
664
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400665static int
666compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100668 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669 _Py_static_string(dot_locals, ".<locals>");
670 Py_ssize_t stack_size;
671 struct compiler_unit *u = c->u;
672 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100673
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400674 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400676 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 if (stack_size > 1) {
678 int scope, force_global = 0;
679 struct compiler_unit *parent;
680 PyObject *mangled, *capsule;
681
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400682 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 assert(parent);
685
Yury Selivanov75445082015-05-11 22:57:16 -0400686 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
687 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
688 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 assert(u->u_name);
690 mangled = _Py_Mangle(parent->u_private, u->u_name);
691 if (!mangled)
692 return 0;
693 scope = PyST_GetScope(parent->u_ste, mangled);
694 Py_DECREF(mangled);
695 assert(scope != GLOBAL_IMPLICIT);
696 if (scope == GLOBAL_EXPLICIT)
697 force_global = 1;
698 }
699
700 if (!force_global) {
701 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400702 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
704 dot_locals_str = _PyUnicode_FromId(&dot_locals);
705 if (dot_locals_str == NULL)
706 return 0;
707 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
708 if (base == NULL)
709 return 0;
710 }
711 else {
712 Py_INCREF(parent->u_qualname);
713 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400714 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100715 }
716 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400717
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400718 if (base != NULL) {
719 dot_str = _PyUnicode_FromId(&dot);
720 if (dot_str == NULL) {
721 Py_DECREF(base);
722 return 0;
723 }
724 name = PyUnicode_Concat(base, dot_str);
725 Py_DECREF(base);
726 if (name == NULL)
727 return 0;
728 PyUnicode_Append(&name, u->u_name);
729 if (name == NULL)
730 return 0;
731 }
732 else {
733 Py_INCREF(u->u_name);
734 name = u->u_name;
735 }
736 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739}
740
Eric V. Smith235a6f02015-09-19 14:51:32 -0400741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000742/* Allocate a new block and return a pointer to it.
743 Returns NULL on error.
744*/
745
746static basicblock *
747compiler_new_block(struct compiler *c)
748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 basicblock *b;
750 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500753 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (b == NULL) {
755 PyErr_NoMemory();
756 return NULL;
757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Extend the singly linked list of blocks with new block. */
759 b->b_list = u->u_blocks;
760 u->u_blocks = b;
761 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762}
763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765compiler_next_block(struct compiler *c)
766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 basicblock *block = compiler_new_block(c);
768 if (block == NULL)
769 return NULL;
770 c->u->u_curblock->b_next = block;
771 c->u->u_curblock = block;
772 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773}
774
775static basicblock *
776compiler_use_next_block(struct compiler *c, basicblock *block)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 assert(block != NULL);
779 c->u->u_curblock->b_next = block;
780 c->u->u_curblock = block;
781 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782}
783
784/* Returns the offset of the next instruction in the current block's
785 b_instr array. Resizes the b_instr as necessary.
786 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000787*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788
789static int
Andy Lester76d58772020-03-10 21:18:12 -0500790compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(b != NULL);
793 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500794 b->b_instr = (struct instr *)PyObject_Calloc(
795 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (b->b_instr == NULL) {
797 PyErr_NoMemory();
798 return -1;
799 }
800 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 }
802 else if (b->b_iused == b->b_ialloc) {
803 struct instr *tmp;
804 size_t oldsize, newsize;
805 oldsize = b->b_ialloc * sizeof(struct instr);
806 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000807
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700808 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyErr_NoMemory();
810 return -1;
811 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (newsize == 0) {
814 PyErr_NoMemory();
815 return -1;
816 }
817 b->b_ialloc <<= 1;
818 tmp = (struct instr *)PyObject_Realloc(
819 (void *)b->b_instr, newsize);
820 if (tmp == NULL) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_instr = tmp;
825 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
826 }
827 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000828}
829
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200830/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831
Christian Heimes2202f872008-02-06 14:31:34 +0000832 The line number is reset in the following cases:
833 - when entering a new scope
834 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200835 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200836 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200839#define SET_LOC(c, x) \
840 (c)->u->u_lineno = (x)->lineno; \
841 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200843/* Return the stack effect of opcode with argument oparg.
844
845 Some opcodes have different stack effect when jump to the target and
846 when not jump. The 'jump' parameter specifies the case:
847
848 * 0 -- when not jump
849 * 1 -- when jump
850 * -1 -- maximal
851 */
852/* XXX Make the stack effect of WITH_CLEANUP_START and
853 WITH_CLEANUP_FINISH deterministic. */
854static int
855stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300858 case NOP:
859 case EXTENDED_ARG:
860 return 0;
861
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200862 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 case POP_TOP:
864 return -1;
865 case ROT_TWO:
866 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200867 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return 0;
869 case DUP_TOP:
870 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000871 case DUP_TOP_TWO:
872 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200874 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 case UNARY_POSITIVE:
876 case UNARY_NEGATIVE:
877 case UNARY_NOT:
878 case UNARY_INVERT:
879 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 case SET_ADD:
882 case LIST_APPEND:
883 return -1;
884 case MAP_ADD:
885 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000886
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200887 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 case BINARY_POWER:
889 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400890 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case BINARY_MODULO:
892 case BINARY_ADD:
893 case BINARY_SUBTRACT:
894 case BINARY_SUBSCR:
895 case BINARY_FLOOR_DIVIDE:
896 case BINARY_TRUE_DIVIDE:
897 return -1;
898 case INPLACE_FLOOR_DIVIDE:
899 case INPLACE_TRUE_DIVIDE:
900 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 case INPLACE_ADD:
903 case INPLACE_SUBTRACT:
904 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400905 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case INPLACE_MODULO:
907 return -1;
908 case STORE_SUBSCR:
909 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case DELETE_SUBSCR:
911 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 case BINARY_LSHIFT:
914 case BINARY_RSHIFT:
915 case BINARY_AND:
916 case BINARY_XOR:
917 case BINARY_OR:
918 return -1;
919 case INPLACE_POWER:
920 return -1;
921 case GET_ITER:
922 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 case PRINT_EXPR:
925 return -1;
926 case LOAD_BUILD_CLASS:
927 return 1;
928 case INPLACE_LSHIFT:
929 case INPLACE_RSHIFT:
930 case INPLACE_AND:
931 case INPLACE_XOR:
932 case INPLACE_OR:
933 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200936 /* 1 in the normal flow.
937 * Restore the stack position and push 6 values before jumping to
938 * the handler if an exception be raised. */
939 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 case RETURN_VALUE:
941 return -1;
942 case IMPORT_STAR:
943 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700944 case SETUP_ANNOTATIONS:
945 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 case YIELD_VALUE:
947 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500948 case YIELD_FROM:
949 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case POP_BLOCK:
951 return 0;
952 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200953 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case STORE_NAME:
956 return -1;
957 case DELETE_NAME:
958 return 0;
959 case UNPACK_SEQUENCE:
960 return oparg-1;
961 case UNPACK_EX:
962 return (oparg&0xFF) + (oparg>>8);
963 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200964 /* -1 at end of iterator, 1 if continue iterating. */
965 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 case STORE_ATTR:
968 return -2;
969 case DELETE_ATTR:
970 return -1;
971 case STORE_GLOBAL:
972 return -1;
973 case DELETE_GLOBAL:
974 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case LOAD_CONST:
976 return 1;
977 case LOAD_NAME:
978 return 1;
979 case BUILD_TUPLE:
980 case BUILD_LIST:
981 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300982 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return 1-oparg;
984 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700985 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300986 case BUILD_CONST_KEY_MAP:
987 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case LOAD_ATTR:
989 return 0;
990 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +0000991 case IS_OP:
992 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +0000994 case JUMP_IF_NOT_EXC_MATCH:
995 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 case IMPORT_NAME:
997 return -1;
998 case IMPORT_FROM:
999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001001 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case JUMP_ABSOLUTE:
1004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001006 case JUMP_IF_TRUE_OR_POP:
1007 case JUMP_IF_FALSE_OR_POP:
1008 return jump ? 0 : -1;
1009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 case POP_JUMP_IF_FALSE:
1011 case POP_JUMP_IF_TRUE:
1012 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case LOAD_GLOBAL:
1015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001017 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001019 /* 0 in the normal flow.
1020 * Restore the stack position and push 6 values before jumping to
1021 * the handler if an exception be raised. */
1022 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001023 case RERAISE:
1024 return -3;
1025
1026 case WITH_EXCEPT_START:
1027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case LOAD_FAST:
1030 return 1;
1031 case STORE_FAST:
1032 return -1;
1033 case DELETE_FAST:
1034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 case RAISE_VARARGS:
1037 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001038
1039 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001041 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001042 case CALL_METHOD:
1043 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001045 return -oparg-1;
1046 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001047 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001048 case MAKE_FUNCTION:
1049 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1050 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 case BUILD_SLICE:
1052 if (oparg == 3)
1053 return -2;
1054 else
1055 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001057 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_CLOSURE:
1059 return 1;
1060 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001061 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return 1;
1063 case STORE_DEREF:
1064 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001065 case DELETE_DEREF:
1066 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001067
1068 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001069 case GET_AWAITABLE:
1070 return 0;
1071 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001072 /* 0 in the normal flow.
1073 * Restore the stack position to the position before the result
1074 * of __aenter__ and push 6 values before jumping to the handler
1075 * if an exception be raised. */
1076 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001077 case BEFORE_ASYNC_WITH:
1078 return 1;
1079 case GET_AITER:
1080 return 0;
1081 case GET_ANEXT:
1082 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001083 case GET_YIELD_FROM_ITER:
1084 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001085 case END_ASYNC_FOR:
1086 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001087 case FORMAT_VALUE:
1088 /* If there's a fmt_spec on the stack, we go from 2->1,
1089 else 1->1. */
1090 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001091 case LOAD_METHOD:
1092 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001093 case LOAD_ASSERTION_ERROR:
1094 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001095 case LIST_TO_TUPLE:
1096 return 0;
1097 case LIST_EXTEND:
1098 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001099 case DICT_MERGE:
1100 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001101 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001103 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 }
Larry Hastings3a907972013-11-23 14:49:22 -08001105 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106}
1107
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001108int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001109PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1110{
1111 return stack_effect(opcode, oparg, jump);
1112}
1113
1114int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001115PyCompile_OpcodeStackEffect(int opcode, int oparg)
1116{
1117 return stack_effect(opcode, oparg, -1);
1118}
1119
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120/* Add an opcode with no argument.
1121 Returns 0 on failure, 1 on success.
1122*/
1123
1124static int
1125compiler_addop(struct compiler *c, int opcode)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 basicblock *b;
1128 struct instr *i;
1129 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001130 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001131 if (c->c_do_not_emit_bytecode) {
1132 return 1;
1133 }
Andy Lester76d58772020-03-10 21:18:12 -05001134 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (off < 0)
1136 return 0;
1137 b = c->u->u_curblock;
1138 i = &b->b_instr[off];
1139 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001140 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (opcode == RETURN_VALUE)
1142 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001143 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145}
1146
Victor Stinnerf8e32212013-11-19 23:56:34 +01001147static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001148compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001150 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001153 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001155 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001157 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001158 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001159 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return -1;
1162 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001163 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 Py_DECREF(v);
1165 return -1;
1166 }
1167 Py_DECREF(v);
1168 }
1169 else
1170 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 return arg;
1172}
1173
INADA Naokic2e16072018-11-26 21:23:22 +09001174// Merge const *o* recursively and return constant key object.
1175static PyObject*
1176merge_consts_recursive(struct compiler *c, PyObject *o)
1177{
1178 // None and Ellipsis are singleton, and key is the singleton.
1179 // No need to merge object and key.
1180 if (o == Py_None || o == Py_Ellipsis) {
1181 Py_INCREF(o);
1182 return o;
1183 }
1184
1185 PyObject *key = _PyCode_ConstantKey(o);
1186 if (key == NULL) {
1187 return NULL;
1188 }
1189
1190 // t is borrowed reference
1191 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1192 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001193 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001194 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001195 Py_DECREF(key);
1196 return t;
1197 }
1198
INADA Naokif7e4d362018-11-29 00:58:46 +09001199 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001200 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001201 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001202 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001203 Py_ssize_t len = PyTuple_GET_SIZE(o);
1204 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001205 PyObject *item = PyTuple_GET_ITEM(o, i);
1206 PyObject *u = merge_consts_recursive(c, item);
1207 if (u == NULL) {
1208 Py_DECREF(key);
1209 return NULL;
1210 }
1211
1212 // See _PyCode_ConstantKey()
1213 PyObject *v; // borrowed
1214 if (PyTuple_CheckExact(u)) {
1215 v = PyTuple_GET_ITEM(u, 1);
1216 }
1217 else {
1218 v = u;
1219 }
1220 if (v != item) {
1221 Py_INCREF(v);
1222 PyTuple_SET_ITEM(o, i, v);
1223 Py_DECREF(item);
1224 }
1225
1226 Py_DECREF(u);
1227 }
1228 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001229 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001230 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 // constant keys.
1232 // See _PyCode_ConstantKey() for detail.
1233 assert(PyTuple_CheckExact(key));
1234 assert(PyTuple_GET_SIZE(key) == 2);
1235
1236 Py_ssize_t len = PySet_GET_SIZE(o);
1237 if (len == 0) { // empty frozenset should not be re-created.
1238 return key;
1239 }
1240 PyObject *tuple = PyTuple_New(len);
1241 if (tuple == NULL) {
1242 Py_DECREF(key);
1243 return NULL;
1244 }
1245 Py_ssize_t i = 0, pos = 0;
1246 PyObject *item;
1247 Py_hash_t hash;
1248 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1249 PyObject *k = merge_consts_recursive(c, item);
1250 if (k == NULL) {
1251 Py_DECREF(tuple);
1252 Py_DECREF(key);
1253 return NULL;
1254 }
1255 PyObject *u;
1256 if (PyTuple_CheckExact(k)) {
1257 u = PyTuple_GET_ITEM(k, 1);
1258 Py_INCREF(u);
1259 Py_DECREF(k);
1260 }
1261 else {
1262 u = k;
1263 }
1264 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1265 i++;
1266 }
1267
1268 // Instead of rewriting o, we create new frozenset and embed in the
1269 // key tuple. Caller should get merged frozenset from the key tuple.
1270 PyObject *new = PyFrozenSet_New(tuple);
1271 Py_DECREF(tuple);
1272 if (new == NULL) {
1273 Py_DECREF(key);
1274 return NULL;
1275 }
1276 assert(PyTuple_GET_ITEM(key, 1) == o);
1277 Py_DECREF(o);
1278 PyTuple_SET_ITEM(key, 1, new);
1279 }
INADA Naokic2e16072018-11-26 21:23:22 +09001280
1281 return key;
1282}
1283
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001284static Py_ssize_t
1285compiler_add_const(struct compiler *c, PyObject *o)
1286{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001287 if (c->c_do_not_emit_bytecode) {
1288 return 0;
1289 }
1290
INADA Naokic2e16072018-11-26 21:23:22 +09001291 PyObject *key = merge_consts_recursive(c, o);
1292 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001293 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001294 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001295
Andy Lester76d58772020-03-10 21:18:12 -05001296 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001297 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299}
1300
1301static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001302compiler_addop_load_const(struct compiler *c, PyObject *o)
1303{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001304 if (c->c_do_not_emit_bytecode) {
1305 return 1;
1306 }
1307
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001308 Py_ssize_t arg = compiler_add_const(c, o);
1309 if (arg < 0)
1310 return 0;
1311 return compiler_addop_i(c, LOAD_CONST, arg);
1312}
1313
1314static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001318 if (c->c_do_not_emit_bytecode) {
1319 return 1;
1320 }
1321
Andy Lester76d58772020-03-10 21:18:12 -05001322 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325 return compiler_addop_i(c, opcode, arg);
1326}
1327
1328static int
1329compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001332 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001333
1334 if (c->c_do_not_emit_bytecode) {
1335 return 1;
1336 }
1337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1339 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001340 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001341 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 Py_DECREF(mangled);
1343 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001344 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 return compiler_addop_i(c, opcode, arg);
1346}
1347
1348/* Add an opcode with an integer argument.
1349 Returns 0 on failure, 1 on success.
1350*/
1351
1352static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001353compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 struct instr *i;
1356 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001357
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001358 if (c->c_do_not_emit_bytecode) {
1359 return 1;
1360 }
1361
Victor Stinner2ad474b2016-03-01 23:34:47 +01001362 /* oparg value is unsigned, but a signed C int is usually used to store
1363 it in the C code (like Python/ceval.c).
1364
1365 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1366
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001367 The argument of a concrete bytecode instruction is limited to 8-bit.
1368 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1369 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001370 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001371
Andy Lester76d58772020-03-10 21:18:12 -05001372 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (off < 0)
1374 return 0;
1375 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001376 i->i_opcode = opcode;
1377 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001378 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380}
1381
1382static int
1383compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 struct instr *i;
1386 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001388 if (c->c_do_not_emit_bytecode) {
1389 return 1;
1390 }
1391
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001392 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001394 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (off < 0)
1396 return 0;
1397 i = &c->u->u_curblock->b_instr[off];
1398 i->i_opcode = opcode;
1399 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (absolute)
1401 i->i_jabs = 1;
1402 else
1403 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001404 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406}
1407
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001408/* NEXT_BLOCK() creates an implicit jump from the current block
1409 to the new block.
1410
1411 The returns inside this macro make it impossible to decref objects
1412 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (compiler_next_block((C)) == NULL) \
1416 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417}
1418
1419#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 if (!compiler_addop((C), (OP))) \
1421 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422}
1423
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001424#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 if (!compiler_addop((C), (OP))) { \
1426 compiler_exit_scope(c); \
1427 return 0; \
1428 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001429}
1430
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001431#define ADDOP_LOAD_CONST(C, O) { \
1432 if (!compiler_addop_load_const((C), (O))) \
1433 return 0; \
1434}
1435
1436/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1437#define ADDOP_LOAD_CONST_NEW(C, O) { \
1438 PyObject *__new_const = (O); \
1439 if (__new_const == NULL) { \
1440 return 0; \
1441 } \
1442 if (!compiler_addop_load_const((C), __new_const)) { \
1443 Py_DECREF(__new_const); \
1444 return 0; \
1445 } \
1446 Py_DECREF(__new_const); \
1447}
1448
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1451 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452}
1453
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001454/* Same as ADDOP_O, but steals a reference. */
1455#define ADDOP_N(C, OP, O, TYPE) { \
1456 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1457 Py_DECREF((O)); \
1458 return 0; \
1459 } \
1460 Py_DECREF((O)); \
1461}
1462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1465 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466}
1467
1468#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (!compiler_addop_i((C), (OP), (O))) \
1470 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
1473#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (!compiler_addop_j((C), (OP), (O), 1)) \
1475 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476}
1477
1478#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (!compiler_addop_j((C), (OP), (O), 0)) \
1480 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481}
1482
Mark Shannon9af0e472020-01-14 10:12:45 +00001483
1484#define ADDOP_COMPARE(C, CMP) { \
1485 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1486 return 0; \
1487}
1488
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1490 the ASDL name to synthesize the name of the C type and the visit function.
1491*/
1492
1493#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!compiler_visit_ ## TYPE((C), (V))) \
1495 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001498#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_visit_ ## TYPE((C), (V))) { \
1500 compiler_exit_scope(c); \
1501 return 0; \
1502 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001503}
1504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_visit_slice((C), (V), (CTX))) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
1510#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 int _i; \
1512 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1513 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1514 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1515 if (!compiler_visit_ ## TYPE((C), elt)) \
1516 return 0; \
1517 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518}
1519
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001520#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 int _i; \
1522 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1523 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1524 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1525 if (!compiler_visit_ ## TYPE((C), elt)) { \
1526 compiler_exit_scope(c); \
1527 return 0; \
1528 } \
1529 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001530}
1531
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001532/* These macros allows to check only for errors and not emmit bytecode
1533 * while visiting nodes.
1534*/
1535
1536#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1537 c->c_do_not_emit_bytecode++;
1538
1539#define END_DO_NOT_EMIT_BYTECODE \
1540 c->c_do_not_emit_bytecode--; \
1541}
1542
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001543/* Search if variable annotations are present statically in a block. */
1544
1545static int
1546find_ann(asdl_seq *stmts)
1547{
1548 int i, j, res = 0;
1549 stmt_ty st;
1550
1551 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1552 st = (stmt_ty)asdl_seq_GET(stmts, i);
1553 switch (st->kind) {
1554 case AnnAssign_kind:
1555 return 1;
1556 case For_kind:
1557 res = find_ann(st->v.For.body) ||
1558 find_ann(st->v.For.orelse);
1559 break;
1560 case AsyncFor_kind:
1561 res = find_ann(st->v.AsyncFor.body) ||
1562 find_ann(st->v.AsyncFor.orelse);
1563 break;
1564 case While_kind:
1565 res = find_ann(st->v.While.body) ||
1566 find_ann(st->v.While.orelse);
1567 break;
1568 case If_kind:
1569 res = find_ann(st->v.If.body) ||
1570 find_ann(st->v.If.orelse);
1571 break;
1572 case With_kind:
1573 res = find_ann(st->v.With.body);
1574 break;
1575 case AsyncWith_kind:
1576 res = find_ann(st->v.AsyncWith.body);
1577 break;
1578 case Try_kind:
1579 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1580 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1581 st->v.Try.handlers, j);
1582 if (find_ann(handler->v.ExceptHandler.body)) {
1583 return 1;
1584 }
1585 }
1586 res = find_ann(st->v.Try.body) ||
1587 find_ann(st->v.Try.finalbody) ||
1588 find_ann(st->v.Try.orelse);
1589 break;
1590 default:
1591 res = 0;
1592 }
1593 if (res) {
1594 break;
1595 }
1596 }
1597 return res;
1598}
1599
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001600/*
1601 * Frame block handling functions
1602 */
1603
1604static int
1605compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001606 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001607{
1608 struct fblockinfo *f;
1609 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1610 PyErr_SetString(PyExc_SyntaxError,
1611 "too many statically nested blocks");
1612 return 0;
1613 }
1614 f = &c->u->u_fblock[c->u->u_nfblocks++];
1615 f->fb_type = t;
1616 f->fb_block = b;
1617 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001618 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001619 return 1;
1620}
1621
1622static void
1623compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1624{
1625 struct compiler_unit *u = c->u;
1626 assert(u->u_nfblocks > 0);
1627 u->u_nfblocks--;
1628 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1629 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1630}
1631
Mark Shannonfee55262019-11-21 09:11:43 +00001632static int
1633compiler_call_exit_with_nones(struct compiler *c) {
1634 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1635 ADDOP(c, DUP_TOP);
1636 ADDOP(c, DUP_TOP);
1637 ADDOP_I(c, CALL_FUNCTION, 3);
1638 return 1;
1639}
1640
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001641/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001642 * popping the blocks will be restored afterwards, unless another
1643 * return, break or continue is found. In which case, the TOS will
1644 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001645 */
1646static int
1647compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1648 int preserve_tos)
1649{
1650 switch (info->fb_type) {
1651 case WHILE_LOOP:
1652 return 1;
1653
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001654 case FOR_LOOP:
1655 /* Pop the iterator */
1656 if (preserve_tos) {
1657 ADDOP(c, ROT_TWO);
1658 }
1659 ADDOP(c, POP_TOP);
1660 return 1;
1661
1662 case EXCEPT:
1663 ADDOP(c, POP_BLOCK);
1664 return 1;
1665
1666 case FINALLY_TRY:
1667 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001668 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001669 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1670 return 0;
1671 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001672 }
Mark Shannon88dce262019-12-30 09:53:36 +00001673 /* Emit the finally block, restoring the line number when done */
1674 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001675 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001676 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001677 if (preserve_tos) {
1678 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001679 }
1680 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001681
Mark Shannonfee55262019-11-21 09:11:43 +00001682 case FINALLY_END:
1683 if (preserve_tos) {
1684 ADDOP(c, ROT_FOUR);
1685 }
1686 ADDOP(c, POP_TOP);
1687 ADDOP(c, POP_TOP);
1688 ADDOP(c, POP_TOP);
1689 if (preserve_tos) {
1690 ADDOP(c, ROT_FOUR);
1691 }
1692 ADDOP(c, POP_EXCEPT);
1693 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001694
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001695 case WITH:
1696 case ASYNC_WITH:
1697 ADDOP(c, POP_BLOCK);
1698 if (preserve_tos) {
1699 ADDOP(c, ROT_TWO);
1700 }
Mark Shannonfee55262019-11-21 09:11:43 +00001701 if(!compiler_call_exit_with_nones(c)) {
1702 return 0;
1703 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001704 if (info->fb_type == ASYNC_WITH) {
1705 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001706 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 ADDOP(c, YIELD_FROM);
1708 }
Mark Shannonfee55262019-11-21 09:11:43 +00001709 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001710 return 1;
1711
1712 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001713 if (info->fb_datum) {
1714 ADDOP(c, POP_BLOCK);
1715 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001716 if (preserve_tos) {
1717 ADDOP(c, ROT_FOUR);
1718 }
Mark Shannonfee55262019-11-21 09:11:43 +00001719 ADDOP(c, POP_EXCEPT);
1720 if (info->fb_datum) {
1721 ADDOP_LOAD_CONST(c, Py_None);
1722 compiler_nameop(c, info->fb_datum, Store);
1723 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 }
Mark Shannonfee55262019-11-21 09:11:43 +00001725 return 1;
1726
1727 case POP_VALUE:
1728 if (preserve_tos) {
1729 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001730 }
Mark Shannonfee55262019-11-21 09:11:43 +00001731 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001732 return 1;
1733 }
1734 Py_UNREACHABLE();
1735}
1736
Mark Shannonfee55262019-11-21 09:11:43 +00001737/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1738static int
1739compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1740 if (c->u->u_nfblocks == 0) {
1741 return 1;
1742 }
1743 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1744 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1745 *loop = top;
1746 return 1;
1747 }
1748 struct fblockinfo copy = *top;
1749 c->u->u_nfblocks--;
1750 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1751 return 0;
1752 }
1753 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1754 return 0;
1755 }
1756 c->u->u_fblock[c->u->u_nfblocks] = copy;
1757 c->u->u_nfblocks++;
1758 return 1;
1759}
1760
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001761/* Compile a sequence of statements, checking for a docstring
1762 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763
1764static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001765compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001767 int i = 0;
1768 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001769 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001770
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001771 /* Set current line number to the line number of first statement.
1772 This way line number for SETUP_ANNOTATIONS will always
1773 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301774 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001775 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001776 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001777 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001778 }
1779 /* Every annotated class and module should have __annotations__. */
1780 if (find_ann(stmts)) {
1781 ADDOP(c, SETUP_ANNOTATIONS);
1782 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001783 if (!asdl_seq_LEN(stmts))
1784 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001785 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001786 if (c->c_optimize < 2) {
1787 docstring = _PyAST_GetDocString(stmts);
1788 if (docstring) {
1789 i = 1;
1790 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1791 assert(st->kind == Expr_kind);
1792 VISIT(c, expr, st->v.Expr.value);
1793 if (!compiler_nameop(c, __doc__, Store))
1794 return 0;
1795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001797 for (; i < asdl_seq_LEN(stmts); i++)
1798 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800}
1801
1802static PyCodeObject *
1803compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyCodeObject *co;
1806 int addNone = 1;
1807 static PyObject *module;
1808 if (!module) {
1809 module = PyUnicode_InternFromString("<module>");
1810 if (!module)
1811 return NULL;
1812 }
1813 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001814 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 return NULL;
1816 switch (mod->kind) {
1817 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001818 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 compiler_exit_scope(c);
1820 return 0;
1821 }
1822 break;
1823 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001824 if (find_ann(mod->v.Interactive.body)) {
1825 ADDOP(c, SETUP_ANNOTATIONS);
1826 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 c->c_interactive = 1;
1828 VISIT_SEQ_IN_SCOPE(c, stmt,
1829 mod->v.Interactive.body);
1830 break;
1831 case Expression_kind:
1832 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1833 addNone = 0;
1834 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 default:
1836 PyErr_Format(PyExc_SystemError,
1837 "module kind %d should not be possible",
1838 mod->kind);
1839 return 0;
1840 }
1841 co = assemble(c, addNone);
1842 compiler_exit_scope(c);
1843 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001844}
1845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846/* The test for LOCAL must come before the test for FREE in order to
1847 handle classes where name is both local and free. The local var is
1848 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001849*/
1850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851static int
1852get_ref_type(struct compiler *c, PyObject *name)
1853{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001854 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001855 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001856 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001857 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001858 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001860 _Py_FatalErrorFormat(__func__,
1861 "unknown scope for %.100s in %.100s(%s)\n"
1862 "symbols: %s\nlocals: %s\nglobals: %s",
1863 PyUnicode_AsUTF8(name),
1864 PyUnicode_AsUTF8(c->u->u_name),
1865 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1866 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1867 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1868 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872}
1873
1874static int
1875compiler_lookup_arg(PyObject *dict, PyObject *name)
1876{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001877 PyObject *v;
1878 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001880 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001881 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882}
1883
1884static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001887 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001888 if (qualname == NULL)
1889 qualname = co->co_name;
1890
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001891 if (free) {
1892 for (i = 0; i < free; ++i) {
1893 /* Bypass com_addop_varname because it will generate
1894 LOAD_DEREF but LOAD_CLOSURE is needed.
1895 */
1896 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1897 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001899 /* Special case: If a class contains a method with a
1900 free variable that has the same name as a method,
1901 the name will be considered free *and* local in the
1902 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001903 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001904 */
1905 reftype = get_ref_type(c, name);
1906 if (reftype == CELL)
1907 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1908 else /* (reftype == FREE) */
1909 arg = compiler_lookup_arg(c->u->u_freevars, name);
1910 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001911 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001912 "lookup %s in %s %d %d\n"
1913 "freevars of %s: %s\n",
1914 PyUnicode_AsUTF8(PyObject_Repr(name)),
1915 PyUnicode_AsUTF8(c->u->u_name),
1916 reftype, arg,
1917 PyUnicode_AsUTF8(co->co_name),
1918 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001919 }
1920 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922 flags |= 0x08;
1923 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001925 ADDOP_LOAD_CONST(c, (PyObject*)co);
1926 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001927 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929}
1930
1931static int
1932compiler_decorators(struct compiler *c, asdl_seq* decos)
1933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!decos)
1937 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1940 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1941 }
1942 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943}
1944
1945static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001946compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001948{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001949 /* Push a dict of keyword-only default values.
1950
1951 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1952 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 int i;
1954 PyObject *keys = NULL;
1955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1957 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1958 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1959 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001960 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001961 if (!mangled) {
1962 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 if (keys == NULL) {
1965 keys = PyList_New(1);
1966 if (keys == NULL) {
1967 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001968 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001969 }
1970 PyList_SET_ITEM(keys, 0, mangled);
1971 }
1972 else {
1973 int res = PyList_Append(keys, mangled);
1974 Py_DECREF(mangled);
1975 if (res == -1) {
1976 goto error;
1977 }
1978 }
1979 if (!compiler_visit_expr(c, default_)) {
1980 goto error;
1981 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
1983 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001984 if (keys != NULL) {
1985 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1986 PyObject *keys_tuple = PyList_AsTuple(keys);
1987 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001988 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001989 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 assert(default_count > 0);
1991 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001992 }
1993 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001994 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001995 }
1996
1997error:
1998 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001999 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002000}
2001
2002static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002003compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2004{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002005 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002006 return 1;
2007}
2008
2009static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002010compiler_visit_argannotation(struct compiler *c, identifier id,
2011 expr_ty annotation, PyObject *names)
2012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002014 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002015 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2016 VISIT(c, annexpr, annotation)
2017 }
2018 else {
2019 VISIT(c, expr, annotation);
2020 }
Victor Stinner065efc32014-02-18 22:07:56 +01002021 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002022 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002023 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002024 if (PyList_Append(names, mangled) < 0) {
2025 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002026 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002027 }
2028 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002030 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002031}
2032
2033static int
2034compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2035 PyObject *names)
2036{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002037 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 for (i = 0; i < asdl_seq_LEN(args); i++) {
2039 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002040 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 c,
2042 arg->arg,
2043 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002044 names))
2045 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002047 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002048}
2049
2050static int
2051compiler_visit_annotations(struct compiler *c, arguments_ty args,
2052 expr_ty returns)
2053{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002054 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002055 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002056
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002057 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 */
2059 static identifier return_str;
2060 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002061 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 names = PyList_New(0);
2063 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002064 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002065
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002068 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2069 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002070 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002072 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002076 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002077 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002078 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (!return_str) {
2082 return_str = PyUnicode_InternFromString("return");
2083 if (!return_str)
2084 goto error;
2085 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002086 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 goto error;
2088 }
2089
2090 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002092 PyObject *keytuple = PyList_AsTuple(names);
2093 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002094 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002095 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002096 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002098 else {
2099 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002100 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002101 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
2103error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002105 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002106}
2107
2108static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002109compiler_visit_defaults(struct compiler *c, arguments_ty args)
2110{
2111 VISIT_SEQ(c, expr, args->defaults);
2112 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2113 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114}
2115
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002116static Py_ssize_t
2117compiler_default_arguments(struct compiler *c, arguments_ty args)
2118{
2119 Py_ssize_t funcflags = 0;
2120 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002121 if (!compiler_visit_defaults(c, args))
2122 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002123 funcflags |= 0x01;
2124 }
2125 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002126 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002127 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002128 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002129 return -1;
2130 }
2131 else if (res > 0) {
2132 funcflags |= 0x02;
2133 }
2134 }
2135 return funcflags;
2136}
2137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002139forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2140{
2141
2142 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2143 compiler_error(c, "cannot assign to __debug__");
2144 return 1;
2145 }
2146 return 0;
2147}
2148
2149static int
2150compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2151{
2152 if (arg != NULL) {
2153 if (forbidden_name(c, arg->arg, Store))
2154 return 0;
2155 }
2156 return 1;
2157}
2158
2159static int
2160compiler_check_debug_args_seq(struct compiler *c, asdl_seq *args)
2161{
2162 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002163 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002164 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2165 return 0;
2166 }
2167 }
2168 return 1;
2169}
2170
2171static int
2172compiler_check_debug_args(struct compiler *c, arguments_ty args)
2173{
2174 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2175 return 0;
2176 if (!compiler_check_debug_args_seq(c, args->args))
2177 return 0;
2178 if (!compiler_check_debug_one_arg(c, args->vararg))
2179 return 0;
2180 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2181 return 0;
2182 if (!compiler_check_debug_one_arg(c, args->kwarg))
2183 return 0;
2184 return 1;
2185}
2186
2187static int
Yury Selivanov75445082015-05-11 22:57:16 -04002188compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002191 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002192 arguments_ty args;
2193 expr_ty returns;
2194 identifier name;
2195 asdl_seq* decos;
2196 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002197 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002198 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002199 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002200 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201
Yury Selivanov75445082015-05-11 22:57:16 -04002202 if (is_async) {
2203 assert(s->kind == AsyncFunctionDef_kind);
2204
2205 args = s->v.AsyncFunctionDef.args;
2206 returns = s->v.AsyncFunctionDef.returns;
2207 decos = s->v.AsyncFunctionDef.decorator_list;
2208 name = s->v.AsyncFunctionDef.name;
2209 body = s->v.AsyncFunctionDef.body;
2210
2211 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2212 } else {
2213 assert(s->kind == FunctionDef_kind);
2214
2215 args = s->v.FunctionDef.args;
2216 returns = s->v.FunctionDef.returns;
2217 decos = s->v.FunctionDef.decorator_list;
2218 name = s->v.FunctionDef.name;
2219 body = s->v.FunctionDef.body;
2220
2221 scope_type = COMPILER_SCOPE_FUNCTION;
2222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002224 if (!compiler_check_debug_args(c, args))
2225 return 0;
2226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 if (!compiler_decorators(c, decos))
2228 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002229
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002230 firstlineno = s->lineno;
2231 if (asdl_seq_LEN(decos)) {
2232 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2233 }
2234
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002235 funcflags = compiler_default_arguments(c, args);
2236 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002238 }
2239
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002240 annotations = compiler_visit_annotations(c, args, returns);
2241 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002242 return 0;
2243 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002244 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002245 funcflags |= 0x04;
2246 }
2247
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002248 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002249 return 0;
2250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251
INADA Naokicb41b272017-02-23 00:31:59 +09002252 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002253 if (c->c_optimize < 2) {
2254 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002255 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002256 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 compiler_exit_scope(c);
2258 return 0;
2259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002262 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002264 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002266 qualname = c->u->u_qualname;
2267 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002269 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002270 Py_XDECREF(qualname);
2271 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002275 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002276 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* decorators */
2280 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2281 ADDOP_I(c, CALL_FUNCTION, 1);
2282 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283
Yury Selivanov75445082015-05-11 22:57:16 -04002284 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
2287static int
2288compiler_class(struct compiler *c, stmt_ty s)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 PyCodeObject *co;
2291 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002292 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (!compiler_decorators(c, decos))
2296 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002297
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002298 firstlineno = s->lineno;
2299 if (asdl_seq_LEN(decos)) {
2300 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2301 }
2302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* ultimately generate code for:
2304 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2305 where:
2306 <func> is a function/closure created from the class body;
2307 it has a single argument (__locals__) where the dict
2308 (or MutableSequence) representing the locals is passed
2309 <name> is the class name
2310 <bases> is the positional arguments and *varargs argument
2311 <keywords> is the keyword arguments and **kwds argument
2312 This borrows from compiler_call.
2313 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002316 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002317 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return 0;
2319 /* this block represents what we do in the new scope */
2320 {
2321 /* use the class name for name mangling */
2322 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002323 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* load (global) __name__ ... */
2325 str = PyUnicode_InternFromString("__name__");
2326 if (!str || !compiler_nameop(c, str, Load)) {
2327 Py_XDECREF(str);
2328 compiler_exit_scope(c);
2329 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 Py_DECREF(str);
2332 /* ... and store it as __module__ */
2333 str = PyUnicode_InternFromString("__module__");
2334 if (!str || !compiler_nameop(c, str, Store)) {
2335 Py_XDECREF(str);
2336 compiler_exit_scope(c);
2337 return 0;
2338 }
2339 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002340 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002341 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002342 str = PyUnicode_InternFromString("__qualname__");
2343 if (!str || !compiler_nameop(c, str, Store)) {
2344 Py_XDECREF(str);
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002350 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 compiler_exit_scope(c);
2352 return 0;
2353 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002354 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002355 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002357 str = PyUnicode_InternFromString("__class__");
2358 if (str == NULL) {
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 i = compiler_lookup_arg(c->u->u_cellvars, str);
2363 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002364 if (i < 0) {
2365 compiler_exit_scope(c);
2366 return 0;
2367 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002368 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002371 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002372 str = PyUnicode_InternFromString("__classcell__");
2373 if (!str || !compiler_nameop(c, str, Store)) {
2374 Py_XDECREF(str);
2375 compiler_exit_scope(c);
2376 return 0;
2377 }
2378 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002380 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002381 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002382 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002383 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002384 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002385 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* create the code object */
2387 co = assemble(c, 1);
2388 }
2389 /* leave the new scope */
2390 compiler_exit_scope(c);
2391 if (co == NULL)
2392 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* 2. load the 'build_class' function */
2395 ADDOP(c, LOAD_BUILD_CLASS);
2396
2397 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002398 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 Py_DECREF(co);
2400
2401 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002402 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403
2404 /* 5. generate the rest of the code for the call */
2405 if (!compiler_call_helper(c, 2,
2406 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002407 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return 0;
2409
2410 /* 6. apply decorators */
2411 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2412 ADDOP_I(c, CALL_FUNCTION, 1);
2413 }
2414
2415 /* 7. store into <name> */
2416 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2417 return 0;
2418 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419}
2420
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002421/* Return 0 if the expression is a constant value except named singletons.
2422 Return 1 otherwise. */
2423static int
2424check_is_arg(expr_ty e)
2425{
2426 if (e->kind != Constant_kind) {
2427 return 1;
2428 }
2429 PyObject *value = e->v.Constant.value;
2430 return (value == Py_None
2431 || value == Py_False
2432 || value == Py_True
2433 || value == Py_Ellipsis);
2434}
2435
2436/* Check operands of identity chacks ("is" and "is not").
2437 Emit a warning if any operand is a constant except named singletons.
2438 Return 0 on error.
2439 */
2440static int
2441check_compare(struct compiler *c, expr_ty e)
2442{
2443 Py_ssize_t i, n;
2444 int left = check_is_arg(e->v.Compare.left);
2445 n = asdl_seq_LEN(e->v.Compare.ops);
2446 for (i = 0; i < n; i++) {
2447 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2448 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2449 if (op == Is || op == IsNot) {
2450 if (!right || !left) {
2451 const char *msg = (op == Is)
2452 ? "\"is\" with a literal. Did you mean \"==\"?"
2453 : "\"is not\" with a literal. Did you mean \"!=\"?";
2454 return compiler_warn(c, msg);
2455 }
2456 }
2457 left = right;
2458 }
2459 return 1;
2460}
2461
Mark Shannon9af0e472020-01-14 10:12:45 +00002462static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463{
Mark Shannon9af0e472020-01-14 10:12:45 +00002464 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002465 switch (op) {
2466 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002467 cmp = Py_EQ;
2468 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002470 cmp = Py_NE;
2471 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002472 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002473 cmp = Py_LT;
2474 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002475 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002476 cmp = Py_LE;
2477 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002478 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002479 cmp = Py_GT;
2480 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002482 cmp = Py_GE;
2483 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002484 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002485 ADDOP_I(c, IS_OP, 0);
2486 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002488 ADDOP_I(c, IS_OP, 1);
2489 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002490 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002491 ADDOP_I(c, CONTAINS_OP, 0);
2492 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002493 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002494 ADDOP_I(c, CONTAINS_OP, 1);
2495 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002496 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002497 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002498 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002499 ADDOP_I(c, COMPARE_OP, cmp);
2500 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002501}
2502
Mark Shannon9af0e472020-01-14 10:12:45 +00002503
2504
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002505static int
2506compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2507{
2508 switch (e->kind) {
2509 case UnaryOp_kind:
2510 if (e->v.UnaryOp.op == Not)
2511 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2512 /* fallback to general implementation */
2513 break;
2514 case BoolOp_kind: {
2515 asdl_seq *s = e->v.BoolOp.values;
2516 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2517 assert(n >= 0);
2518 int cond2 = e->v.BoolOp.op == Or;
2519 basicblock *next2 = next;
2520 if (!cond2 != !cond) {
2521 next2 = compiler_new_block(c);
2522 if (next2 == NULL)
2523 return 0;
2524 }
2525 for (i = 0; i < n; ++i) {
2526 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2527 return 0;
2528 }
2529 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2530 return 0;
2531 if (next2 != next)
2532 compiler_use_next_block(c, next2);
2533 return 1;
2534 }
2535 case IfExp_kind: {
2536 basicblock *end, *next2;
2537 end = compiler_new_block(c);
2538 if (end == NULL)
2539 return 0;
2540 next2 = compiler_new_block(c);
2541 if (next2 == NULL)
2542 return 0;
2543 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2544 return 0;
2545 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2546 return 0;
2547 ADDOP_JREL(c, JUMP_FORWARD, end);
2548 compiler_use_next_block(c, next2);
2549 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2550 return 0;
2551 compiler_use_next_block(c, end);
2552 return 1;
2553 }
2554 case Compare_kind: {
2555 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2556 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002557 if (!check_compare(c, e)) {
2558 return 0;
2559 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002560 basicblock *cleanup = compiler_new_block(c);
2561 if (cleanup == NULL)
2562 return 0;
2563 VISIT(c, expr, e->v.Compare.left);
2564 for (i = 0; i < n; i++) {
2565 VISIT(c, expr,
2566 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2567 ADDOP(c, DUP_TOP);
2568 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002569 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002570 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2571 NEXT_BLOCK(c);
2572 }
2573 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002574 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002575 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2576 basicblock *end = compiler_new_block(c);
2577 if (end == NULL)
2578 return 0;
2579 ADDOP_JREL(c, JUMP_FORWARD, end);
2580 compiler_use_next_block(c, cleanup);
2581 ADDOP(c, POP_TOP);
2582 if (!cond) {
2583 ADDOP_JREL(c, JUMP_FORWARD, next);
2584 }
2585 compiler_use_next_block(c, end);
2586 return 1;
2587 }
2588 /* fallback to general implementation */
2589 break;
2590 }
2591 default:
2592 /* fallback to general implementation */
2593 break;
2594 }
2595
2596 /* general implementation */
2597 VISIT(c, expr, e);
2598 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2599 return 1;
2600}
2601
2602static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002603compiler_ifexp(struct compiler *c, expr_ty e)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 basicblock *end, *next;
2606
2607 assert(e->kind == IfExp_kind);
2608 end = compiler_new_block(c);
2609 if (end == NULL)
2610 return 0;
2611 next = compiler_new_block(c);
2612 if (next == NULL)
2613 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002614 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2615 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 VISIT(c, expr, e->v.IfExp.body);
2617 ADDOP_JREL(c, JUMP_FORWARD, end);
2618 compiler_use_next_block(c, next);
2619 VISIT(c, expr, e->v.IfExp.orelse);
2620 compiler_use_next_block(c, end);
2621 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002622}
2623
2624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625compiler_lambda(struct compiler *c, expr_ty e)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002628 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002630 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 arguments_ty args = e->v.Lambda.args;
2632 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002634 if (!compiler_check_debug_args(c, args))
2635 return 0;
2636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (!name) {
2638 name = PyUnicode_InternFromString("<lambda>");
2639 if (!name)
2640 return 0;
2641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002643 funcflags = compiler_default_arguments(c, args);
2644 if (funcflags == -1) {
2645 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002647
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002648 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002649 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Make None the first constant, so the lambda can't have a
2653 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002654 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002658 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2660 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2661 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002662 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 }
2664 else {
2665 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002666 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002668 qualname = c->u->u_qualname;
2669 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002671 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002674 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002675 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 Py_DECREF(co);
2677
2678 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679}
2680
2681static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682compiler_if(struct compiler *c, stmt_ty s)
2683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 basicblock *end, *next;
2685 int constant;
2686 assert(s->kind == If_kind);
2687 end = compiler_new_block(c);
2688 if (end == NULL)
2689 return 0;
2690
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002691 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002692 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 * constant = 1: "if 1", "if 2", ...
2694 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002695 if (constant == 0) {
2696 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002698 END_DO_NOT_EMIT_BYTECODE
2699 if (s->v.If.orelse) {
2700 VISIT_SEQ(c, stmt, s->v.If.orelse);
2701 }
2702 } else if (constant == 1) {
2703 VISIT_SEQ(c, stmt, s->v.If.body);
2704 if (s->v.If.orelse) {
2705 BEGIN_DO_NOT_EMIT_BYTECODE
2706 VISIT_SEQ(c, stmt, s->v.If.orelse);
2707 END_DO_NOT_EMIT_BYTECODE
2708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002710 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 next = compiler_new_block(c);
2712 if (next == NULL)
2713 return 0;
2714 }
Mark Shannonfee55262019-11-21 09:11:43 +00002715 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002717 }
2718 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002719 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002720 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002722 if (asdl_seq_LEN(s->v.If.orelse)) {
2723 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 compiler_use_next_block(c, next);
2725 VISIT_SEQ(c, stmt, s->v.If.orelse);
2726 }
2727 }
2728 compiler_use_next_block(c, end);
2729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730}
2731
2732static int
2733compiler_for(struct compiler *c, stmt_ty s)
2734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 start = compiler_new_block(c);
2738 cleanup = compiler_new_block(c);
2739 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002740 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002742 }
2743 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 VISIT(c, expr, s->v.For.iter);
2747 ADDOP(c, GET_ITER);
2748 compiler_use_next_block(c, start);
2749 ADDOP_JREL(c, FOR_ITER, cleanup);
2750 VISIT(c, expr, s->v.For.target);
2751 VISIT_SEQ(c, stmt, s->v.For.body);
2752 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2753 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002754
2755 compiler_pop_fblock(c, FOR_LOOP, start);
2756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 VISIT_SEQ(c, stmt, s->v.For.orelse);
2758 compiler_use_next_block(c, end);
2759 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760}
2761
Yury Selivanov75445082015-05-11 22:57:16 -04002762
2763static int
2764compiler_async_for(struct compiler *c, stmt_ty s)
2765{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002767 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002768 c->u->u_ste->ste_coroutine = 1;
2769 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002770 return compiler_error(c, "'async for' outside async function");
2771 }
2772
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002773 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002774 except = compiler_new_block(c);
2775 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002776
Mark Shannonfee55262019-11-21 09:11:43 +00002777 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002778 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002779 }
Yury Selivanov75445082015-05-11 22:57:16 -04002780 VISIT(c, expr, s->v.AsyncFor.iter);
2781 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002782
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002783 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002784 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002785 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002786 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002787 /* SETUP_FINALLY to guard the __anext__ call */
2788 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002789 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002790 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002791 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002793
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002794 /* Success block for __anext__ */
2795 VISIT(c, expr, s->v.AsyncFor.target);
2796 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2797 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2798
2799 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002800
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002802 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002803 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002804
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002805 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002806 VISIT_SEQ(c, stmt, s->v.For.orelse);
2807
2808 compiler_use_next_block(c, end);
2809
2810 return 1;
2811}
2812
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813static int
2814compiler_while(struct compiler *c, stmt_ty s)
2815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002817 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002820 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002821 // Push a dummy block so the VISIT_SEQ knows that we are
2822 // inside a while loop so it can correctly evaluate syntax
2823 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002824 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002825 return 0;
2826 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002827 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002828 // Remove the dummy block now that is not needed.
2829 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002830 END_DO_NOT_EMIT_BYTECODE
2831 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 return 1;
2835 }
2836 loop = compiler_new_block(c);
2837 end = compiler_new_block(c);
2838 if (constant == -1) {
2839 anchor = compiler_new_block(c);
2840 if (anchor == NULL)
2841 return 0;
2842 }
2843 if (loop == NULL || end == NULL)
2844 return 0;
2845 if (s->v.While.orelse) {
2846 orelse = compiler_new_block(c);
2847 if (orelse == NULL)
2848 return 0;
2849 }
2850 else
2851 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002854 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 return 0;
2856 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002857 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2858 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 }
2860 VISIT_SEQ(c, stmt, s->v.While.body);
2861 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 /* XXX should the two POP instructions be in a separate block
2864 if there is no else clause ?
2865 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002867 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002869 compiler_pop_fblock(c, WHILE_LOOP, loop);
2870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 if (orelse != NULL) /* what if orelse is just pass? */
2872 VISIT_SEQ(c, stmt, s->v.While.orelse);
2873 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876}
2877
2878static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002882 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 if (c->u->u_ste->ste_type != FunctionBlock)
2884 return compiler_error(c, "'return' outside function");
2885 if (s->v.Return.value != NULL &&
2886 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2887 {
2888 return compiler_error(
2889 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 if (preserve_tos) {
2892 VISIT(c, expr, s->v.Return.value);
2893 }
Mark Shannonfee55262019-11-21 09:11:43 +00002894 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2895 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002897 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002898 }
2899 else if (!preserve_tos) {
2900 VISIT(c, expr, s->v.Return.value);
2901 }
2902 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905}
2906
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002907static int
2908compiler_break(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, "'break' outside loop");
2916 }
2917 if (!compiler_unwind_fblock(c, loop, 0)) {
2918 return 0;
2919 }
2920 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2921 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002922}
2923
2924static int
2925compiler_continue(struct compiler *c)
2926{
Mark Shannonfee55262019-11-21 09:11:43 +00002927 struct fblockinfo *loop = NULL;
2928 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2929 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002930 }
Mark Shannonfee55262019-11-21 09:11:43 +00002931 if (loop == NULL) {
2932 return compiler_error(c, "'continue' not properly in loop");
2933 }
2934 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2935 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002936}
2937
2938
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940
2941 SETUP_FINALLY L
2942 <code for body>
2943 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002944 <code for finalbody>
2945 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 L:
2947 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002948 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 The special instructions use the block stack. Each block
2951 stack entry contains the instruction that created it (here
2952 SETUP_FINALLY), the level of the value stack at the time the
2953 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 Pushes the current value stack level and the label
2957 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002959 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002962 when a SETUP_FINALLY entry is found, the raised and the caught
2963 exceptions are pushed onto the value stack (and the exception
2964 condition is cleared), and the interpreter jumps to the label
2965 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966*/
2967
2968static int
2969compiler_try_finally(struct compiler *c, stmt_ty s)
2970{
Mark Shannonfee55262019-11-21 09:11:43 +00002971 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 body = compiler_new_block(c);
2974 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002975 exit = compiler_new_block(c);
2976 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002979 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 ADDOP_JREL(c, SETUP_FINALLY, end);
2981 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002982 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002984 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2985 if (!compiler_try_except(c, s))
2986 return 0;
2987 }
2988 else {
2989 VISIT_SEQ(c, stmt, s->v.Try.body);
2990 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002992 compiler_pop_fblock(c, FINALLY_TRY, body);
2993 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2994 ADDOP_JREL(c, JUMP_FORWARD, exit);
2995 /* `finally` block */
2996 compiler_use_next_block(c, end);
2997 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2998 return 0;
2999 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3000 compiler_pop_fblock(c, FINALLY_END, end);
3001 ADDOP(c, RERAISE);
3002 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004}
3005
3006/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003007 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008 (The contents of the value stack is shown in [], with the top
3009 at the right; 'tb' is trace-back info, 'val' the exception's
3010 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011
3012 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003013 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 [] <code for S>
3015 [] POP_BLOCK
3016 [] JUMP_FORWARD L0
3017
3018 [tb, val, exc] L1: DUP )
3019 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003020 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 [tb, val, exc] POP
3022 [tb, val] <assign to V1> (or POP if no V1)
3023 [tb] POP
3024 [] <code for S1>
3025 JUMP_FORWARD L0
3026
3027 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028 .............................etc.......................
3029
Mark Shannonfee55262019-11-21 09:11:43 +00003030 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031
3032 [] L0: <next statement>
3033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 Of course, parts are not generated if Vi or Ei is not present.
3035*/
3036static int
3037compiler_try_except(struct compiler *c, stmt_ty s)
3038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003040 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 body = compiler_new_block(c);
3043 except = compiler_new_block(c);
3044 orelse = compiler_new_block(c);
3045 end = compiler_new_block(c);
3046 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3047 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003048 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003050 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003052 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 ADDOP(c, POP_BLOCK);
3054 compiler_pop_fblock(c, EXCEPT, body);
3055 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003056 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 compiler_use_next_block(c, except);
3058 for (i = 0; i < n; i++) {
3059 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003060 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 if (!handler->v.ExceptHandler.type && i < n-1)
3062 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003063 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 except = compiler_new_block(c);
3065 if (except == NULL)
3066 return 0;
3067 if (handler->v.ExceptHandler.type) {
3068 ADDOP(c, DUP_TOP);
3069 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003070 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
3072 ADDOP(c, POP_TOP);
3073 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003075
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 cleanup_end = compiler_new_block(c);
3077 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003078 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003080 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003081
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3083 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 /*
3086 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003087 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003088 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003089 try:
3090 # body
3091 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003092 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003093 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003096 /* second try: */
3097 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3098 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003099 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003100 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 /* second # body */
3103 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003104 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003105 ADDOP(c, POP_BLOCK);
3106 ADDOP(c, POP_EXCEPT);
3107 /* name = None; del name */
3108 ADDOP_LOAD_CONST(c, Py_None);
3109 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3110 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3111 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112
Mark Shannonfee55262019-11-21 09:11:43 +00003113 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003114 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003116 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003117 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003118 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120
Mark Shannonfee55262019-11-21 09:11:43 +00003121 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
3123 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003124 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003126 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003127 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003128 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129
Guido van Rossumb940e112007-01-10 16:19:56 +00003130 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003131 ADDOP(c, POP_TOP);
3132 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003133 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003134 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003136 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003137 ADDOP(c, POP_EXCEPT);
3138 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 compiler_use_next_block(c, except);
3141 }
Mark Shannonfee55262019-11-21 09:11:43 +00003142 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003144 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 compiler_use_next_block(c, end);
3146 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147}
3148
3149static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003150compiler_try(struct compiler *c, stmt_ty s) {
3151 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3152 return compiler_try_finally(c, s);
3153 else
3154 return compiler_try_except(c, s);
3155}
3156
3157
3158static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159compiler_import_as(struct compiler *c, identifier name, identifier asname)
3160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 /* The IMPORT_NAME opcode was already generated. This function
3162 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003165 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003167 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3168 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003169 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003170 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003173 while (1) {
3174 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003176 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003177 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003178 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003179 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003181 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003182 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003183 if (dot == -1) {
3184 break;
3185 }
3186 ADDOP(c, ROT_TWO);
3187 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003189 if (!compiler_nameop(c, asname, Store)) {
3190 return 0;
3191 }
3192 ADDOP(c, POP_TOP);
3193 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 }
3195 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196}
3197
3198static int
3199compiler_import(struct compiler *c, stmt_ty s)
3200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 /* The Import node stores a module name like a.b.c as a single
3202 string. This is convenient for all cases except
3203 import a.b.c as d
3204 where we need to parse that string to extract the individual
3205 module names.
3206 XXX Perhaps change the representation to make this case simpler?
3207 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003208 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 for (i = 0; i < n; i++) {
3211 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3212 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003214 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3215 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 if (alias->asname) {
3219 r = compiler_import_as(c, alias->name, alias->asname);
3220 if (!r)
3221 return r;
3222 }
3223 else {
3224 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003225 Py_ssize_t dot = PyUnicode_FindChar(
3226 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003227 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003228 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003229 if (tmp == NULL)
3230 return 0;
3231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003233 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 Py_DECREF(tmp);
3235 }
3236 if (!r)
3237 return r;
3238 }
3239 }
3240 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003241}
3242
3243static int
3244compiler_from_import(struct compiler *c, stmt_ty s)
3245{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003246 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003247 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (!empty_string) {
3251 empty_string = PyUnicode_FromString("");
3252 if (!empty_string)
3253 return 0;
3254 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003256 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003257
3258 names = PyTuple_New(n);
3259 if (!names)
3260 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 /* build up the names */
3263 for (i = 0; i < n; i++) {
3264 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3265 Py_INCREF(alias->name);
3266 PyTuple_SET_ITEM(names, i, alias->name);
3267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003270 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 Py_DECREF(names);
3272 return compiler_error(c, "from __future__ imports must occur "
3273 "at the beginning of the file");
3274 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003275 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (s->v.ImportFrom.module) {
3278 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3279 }
3280 else {
3281 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3282 }
3283 for (i = 0; i < n; i++) {
3284 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3285 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003287 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 assert(n == 1);
3289 ADDOP(c, IMPORT_STAR);
3290 return 1;
3291 }
3292
3293 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3294 store_name = alias->name;
3295 if (alias->asname)
3296 store_name = alias->asname;
3297
3298 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 return 0;
3300 }
3301 }
3302 /* remove imported module */
3303 ADDOP(c, POP_TOP);
3304 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305}
3306
3307static int
3308compiler_assert(struct compiler *c, stmt_ty s)
3309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311
Georg Brandl8334fd92010-12-04 10:26:46 +00003312 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003315 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3316 {
3317 if (!compiler_warn(c, "assertion is always true, "
3318 "perhaps remove parentheses?"))
3319 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003320 return 0;
3321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 end = compiler_new_block(c);
3324 if (end == NULL)
3325 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003326 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3327 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003328 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 if (s->v.Assert.msg) {
3330 VISIT(c, expr, s->v.Assert.msg);
3331 ADDOP_I(c, CALL_FUNCTION, 1);
3332 }
3333 ADDOP_I(c, RAISE_VARARGS, 1);
3334 compiler_use_next_block(c, end);
3335 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336}
3337
3338static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003339compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3340{
3341 if (c->c_interactive && c->c_nestlevel <= 1) {
3342 VISIT(c, expr, value);
3343 ADDOP(c, PRINT_EXPR);
3344 return 1;
3345 }
3346
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003347 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003348 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003349 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003350 }
3351
3352 VISIT(c, expr, value);
3353 ADDOP(c, POP_TOP);
3354 return 1;
3355}
3356
3357static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358compiler_visit_stmt(struct compiler *c, stmt_ty s)
3359{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003360 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003363 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 switch (s->kind) {
3366 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003367 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 case ClassDef_kind:
3369 return compiler_class(c, s);
3370 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003371 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 case Delete_kind:
3373 VISIT_SEQ(c, expr, s->v.Delete.targets)
3374 break;
3375 case Assign_kind:
3376 n = asdl_seq_LEN(s->v.Assign.targets);
3377 VISIT(c, expr, s->v.Assign.value);
3378 for (i = 0; i < n; i++) {
3379 if (i < n - 1)
3380 ADDOP(c, DUP_TOP);
3381 VISIT(c, expr,
3382 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3383 }
3384 break;
3385 case AugAssign_kind:
3386 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003387 case AnnAssign_kind:
3388 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 case For_kind:
3390 return compiler_for(c, s);
3391 case While_kind:
3392 return compiler_while(c, s);
3393 case If_kind:
3394 return compiler_if(c, s);
3395 case Raise_kind:
3396 n = 0;
3397 if (s->v.Raise.exc) {
3398 VISIT(c, expr, s->v.Raise.exc);
3399 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003400 if (s->v.Raise.cause) {
3401 VISIT(c, expr, s->v.Raise.cause);
3402 n++;
3403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003405 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003407 case Try_kind:
3408 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 case Assert_kind:
3410 return compiler_assert(c, s);
3411 case Import_kind:
3412 return compiler_import(c, s);
3413 case ImportFrom_kind:
3414 return compiler_from_import(c, s);
3415 case Global_kind:
3416 case Nonlocal_kind:
3417 break;
3418 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003419 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 case Pass_kind:
3421 break;
3422 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003423 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 case Continue_kind:
3425 return compiler_continue(c);
3426 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003427 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003428 case AsyncFunctionDef_kind:
3429 return compiler_function(c, s, 1);
3430 case AsyncWith_kind:
3431 return compiler_async_with(c, s, 0);
3432 case AsyncFor_kind:
3433 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 }
Yury Selivanov75445082015-05-11 22:57:16 -04003435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437}
3438
3439static int
3440unaryop(unaryop_ty op)
3441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 switch (op) {
3443 case Invert:
3444 return UNARY_INVERT;
3445 case Not:
3446 return UNARY_NOT;
3447 case UAdd:
3448 return UNARY_POSITIVE;
3449 case USub:
3450 return UNARY_NEGATIVE;
3451 default:
3452 PyErr_Format(PyExc_SystemError,
3453 "unary op %d should not be possible", op);
3454 return 0;
3455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456}
3457
3458static int
Andy Lester76d58772020-03-10 21:18:12 -05003459binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 switch (op) {
3462 case Add:
3463 return BINARY_ADD;
3464 case Sub:
3465 return BINARY_SUBTRACT;
3466 case Mult:
3467 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003468 case MatMult:
3469 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 case Div:
3471 return BINARY_TRUE_DIVIDE;
3472 case Mod:
3473 return BINARY_MODULO;
3474 case Pow:
3475 return BINARY_POWER;
3476 case LShift:
3477 return BINARY_LSHIFT;
3478 case RShift:
3479 return BINARY_RSHIFT;
3480 case BitOr:
3481 return BINARY_OR;
3482 case BitXor:
3483 return BINARY_XOR;
3484 case BitAnd:
3485 return BINARY_AND;
3486 case FloorDiv:
3487 return BINARY_FLOOR_DIVIDE;
3488 default:
3489 PyErr_Format(PyExc_SystemError,
3490 "binary op %d should not be possible", op);
3491 return 0;
3492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493}
3494
3495static int
Andy Lester76d58772020-03-10 21:18:12 -05003496inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 switch (op) {
3499 case Add:
3500 return INPLACE_ADD;
3501 case Sub:
3502 return INPLACE_SUBTRACT;
3503 case Mult:
3504 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003505 case MatMult:
3506 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 case Div:
3508 return INPLACE_TRUE_DIVIDE;
3509 case Mod:
3510 return INPLACE_MODULO;
3511 case Pow:
3512 return INPLACE_POWER;
3513 case LShift:
3514 return INPLACE_LSHIFT;
3515 case RShift:
3516 return INPLACE_RSHIFT;
3517 case BitOr:
3518 return INPLACE_OR;
3519 case BitXor:
3520 return INPLACE_XOR;
3521 case BitAnd:
3522 return INPLACE_AND;
3523 case FloorDiv:
3524 return INPLACE_FLOOR_DIVIDE;
3525 default:
3526 PyErr_Format(PyExc_SystemError,
3527 "inplace binary op %d should not be possible", op);
3528 return 0;
3529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530}
3531
3532static int
3533compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3534{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003535 int op, scope;
3536 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 PyObject *dict = c->u->u_names;
3540 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003542 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3543 !_PyUnicode_EqualToASCIIString(name, "True") &&
3544 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003545
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003546 if (forbidden_name(c, name, ctx))
3547 return 0;
3548
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003549 mangled = _Py_Mangle(c->u->u_private, name);
3550 if (!mangled)
3551 return 0;
3552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 op = 0;
3554 optype = OP_NAME;
3555 scope = PyST_GetScope(c->u->u_ste, mangled);
3556 switch (scope) {
3557 case FREE:
3558 dict = c->u->u_freevars;
3559 optype = OP_DEREF;
3560 break;
3561 case CELL:
3562 dict = c->u->u_cellvars;
3563 optype = OP_DEREF;
3564 break;
3565 case LOCAL:
3566 if (c->u->u_ste->ste_type == FunctionBlock)
3567 optype = OP_FAST;
3568 break;
3569 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003570 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 optype = OP_GLOBAL;
3572 break;
3573 case GLOBAL_EXPLICIT:
3574 optype = OP_GLOBAL;
3575 break;
3576 default:
3577 /* scope can be 0 */
3578 break;
3579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003582 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 switch (optype) {
3585 case OP_DEREF:
3586 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003587 case Load:
3588 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3589 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003590 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003591 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 }
3593 break;
3594 case OP_FAST:
3595 switch (ctx) {
3596 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003597 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003600 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 return 1;
3602 case OP_GLOBAL:
3603 switch (ctx) {
3604 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003605 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 }
3608 break;
3609 case OP_NAME:
3610 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003611 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003612 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 }
3615 break;
3616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003619 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 Py_DECREF(mangled);
3621 if (arg < 0)
3622 return 0;
3623 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624}
3625
3626static int
3627compiler_boolop(struct compiler *c, expr_ty e)
3628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003630 int jumpi;
3631 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 assert(e->kind == BoolOp_kind);
3635 if (e->v.BoolOp.op == And)
3636 jumpi = JUMP_IF_FALSE_OR_POP;
3637 else
3638 jumpi = JUMP_IF_TRUE_OR_POP;
3639 end = compiler_new_block(c);
3640 if (end == NULL)
3641 return 0;
3642 s = e->v.BoolOp.values;
3643 n = asdl_seq_LEN(s) - 1;
3644 assert(n >= 0);
3645 for (i = 0; i < n; ++i) {
3646 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3647 ADDOP_JABS(c, jumpi, end);
3648 }
3649 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3650 compiler_use_next_block(c, end);
3651 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652}
3653
3654static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003655starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3656 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003657{
3658 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003659 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003660 if (n > 2 && are_all_items_const(elts, 0, n)) {
3661 PyObject *folded = PyTuple_New(n);
3662 if (folded == NULL) {
3663 return 0;
3664 }
3665 PyObject *val;
3666 for (i = 0; i < n; i++) {
3667 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3668 Py_INCREF(val);
3669 PyTuple_SET_ITEM(folded, i, val);
3670 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003671 if (tuple) {
3672 ADDOP_LOAD_CONST_NEW(c, folded);
3673 } else {
3674 if (add == SET_ADD) {
3675 Py_SETREF(folded, PyFrozenSet_New(folded));
3676 if (folded == NULL) {
3677 return 0;
3678 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003679 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003680 ADDOP_I(c, build, pushed);
3681 ADDOP_LOAD_CONST_NEW(c, folded);
3682 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003683 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003684 return 1;
3685 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003686
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 for (i = 0; i < n; i++) {
3688 expr_ty elt = asdl_seq_GET(elts, i);
3689 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003690 seen_star = 1;
3691 }
3692 }
3693 if (seen_star) {
3694 seen_star = 0;
3695 for (i = 0; i < n; i++) {
3696 expr_ty elt = asdl_seq_GET(elts, i);
3697 if (elt->kind == Starred_kind) {
3698 if (seen_star == 0) {
3699 ADDOP_I(c, build, i+pushed);
3700 seen_star = 1;
3701 }
3702 VISIT(c, expr, elt->v.Starred.value);
3703 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003704 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003705 else {
3706 VISIT(c, expr, elt);
3707 if (seen_star) {
3708 ADDOP_I(c, add, 1);
3709 }
3710 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003711 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003712 assert(seen_star);
3713 if (tuple) {
3714 ADDOP(c, LIST_TO_TUPLE);
3715 }
3716 }
3717 else {
3718 for (i = 0; i < n; i++) {
3719 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003720 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003721 }
3722 if (tuple) {
3723 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3724 } else {
3725 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003726 }
3727 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003728 return 1;
3729}
3730
3731static int
3732assignment_helper(struct compiler *c, asdl_seq *elts)
3733{
3734 Py_ssize_t n = asdl_seq_LEN(elts);
3735 Py_ssize_t i;
3736 int seen_star = 0;
3737 for (i = 0; i < n; i++) {
3738 expr_ty elt = asdl_seq_GET(elts, i);
3739 if (elt->kind == Starred_kind && !seen_star) {
3740 if ((i >= (1 << 8)) ||
3741 (n-i-1 >= (INT_MAX >> 8)))
3742 return compiler_error(c,
3743 "too many expressions in "
3744 "star-unpacking assignment");
3745 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3746 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003747 }
3748 else if (elt->kind == Starred_kind) {
3749 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003750 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 }
3752 }
3753 if (!seen_star) {
3754 ADDOP_I(c, UNPACK_SEQUENCE, n);
3755 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003756 for (i = 0; i < n; i++) {
3757 expr_ty elt = asdl_seq_GET(elts, i);
3758 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3759 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003760 return 1;
3761}
3762
3763static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764compiler_list(struct compiler *c, expr_ty e)
3765{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003766 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003767 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003768 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003770 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003771 return starunpack_helper(c, elts, 0, BUILD_LIST,
3772 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003774 else
3775 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777}
3778
3779static int
3780compiler_tuple(struct compiler *c, expr_ty e)
3781{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003782 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003783 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003784 return assignment_helper(c, elts);
3785 }
3786 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003787 return starunpack_helper(c, elts, 0, BUILD_LIST,
3788 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 }
3790 else
3791 VISIT_SEQ(c, expr, elts);
3792 return 1;
3793}
3794
3795static int
3796compiler_set(struct compiler *c, expr_ty e)
3797{
Mark Shannon13bc1392020-01-23 09:25:17 +00003798 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3799 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800}
3801
3802static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003803are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3804{
3805 Py_ssize_t i;
3806 for (i = begin; i < end; i++) {
3807 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003808 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003809 return 0;
3810 }
3811 return 1;
3812}
3813
3814static int
3815compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3816{
3817 Py_ssize_t i, n = end - begin;
3818 PyObject *keys, *key;
3819 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3820 for (i = begin; i < end; i++) {
3821 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3822 }
3823 keys = PyTuple_New(n);
3824 if (keys == NULL) {
3825 return 0;
3826 }
3827 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003828 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003829 Py_INCREF(key);
3830 PyTuple_SET_ITEM(keys, i - begin, key);
3831 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003832 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003833 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3834 }
3835 else {
3836 for (i = begin; i < end; i++) {
3837 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3838 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3839 }
3840 ADDOP_I(c, BUILD_MAP, n);
3841 }
3842 return 1;
3843}
3844
3845static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003846compiler_dict(struct compiler *c, expr_ty e)
3847{
Victor Stinner976bb402016-03-23 11:36:19 +01003848 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003849 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003850 int is_unpacking = 0;
3851 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003852 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003853 elements = 0;
3854 for (i = 0; i < n; i++) {
3855 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003856 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003857 if (elements) {
3858 if (!compiler_subdict(c, e, i - elements, i)) {
3859 return 0;
3860 }
3861 if (have_dict) {
3862 ADDOP_I(c, DICT_UPDATE, 1);
3863 }
3864 have_dict = 1;
3865 elements = 0;
3866 }
3867 if (have_dict == 0) {
3868 ADDOP_I(c, BUILD_MAP, 0);
3869 have_dict = 1;
3870 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003871 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003872 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873 }
3874 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003875 if (elements == 0xFFFF) {
3876 if (!compiler_subdict(c, e, i - elements, i)) {
3877 return 0;
3878 }
3879 if (have_dict) {
3880 ADDOP_I(c, DICT_UPDATE, 1);
3881 }
3882 have_dict = 1;
3883 elements = 0;
3884 }
3885 else {
3886 elements++;
3887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 }
3889 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003890 if (elements) {
3891 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003892 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003893 }
3894 if (have_dict) {
3895 ADDOP_I(c, DICT_UPDATE, 1);
3896 }
3897 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003898 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003899 if (!have_dict) {
3900 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 }
3902 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903}
3904
3905static int
3906compiler_compare(struct compiler *c, expr_ty e)
3907{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003908 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003910 if (!check_compare(c, e)) {
3911 return 0;
3912 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003914 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3915 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3916 if (n == 0) {
3917 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003918 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003919 }
3920 else {
3921 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (cleanup == NULL)
3923 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003924 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 VISIT(c, expr,
3926 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003927 ADDOP(c, DUP_TOP);
3928 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003929 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003930 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3931 NEXT_BLOCK(c);
3932 }
3933 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003934 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 basicblock *end = compiler_new_block(c);
3936 if (end == NULL)
3937 return 0;
3938 ADDOP_JREL(c, JUMP_FORWARD, end);
3939 compiler_use_next_block(c, cleanup);
3940 ADDOP(c, ROT_TWO);
3941 ADDOP(c, POP_TOP);
3942 compiler_use_next_block(c, end);
3943 }
3944 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945}
3946
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003947static PyTypeObject *
3948infer_type(expr_ty e)
3949{
3950 switch (e->kind) {
3951 case Tuple_kind:
3952 return &PyTuple_Type;
3953 case List_kind:
3954 case ListComp_kind:
3955 return &PyList_Type;
3956 case Dict_kind:
3957 case DictComp_kind:
3958 return &PyDict_Type;
3959 case Set_kind:
3960 case SetComp_kind:
3961 return &PySet_Type;
3962 case GeneratorExp_kind:
3963 return &PyGen_Type;
3964 case Lambda_kind:
3965 return &PyFunction_Type;
3966 case JoinedStr_kind:
3967 case FormattedValue_kind:
3968 return &PyUnicode_Type;
3969 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003970 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003971 default:
3972 return NULL;
3973 }
3974}
3975
3976static int
3977check_caller(struct compiler *c, expr_ty e)
3978{
3979 switch (e->kind) {
3980 case Constant_kind:
3981 case Tuple_kind:
3982 case List_kind:
3983 case ListComp_kind:
3984 case Dict_kind:
3985 case DictComp_kind:
3986 case Set_kind:
3987 case SetComp_kind:
3988 case GeneratorExp_kind:
3989 case JoinedStr_kind:
3990 case FormattedValue_kind:
3991 return compiler_warn(c, "'%.200s' object is not callable; "
3992 "perhaps you missed a comma?",
3993 infer_type(e)->tp_name);
3994 default:
3995 return 1;
3996 }
3997}
3998
3999static int
4000check_subscripter(struct compiler *c, expr_ty e)
4001{
4002 PyObject *v;
4003
4004 switch (e->kind) {
4005 case Constant_kind:
4006 v = e->v.Constant.value;
4007 if (!(v == Py_None || v == Py_Ellipsis ||
4008 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4009 PyAnySet_Check(v)))
4010 {
4011 return 1;
4012 }
4013 /* fall through */
4014 case Set_kind:
4015 case SetComp_kind:
4016 case GeneratorExp_kind:
4017 case Lambda_kind:
4018 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4019 "perhaps you missed a comma?",
4020 infer_type(e)->tp_name);
4021 default:
4022 return 1;
4023 }
4024}
4025
4026static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004027check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004028{
4029 PyObject *v;
4030
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004031 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004032 if (index_type == NULL
4033 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4034 || index_type == &PySlice_Type) {
4035 return 1;
4036 }
4037
4038 switch (e->kind) {
4039 case Constant_kind:
4040 v = e->v.Constant.value;
4041 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4042 return 1;
4043 }
4044 /* fall through */
4045 case Tuple_kind:
4046 case List_kind:
4047 case ListComp_kind:
4048 case JoinedStr_kind:
4049 case FormattedValue_kind:
4050 return compiler_warn(c, "%.200s indices must be integers or slices, "
4051 "not %.200s; "
4052 "perhaps you missed a comma?",
4053 infer_type(e)->tp_name,
4054 index_type->tp_name);
4055 default:
4056 return 1;
4057 }
4058}
4059
Zackery Spytz97f5de02019-03-22 01:30:32 -06004060// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004062maybe_optimize_method_call(struct compiler *c, expr_ty e)
4063{
4064 Py_ssize_t argsl, i;
4065 expr_ty meth = e->v.Call.func;
4066 asdl_seq *args = e->v.Call.args;
4067
4068 /* Check that the call node is an attribute access, and that
4069 the call doesn't have keyword parameters. */
4070 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4071 asdl_seq_LEN(e->v.Call.keywords))
4072 return -1;
4073
4074 /* Check that there are no *varargs types of arguments. */
4075 argsl = asdl_seq_LEN(args);
4076 for (i = 0; i < argsl; i++) {
4077 expr_ty elt = asdl_seq_GET(args, i);
4078 if (elt->kind == Starred_kind) {
4079 return -1;
4080 }
4081 }
4082
4083 /* Alright, we can optimize the code. */
4084 VISIT(c, expr, meth->v.Attribute.value);
4085 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4086 VISIT_SEQ(c, expr, e->v.Call.args);
4087 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4088 return 1;
4089}
4090
4091static int
Zackery Spytz08050e92020-04-06 00:47:47 -06004092validate_keywords(struct compiler *c, asdl_seq *keywords)
4093{
4094 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4095 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004096 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4097 if (key->arg == NULL) {
4098 continue;
4099 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004100 if (forbidden_name(c, key->arg, Store)) {
4101 return -1;
4102 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004103 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004104 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4105 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4106 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4107 if (msg == NULL) {
4108 return -1;
4109 }
4110 c->u->u_col_offset = other->col_offset;
4111 compiler_error(c, PyUnicode_AsUTF8(msg));
4112 Py_DECREF(msg);
4113 return -1;
4114 }
4115 }
4116 }
4117 return 0;
4118}
4119
4120static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121compiler_call(struct compiler *c, expr_ty e)
4122{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004123 int ret = maybe_optimize_method_call(c, e);
4124 if (ret >= 0) {
4125 return ret;
4126 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004127 if (!check_caller(c, e->v.Call.func)) {
4128 return 0;
4129 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 VISIT(c, expr, e->v.Call.func);
4131 return compiler_call_helper(c, 0,
4132 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004133 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004134}
4135
Eric V. Smith235a6f02015-09-19 14:51:32 -04004136static int
4137compiler_joined_str(struct compiler *c, expr_ty e)
4138{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004139 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004140 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4141 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004142 return 1;
4143}
4144
Eric V. Smitha78c7952015-11-03 12:45:05 -05004145/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004146static int
4147compiler_formatted_value(struct compiler *c, expr_ty e)
4148{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004149 /* Our oparg encodes 2 pieces of information: the conversion
4150 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004151
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004152 Convert the conversion char to 3 bits:
4153 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004154 !s : 001 0x1 FVC_STR
4155 !r : 010 0x2 FVC_REPR
4156 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157
Eric V. Smitha78c7952015-11-03 12:45:05 -05004158 next bit is whether or not we have a format spec:
4159 yes : 100 0x4
4160 no : 000 0x0
4161 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004163 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004164 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004165
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004166 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004167 VISIT(c, expr, e->v.FormattedValue.value);
4168
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004169 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004170 case 's': oparg = FVC_STR; break;
4171 case 'r': oparg = FVC_REPR; break;
4172 case 'a': oparg = FVC_ASCII; break;
4173 case -1: oparg = FVC_NONE; break;
4174 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004175 PyErr_Format(PyExc_SystemError,
4176 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004179 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004180 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004181 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004182 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004183 }
4184
Eric V. Smitha78c7952015-11-03 12:45:05 -05004185 /* And push our opcode and oparg */
4186 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004187
Eric V. Smith235a6f02015-09-19 14:51:32 -04004188 return 1;
4189}
4190
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004191static int
4192compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4193{
4194 Py_ssize_t i, n = end - begin;
4195 keyword_ty kw;
4196 PyObject *keys, *key;
4197 assert(n > 0);
4198 if (n > 1) {
4199 for (i = begin; i < end; i++) {
4200 kw = asdl_seq_GET(keywords, i);
4201 VISIT(c, expr, kw->value);
4202 }
4203 keys = PyTuple_New(n);
4204 if (keys == NULL) {
4205 return 0;
4206 }
4207 for (i = begin; i < end; i++) {
4208 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4209 Py_INCREF(key);
4210 PyTuple_SET_ITEM(keys, i - begin, key);
4211 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004212 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004213 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4214 }
4215 else {
4216 /* a for loop only executes once */
4217 for (i = begin; i < end; i++) {
4218 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004219 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004220 VISIT(c, expr, kw->value);
4221 }
4222 ADDOP_I(c, BUILD_MAP, n);
4223 }
4224 return 1;
4225}
4226
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004227/* shared code between compiler_call and compiler_class */
4228static int
4229compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004230 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004231 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004232 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004233{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004234 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004235
Pablo Galindo254ec782020-04-03 20:37:13 +01004236 if (validate_keywords(c, keywords) == -1) {
4237 return 0;
4238 }
4239
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004240 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004241 nkwelts = asdl_seq_LEN(keywords);
4242
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004243 for (i = 0; i < nelts; i++) {
4244 expr_ty elt = asdl_seq_GET(args, i);
4245 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004246 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004247 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004248 }
4249 for (i = 0; i < nkwelts; i++) {
4250 keyword_ty kw = asdl_seq_GET(keywords, i);
4251 if (kw->arg == NULL) {
4252 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004255
Mark Shannon13bc1392020-01-23 09:25:17 +00004256 /* No * or ** args, so can use faster calling sequence */
4257 for (i = 0; i < nelts; i++) {
4258 expr_ty elt = asdl_seq_GET(args, i);
4259 assert(elt->kind != Starred_kind);
4260 VISIT(c, expr, elt);
4261 }
4262 if (nkwelts) {
4263 PyObject *names;
4264 VISIT_SEQ(c, keyword, keywords);
4265 names = PyTuple_New(nkwelts);
4266 if (names == NULL) {
4267 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004268 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004269 for (i = 0; i < nkwelts; i++) {
4270 keyword_ty kw = asdl_seq_GET(keywords, i);
4271 Py_INCREF(kw->arg);
4272 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004273 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004274 ADDOP_LOAD_CONST_NEW(c, names);
4275 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4276 return 1;
4277 }
4278 else {
4279 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4280 return 1;
4281 }
4282
4283ex_call:
4284
4285 /* Do positional arguments. */
4286 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4287 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4288 }
4289 else if (starunpack_helper(c, args, n, BUILD_LIST,
4290 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4291 return 0;
4292 }
4293 /* Then keyword arguments */
4294 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004295 /* Has a new dict been pushed */
4296 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004297
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004298 nseen = 0; /* the number of keyword arguments on the stack following */
4299 for (i = 0; i < nkwelts; i++) {
4300 keyword_ty kw = asdl_seq_GET(keywords, i);
4301 if (kw->arg == NULL) {
4302 /* A keyword argument unpacking. */
4303 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004304 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004305 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 }
Mark Shannondb64f122020-06-01 10:42:42 +01004307 if (have_dict) {
4308 ADDOP_I(c, DICT_MERGE, 1);
4309 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004310 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004311 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004312 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004313 if (!have_dict) {
4314 ADDOP_I(c, BUILD_MAP, 0);
4315 have_dict = 1;
4316 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004317 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004318 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004319 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004320 else {
4321 nseen++;
4322 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004323 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004324 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004325 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004326 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004327 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004328 }
4329 if (have_dict) {
4330 ADDOP_I(c, DICT_MERGE, 1);
4331 }
4332 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004333 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004334 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004336 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4337 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004338}
4339
Nick Coghlan650f0d02007-04-15 12:05:43 +00004340
4341/* List and set comprehensions and generator expressions work by creating a
4342 nested function to perform the actual iteration. This means that the
4343 iteration variables don't leak into the current scope.
4344 The defined function is called immediately following its definition, with the
4345 result of that call being the result of the expression.
4346 The LC/SC version returns the populated container, while the GE version is
4347 flagged in symtable.c as a generator, so it returns the generator object
4348 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004349
4350 Possible cleanups:
4351 - iterate over the generator sequence instead of using recursion
4352*/
4353
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004355static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356compiler_comprehension_generator(struct compiler *c,
4357 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004358 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004360{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004361 comprehension_ty gen;
4362 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4363 if (gen->is_async) {
4364 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004365 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004366 } else {
4367 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004368 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004369 }
4370}
4371
4372static int
4373compiler_sync_comprehension_generator(struct compiler *c,
4374 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004375 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376 expr_ty elt, expr_ty val, int type)
4377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 /* generate code for the iterator, then each of the ifs,
4379 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 comprehension_ty gen;
4382 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004383 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 start = compiler_new_block(c);
4386 skip = compiler_new_block(c);
4387 if_cleanup = compiler_new_block(c);
4388 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4391 anchor == NULL)
4392 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (gen_index == 0) {
4397 /* Receive outermost iter as an implicit argument */
4398 c->u->u_argcount = 1;
4399 ADDOP_I(c, LOAD_FAST, 0);
4400 }
4401 else {
4402 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004403 /* Fast path for the temporary variable assignment idiom:
4404 for y in [f(x)]
4405 */
4406 asdl_seq *elts;
4407 switch (gen->iter->kind) {
4408 case List_kind:
4409 elts = gen->iter->v.List.elts;
4410 break;
4411 case Tuple_kind:
4412 elts = gen->iter->v.Tuple.elts;
4413 break;
4414 default:
4415 elts = NULL;
4416 }
4417 if (asdl_seq_LEN(elts) == 1) {
4418 expr_ty elt = asdl_seq_GET(elts, 0);
4419 if (elt->kind != Starred_kind) {
4420 VISIT(c, expr, elt);
4421 start = NULL;
4422 }
4423 }
4424 if (start) {
4425 VISIT(c, expr, gen->iter);
4426 ADDOP(c, GET_ITER);
4427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004429 if (start) {
4430 depth++;
4431 compiler_use_next_block(c, start);
4432 ADDOP_JREL(c, FOR_ITER, anchor);
4433 NEXT_BLOCK(c);
4434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 /* XXX this needs to be cleaned up...a lot! */
4438 n = asdl_seq_LEN(gen->ifs);
4439 for (i = 0; i < n; i++) {
4440 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004441 if (!compiler_jump_if(c, e, if_cleanup, 0))
4442 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 NEXT_BLOCK(c);
4444 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 if (++gen_index < asdl_seq_LEN(generators))
4447 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004448 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 elt, val, type))
4450 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 /* only append after the last for generator */
4453 if (gen_index >= asdl_seq_LEN(generators)) {
4454 /* comprehension specific code */
4455 switch (type) {
4456 case COMP_GENEXP:
4457 VISIT(c, expr, elt);
4458 ADDOP(c, YIELD_VALUE);
4459 ADDOP(c, POP_TOP);
4460 break;
4461 case COMP_LISTCOMP:
4462 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004463 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 break;
4465 case COMP_SETCOMP:
4466 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004467 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 break;
4469 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004470 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004473 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 break;
4476 default:
4477 return 0;
4478 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 compiler_use_next_block(c, skip);
4481 }
4482 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004483 if (start) {
4484 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4485 compiler_use_next_block(c, anchor);
4486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487
4488 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004489}
4490
4491static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492compiler_async_comprehension_generator(struct compiler *c,
4493 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004494 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 expr_ty elt, expr_ty val, int type)
4496{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004498 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004499 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004500 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004501 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004504 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505 return 0;
4506 }
4507
4508 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4509
4510 if (gen_index == 0) {
4511 /* Receive outermost iter as an implicit argument */
4512 c->u->u_argcount = 1;
4513 ADDOP_I(c, LOAD_FAST, 0);
4514 }
4515 else {
4516 /* Sub-iter - calculate on the fly */
4517 VISIT(c, expr, gen->iter);
4518 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004519 }
4520
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004521 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004522
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004523 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004525 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004528 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529
4530 n = asdl_seq_LEN(gen->ifs);
4531 for (i = 0; i < n; i++) {
4532 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004533 if (!compiler_jump_if(c, e, if_cleanup, 0))
4534 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 NEXT_BLOCK(c);
4536 }
4537
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004538 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004539 if (++gen_index < asdl_seq_LEN(generators))
4540 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004541 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004542 elt, val, type))
4543 return 0;
4544
4545 /* only append after the last for generator */
4546 if (gen_index >= asdl_seq_LEN(generators)) {
4547 /* comprehension specific code */
4548 switch (type) {
4549 case COMP_GENEXP:
4550 VISIT(c, expr, elt);
4551 ADDOP(c, YIELD_VALUE);
4552 ADDOP(c, POP_TOP);
4553 break;
4554 case COMP_LISTCOMP:
4555 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004556 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 break;
4558 case COMP_SETCOMP:
4559 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004560 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 break;
4562 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004563 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004564 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004565 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004566 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004567 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568 break;
4569 default:
4570 return 0;
4571 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004572 }
4573 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004574 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4575
4576 compiler_use_next_block(c, except);
4577 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578
4579 return 1;
4580}
4581
4582static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004583compiler_comprehension(struct compiler *c, expr_ty e, int type,
4584 identifier name, asdl_seq *generators, expr_ty elt,
4585 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004588 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004589 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004591
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004592 if (IS_TOP_LEVEL_AWAIT(c)) {
4593 c->u->u_ste->ste_coroutine = 1;
4594 }
4595 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004596
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004597 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004598 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4599 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004600 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004602 }
4603
4604 is_async_generator = c->u->u_ste->ste_coroutine;
4605
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004606 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004607 compiler_error(c, "asynchronous comprehension outside of "
4608 "an asynchronous function");
4609 goto error_in_scope;
4610 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (type != COMP_GENEXP) {
4613 int op;
4614 switch (type) {
4615 case COMP_LISTCOMP:
4616 op = BUILD_LIST;
4617 break;
4618 case COMP_SETCOMP:
4619 op = BUILD_SET;
4620 break;
4621 case COMP_DICTCOMP:
4622 op = BUILD_MAP;
4623 break;
4624 default:
4625 PyErr_Format(PyExc_SystemError,
4626 "unknown comprehension type %d", type);
4627 goto error_in_scope;
4628 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 ADDOP_I(c, op, 0);
4631 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004632
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004633 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 val, type))
4635 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 if (type != COMP_GENEXP) {
4638 ADDOP(c, RETURN_VALUE);
4639 }
4640
4641 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004642 qualname = c->u->u_qualname;
4643 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004645 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 goto error;
4647
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004648 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004650 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 Py_DECREF(co);
4652
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004653 VISIT(c, expr, outermost->iter);
4654
4655 if (outermost->is_async) {
4656 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004657 } else {
4658 ADDOP(c, GET_ITER);
4659 }
4660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004662
4663 if (is_async_generator && type != COMP_GENEXP) {
4664 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004665 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004666 ADDOP(c, YIELD_FROM);
4667 }
4668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004670error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004672error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004673 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 Py_XDECREF(co);
4675 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004676}
4677
4678static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004679compiler_genexp(struct compiler *c, expr_ty e)
4680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 static identifier name;
4682 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004683 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 if (!name)
4685 return 0;
4686 }
4687 assert(e->kind == GeneratorExp_kind);
4688 return compiler_comprehension(c, e, COMP_GENEXP, name,
4689 e->v.GeneratorExp.generators,
4690 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004691}
4692
4693static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004694compiler_listcomp(struct compiler *c, expr_ty e)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 static identifier name;
4697 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004698 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (!name)
4700 return 0;
4701 }
4702 assert(e->kind == ListComp_kind);
4703 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4704 e->v.ListComp.generators,
4705 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004706}
4707
4708static int
4709compiler_setcomp(struct compiler *c, expr_ty e)
4710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 static identifier name;
4712 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004713 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 if (!name)
4715 return 0;
4716 }
4717 assert(e->kind == SetComp_kind);
4718 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4719 e->v.SetComp.generators,
4720 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004721}
4722
4723
4724static int
4725compiler_dictcomp(struct compiler *c, expr_ty e)
4726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 static identifier name;
4728 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004729 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (!name)
4731 return 0;
4732 }
4733 assert(e->kind == DictComp_kind);
4734 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4735 e->v.DictComp.generators,
4736 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004737}
4738
4739
4740static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004741compiler_visit_keyword(struct compiler *c, keyword_ty k)
4742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 VISIT(c, expr, k->value);
4744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745}
4746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748 whether they are true or false.
4749
4750 Return values: 1 for true, 0 for false, -1 for non-constant.
4751 */
4752
4753static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004754expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004755{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004756 if (e->kind == Constant_kind) {
4757 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004758 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004759 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004760}
4761
Mark Shannonfee55262019-11-21 09:11:43 +00004762static int
4763compiler_with_except_finish(struct compiler *c) {
4764 basicblock *exit;
4765 exit = compiler_new_block(c);
4766 if (exit == NULL)
4767 return 0;
4768 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4769 ADDOP(c, RERAISE);
4770 compiler_use_next_block(c, exit);
4771 ADDOP(c, POP_TOP);
4772 ADDOP(c, POP_TOP);
4773 ADDOP(c, POP_TOP);
4774 ADDOP(c, POP_EXCEPT);
4775 ADDOP(c, POP_TOP);
4776 return 1;
4777}
Yury Selivanov75445082015-05-11 22:57:16 -04004778
4779/*
4780 Implements the async with statement.
4781
4782 The semantics outlined in that PEP are as follows:
4783
4784 async with EXPR as VAR:
4785 BLOCK
4786
4787 It is implemented roughly as:
4788
4789 context = EXPR
4790 exit = context.__aexit__ # not calling it
4791 value = await context.__aenter__()
4792 try:
4793 VAR = value # if VAR present in the syntax
4794 BLOCK
4795 finally:
4796 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004797 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004798 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004799 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004800 if not (await exit(*exc)):
4801 raise
4802 */
4803static int
4804compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4805{
Mark Shannonfee55262019-11-21 09:11:43 +00004806 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004807 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4808
4809 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004810 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004811 c->u->u_ste->ste_coroutine = 1;
4812 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004813 return compiler_error(c, "'async with' outside async function");
4814 }
Yury Selivanov75445082015-05-11 22:57:16 -04004815
4816 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004817 final = compiler_new_block(c);
4818 exit = compiler_new_block(c);
4819 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004820 return 0;
4821
4822 /* Evaluate EXPR */
4823 VISIT(c, expr, item->context_expr);
4824
4825 ADDOP(c, BEFORE_ASYNC_WITH);
4826 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004827 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004828 ADDOP(c, YIELD_FROM);
4829
Mark Shannonfee55262019-11-21 09:11:43 +00004830 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004831
4832 /* SETUP_ASYNC_WITH pushes a finally block. */
4833 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004834 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004835 return 0;
4836 }
4837
4838 if (item->optional_vars) {
4839 VISIT(c, expr, item->optional_vars);
4840 }
4841 else {
4842 /* Discard result from context.__aenter__() */
4843 ADDOP(c, POP_TOP);
4844 }
4845
4846 pos++;
4847 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4848 /* BLOCK code */
4849 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4850 else if (!compiler_async_with(c, s, pos))
4851 return 0;
4852
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004853 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004854 ADDOP(c, POP_BLOCK);
4855 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004856
Mark Shannonfee55262019-11-21 09:11:43 +00004857 /* For successful outcome:
4858 * call __exit__(None, None, None)
4859 */
4860 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004861 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004862 ADDOP(c, GET_AWAITABLE);
4863 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4864 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004865
Mark Shannonfee55262019-11-21 09:11:43 +00004866 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004867
Mark Shannonfee55262019-11-21 09:11:43 +00004868 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4869
4870 /* For exceptional outcome: */
4871 compiler_use_next_block(c, final);
4872
4873 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004874 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004875 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004876 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004877 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004878
Mark Shannonfee55262019-11-21 09:11:43 +00004879compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004880 return 1;
4881}
4882
4883
Guido van Rossumc2e20742006-02-27 22:32:47 +00004884/*
4885 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004886 with EXPR as VAR:
4887 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004888 is implemented as:
4889 <code for EXPR>
4890 SETUP_WITH E
4891 <code to store to VAR> or POP_TOP
4892 <code for BLOCK>
4893 LOAD_CONST (None, None, None)
4894 CALL_FUNCTION_EX 0
4895 JUMP_FORWARD EXIT
4896 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4897 POP_JUMP_IF_TRUE T:
4898 RERAISE
4899 T: POP_TOP * 3 (remove exception from stack)
4900 POP_EXCEPT
4901 POP_TOP
4902 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004903 */
Mark Shannonfee55262019-11-21 09:11:43 +00004904
Guido van Rossumc2e20742006-02-27 22:32:47 +00004905static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004906compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004907{
Mark Shannonfee55262019-11-21 09:11:43 +00004908 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004909 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910
4911 assert(s->kind == With_kind);
4912
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004914 final = compiler_new_block(c);
4915 exit = compiler_new_block(c);
4916 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004917 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918
Thomas Wouters477c8d52006-05-27 19:21:47 +00004919 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004920 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004921 /* Will push bound __exit__ */
4922 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004923
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004924 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004925 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004926 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004927 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004928 }
4929
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004930 if (item->optional_vars) {
4931 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004932 }
4933 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004935 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004936 }
4937
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004938 pos++;
4939 if (pos == asdl_seq_LEN(s->v.With.items))
4940 /* BLOCK code */
4941 VISIT_SEQ(c, stmt, s->v.With.body)
4942 else if (!compiler_with(c, s, pos))
4943 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004944
Guido van Rossumc2e20742006-02-27 22:32:47 +00004945 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004946 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004947
Mark Shannonfee55262019-11-21 09:11:43 +00004948 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004949
Mark Shannonfee55262019-11-21 09:11:43 +00004950 /* For successful outcome:
4951 * call __exit__(None, None, None)
4952 */
4953 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004954 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004955 ADDOP(c, POP_TOP);
4956 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004957
Mark Shannonfee55262019-11-21 09:11:43 +00004958 /* For exceptional outcome: */
4959 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004960
Mark Shannonfee55262019-11-21 09:11:43 +00004961 ADDOP(c, WITH_EXCEPT_START);
4962 compiler_with_except_finish(c);
4963
4964 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004965 return 1;
4966}
4967
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004968static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004969compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004972 case NamedExpr_kind:
4973 VISIT(c, expr, e->v.NamedExpr.value);
4974 ADDOP(c, DUP_TOP);
4975 VISIT(c, expr, e->v.NamedExpr.target);
4976 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 case BoolOp_kind:
4978 return compiler_boolop(c, e);
4979 case BinOp_kind:
4980 VISIT(c, expr, e->v.BinOp.left);
4981 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004982 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 break;
4984 case UnaryOp_kind:
4985 VISIT(c, expr, e->v.UnaryOp.operand);
4986 ADDOP(c, unaryop(e->v.UnaryOp.op));
4987 break;
4988 case Lambda_kind:
4989 return compiler_lambda(c, e);
4990 case IfExp_kind:
4991 return compiler_ifexp(c, e);
4992 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004993 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004994 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004995 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 case GeneratorExp_kind:
4997 return compiler_genexp(c, e);
4998 case ListComp_kind:
4999 return compiler_listcomp(c, e);
5000 case SetComp_kind:
5001 return compiler_setcomp(c, e);
5002 case DictComp_kind:
5003 return compiler_dictcomp(c, e);
5004 case Yield_kind:
5005 if (c->u->u_ste->ste_type != FunctionBlock)
5006 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005007 if (e->v.Yield.value) {
5008 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 }
5010 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005011 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005013 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005015 case YieldFrom_kind:
5016 if (c->u->u_ste->ste_type != FunctionBlock)
5017 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005018
5019 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5020 return compiler_error(c, "'yield from' inside async function");
5021
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005022 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005023 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005024 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005025 ADDOP(c, YIELD_FROM);
5026 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005027 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005028 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005029 if (c->u->u_ste->ste_type != FunctionBlock){
5030 return compiler_error(c, "'await' outside function");
5031 }
Yury Selivanov75445082015-05-11 22:57:16 -04005032
Victor Stinner331a6a52019-05-27 16:39:22 +02005033 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005034 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5035 return compiler_error(c, "'await' outside async function");
5036 }
5037 }
Yury Selivanov75445082015-05-11 22:57:16 -04005038
5039 VISIT(c, expr, e->v.Await.value);
5040 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005041 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005042 ADDOP(c, YIELD_FROM);
5043 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 case Compare_kind:
5045 return compiler_compare(c, e);
5046 case Call_kind:
5047 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005048 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005050 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005051 case JoinedStr_kind:
5052 return compiler_joined_str(c, e);
5053 case FormattedValue_kind:
5054 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 /* The following exprs can be assignment targets. */
5056 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005057 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 case Load:
5060 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5061 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005063 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5064 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5066 break;
5067 case Del:
5068 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5069 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 }
5071 break;
5072 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005073 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 case Starred_kind:
5075 switch (e->v.Starred.ctx) {
5076 case Store:
5077 /* In all legitimate cases, the Starred node was already replaced
5078 * by compiler_list/compiler_tuple. XXX: is that okay? */
5079 return compiler_error(c,
5080 "starred assignment target must be in a list or tuple");
5081 default:
5082 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005083 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005085 break;
5086 case Slice_kind:
5087 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 case Name_kind:
5089 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5090 /* child nodes of List and Tuple will have expr_context set */
5091 case List_kind:
5092 return compiler_list(c, e);
5093 case Tuple_kind:
5094 return compiler_tuple(c, e);
5095 }
5096 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005097}
5098
5099static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005100compiler_visit_expr(struct compiler *c, expr_ty e)
5101{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005102 int old_lineno = c->u->u_lineno;
5103 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005104 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005105 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005106 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005107 c->u->u_col_offset = old_col_offset;
5108 return res;
5109}
5110
5111static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005112compiler_augassign(struct compiler *c, stmt_ty s)
5113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005115 expr_ty e = s->v.AugAssign.target;
5116
5117 int old_lineno = c->u->u_lineno;
5118 int old_col_offset = c->u->u_col_offset;
5119 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 switch (e->kind) {
5122 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005123 VISIT(c, expr, e->v.Attribute.value);
5124 ADDOP(c, DUP_TOP);
5125 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 break;
5127 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005128 VISIT(c, expr, e->v.Subscript.value);
5129 VISIT(c, expr, e->v.Subscript.slice);
5130 ADDOP(c, DUP_TOP_TWO);
5131 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 break;
5133 case Name_kind:
5134 if (!compiler_nameop(c, e->v.Name.id, Load))
5135 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005136 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 default:
5138 PyErr_Format(PyExc_SystemError,
5139 "invalid node type (%d) for augmented assignment",
5140 e->kind);
5141 return 0;
5142 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005143
5144 c->u->u_lineno = old_lineno;
5145 c->u->u_col_offset = old_col_offset;
5146
5147 VISIT(c, expr, s->v.AugAssign.value);
5148 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5149
5150 SET_LOC(c, e);
5151
5152 switch (e->kind) {
5153 case Attribute_kind:
5154 ADDOP(c, ROT_TWO);
5155 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5156 break;
5157 case Subscript_kind:
5158 ADDOP(c, ROT_THREE);
5159 ADDOP(c, STORE_SUBSCR);
5160 break;
5161 case Name_kind:
5162 return compiler_nameop(c, e->v.Name.id, Store);
5163 default:
5164 Py_UNREACHABLE();
5165 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005166 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005167}
5168
5169static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005170check_ann_expr(struct compiler *c, expr_ty e)
5171{
5172 VISIT(c, expr, e);
5173 ADDOP(c, POP_TOP);
5174 return 1;
5175}
5176
5177static int
5178check_annotation(struct compiler *c, stmt_ty s)
5179{
5180 /* Annotations are only evaluated in a module or class. */
5181 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5182 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5183 return check_ann_expr(c, s->v.AnnAssign.annotation);
5184 }
5185 return 1;
5186}
5187
5188static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005189check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005190{
5191 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005192 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005193 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005194 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005195 return 0;
5196 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005197 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5198 return 0;
5199 }
5200 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5201 return 0;
5202 }
5203 return 1;
5204 case Tuple_kind: {
5205 /* extended slice */
5206 asdl_seq *elts = e->v.Tuple.elts;
5207 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005208 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005209 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005210 return 0;
5211 }
5212 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005213 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005214 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005215 default:
5216 return check_ann_expr(c, e);
5217 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005218}
5219
5220static int
5221compiler_annassign(struct compiler *c, stmt_ty s)
5222{
5223 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005224 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005225
5226 assert(s->kind == AnnAssign_kind);
5227
5228 /* We perform the actual assignment first. */
5229 if (s->v.AnnAssign.value) {
5230 VISIT(c, expr, s->v.AnnAssign.value);
5231 VISIT(c, expr, targ);
5232 }
5233 switch (targ->kind) {
5234 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005235 if (forbidden_name(c, targ->v.Name.id, Store))
5236 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005237 /* If we have a simple name in a module or class, store annotation. */
5238 if (s->v.AnnAssign.simple &&
5239 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5240 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005241 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5242 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5243 }
5244 else {
5245 VISIT(c, expr, s->v.AnnAssign.annotation);
5246 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005247 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005248 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005249 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005250 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005251 }
5252 break;
5253 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005254 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5255 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005256 if (!s->v.AnnAssign.value &&
5257 !check_ann_expr(c, targ->v.Attribute.value)) {
5258 return 0;
5259 }
5260 break;
5261 case Subscript_kind:
5262 if (!s->v.AnnAssign.value &&
5263 (!check_ann_expr(c, targ->v.Subscript.value) ||
5264 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5265 return 0;
5266 }
5267 break;
5268 default:
5269 PyErr_Format(PyExc_SystemError,
5270 "invalid node type (%d) for annotated assignment",
5271 targ->kind);
5272 return 0;
5273 }
5274 /* Annotation is evaluated last. */
5275 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5276 return 0;
5277 }
5278 return 1;
5279}
5280
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005281/* Raises a SyntaxError and returns 0.
5282 If something goes wrong, a different exception may be raised.
5283*/
5284
5285static int
5286compiler_error(struct compiler *c, const char *errstr)
5287{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005288 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290
Victor Stinner14e461d2013-08-26 22:28:21 +02005291 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (!loc) {
5293 Py_INCREF(Py_None);
5294 loc = Py_None;
5295 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005296 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005297 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 if (!u)
5299 goto exit;
5300 v = Py_BuildValue("(zO)", errstr, u);
5301 if (!v)
5302 goto exit;
5303 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005304 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005305 Py_DECREF(loc);
5306 Py_XDECREF(u);
5307 Py_XDECREF(v);
5308 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005309}
5310
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005311/* Emits a SyntaxWarning and returns 1 on success.
5312 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5313 and returns 0.
5314*/
5315static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005316compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005317{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005318 va_list vargs;
5319#ifdef HAVE_STDARG_PROTOTYPES
5320 va_start(vargs, format);
5321#else
5322 va_start(vargs);
5323#endif
5324 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5325 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005326 if (msg == NULL) {
5327 return 0;
5328 }
5329 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5330 c->u->u_lineno, NULL, NULL) < 0)
5331 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005332 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005333 /* Replace the SyntaxWarning exception with a SyntaxError
5334 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005335 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005336 assert(PyUnicode_AsUTF8(msg) != NULL);
5337 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005338 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005339 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005340 return 0;
5341 }
5342 Py_DECREF(msg);
5343 return 1;
5344}
5345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005346static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005347compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005348{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005349 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005352 if (ctx == Load) {
5353 if (!check_subscripter(c, e->v.Subscript.value)) {
5354 return 0;
5355 }
5356 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5357 return 0;
5358 }
5359 }
5360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 case Store: op = STORE_SUBSCR; break;
5364 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005366 assert(op);
5367 VISIT(c, expr, e->v.Subscript.value);
5368 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 ADDOP(c, op);
5370 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005371}
5372
5373static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005374compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 int n = 2;
5377 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 /* only handles the cases where BUILD_SLICE is emitted */
5380 if (s->v.Slice.lower) {
5381 VISIT(c, expr, s->v.Slice.lower);
5382 }
5383 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005384 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 if (s->v.Slice.upper) {
5388 VISIT(c, expr, s->v.Slice.upper);
5389 }
5390 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005391 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 }
5393
5394 if (s->v.Slice.step) {
5395 n++;
5396 VISIT(c, expr, s->v.Slice.step);
5397 }
5398 ADDOP_I(c, BUILD_SLICE, n);
5399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400}
5401
Thomas Wouters89f507f2006-12-13 04:49:30 +00005402/* End of the compiler section, beginning of the assembler section */
5403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005405 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005406
5407 XXX must handle implicit jumps from one block to next
5408*/
5409
Thomas Wouters89f507f2006-12-13 04:49:30 +00005410struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 PyObject *a_bytecode; /* string containing bytecode */
5412 int a_offset; /* offset into bytecode */
5413 int a_nblocks; /* number of reachable blocks */
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005414 basicblock **a_reverse_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 PyObject *a_lnotab; /* string containing lnotab */
5416 int a_lnotab_off; /* offset into lnotab */
5417 int a_lineno; /* last lineno of emitted instruction */
5418 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005419};
5420
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005421static void
T. Wouters99b54d62019-09-12 07:05:33 -07005422dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005423{
T. Wouters99b54d62019-09-12 07:05:33 -07005424
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005425 /* There is no real depth-first-search to do here because all the
5426 * blocks are emitted in topological order already, so we just need to
5427 * follow the b_next pointers and place them in a->a_reverse_postorder in
5428 * reverse order and make sure that the first one starts at 0. */
5429
5430 for (a->a_nblocks = 0; b != NULL; b = b->b_next) {
5431 a->a_reverse_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433}
5434
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005435Py_LOCAL_INLINE(void)
5436stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005437{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005438 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005439 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005440 assert(b->b_startdepth < 0);
5441 b->b_startdepth = depth;
5442 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005443 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005444}
5445
5446/* Find the flow path that needs the largest stack. We assume that
5447 * cycles in the flow graph have no net effect on the stack depth.
5448 */
5449static int
5450stackdepth(struct compiler *c)
5451{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005452 basicblock *b, *entryblock = NULL;
5453 basicblock **stack, **sp;
5454 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 b->b_startdepth = INT_MIN;
5457 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005458 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005459 }
5460 if (!entryblock)
5461 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005462 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5463 if (!stack) {
5464 PyErr_NoMemory();
5465 return -1;
5466 }
5467
5468 sp = stack;
5469 stackdepth_push(&sp, entryblock, 0);
5470 while (sp != stack) {
5471 b = *--sp;
5472 int depth = b->b_startdepth;
5473 assert(depth >= 0);
5474 basicblock *next = b->b_next;
5475 for (int i = 0; i < b->b_iused; i++) {
5476 struct instr *instr = &b->b_instr[i];
5477 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5478 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005479 _Py_FatalErrorFormat(__func__,
5480 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005481 }
5482 int new_depth = depth + effect;
5483 if (new_depth > maxdepth) {
5484 maxdepth = new_depth;
5485 }
5486 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5487 if (instr->i_jrel || instr->i_jabs) {
5488 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5489 assert(effect != PY_INVALID_STACK_EFFECT);
5490 int target_depth = depth + effect;
5491 if (target_depth > maxdepth) {
5492 maxdepth = target_depth;
5493 }
5494 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005495 stackdepth_push(&sp, instr->i_target, target_depth);
5496 }
5497 depth = new_depth;
5498 if (instr->i_opcode == JUMP_ABSOLUTE ||
5499 instr->i_opcode == JUMP_FORWARD ||
5500 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005501 instr->i_opcode == RAISE_VARARGS ||
5502 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005503 {
5504 /* remaining code is dead */
5505 next = NULL;
5506 break;
5507 }
5508 }
5509 if (next != NULL) {
5510 stackdepth_push(&sp, next, depth);
5511 }
5512 }
5513 PyObject_Free(stack);
5514 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005515}
5516
5517static int
5518assemble_init(struct assembler *a, int nblocks, int firstlineno)
5519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 memset(a, 0, sizeof(struct assembler));
5521 a->a_lineno = firstlineno;
5522 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5523 if (!a->a_bytecode)
5524 return 0;
5525 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5526 if (!a->a_lnotab)
5527 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005528 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 PyErr_NoMemory();
5530 return 0;
5531 }
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005532 a->a_reverse_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 sizeof(basicblock *) * nblocks);
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005534 if (!a->a_reverse_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 PyErr_NoMemory();
5536 return 0;
5537 }
5538 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005539}
5540
5541static void
5542assemble_free(struct assembler *a)
5543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 Py_XDECREF(a->a_bytecode);
5545 Py_XDECREF(a->a_lnotab);
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005546 if (a->a_reverse_postorder)
5547 PyObject_Free(a->a_reverse_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005548}
5549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005550static int
5551blocksize(basicblock *b)
5552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 int i;
5554 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005557 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005559}
5560
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005561/* Appends a pair to the end of the line number table, a_lnotab, representing
5562 the instruction's bytecode offset and line number. See
5563 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005564
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005565static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005569 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005573 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005575 }
5576
5577 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5578 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005580 if (d_bytecode > 255) {
5581 int j, nbytes, ncodes = d_bytecode / 255;
5582 nbytes = a->a_lnotab_off + 2 * ncodes;
5583 len = PyBytes_GET_SIZE(a->a_lnotab);
5584 if (nbytes >= len) {
5585 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5586 len = nbytes;
5587 else if (len <= INT_MAX / 2)
5588 len *= 2;
5589 else {
5590 PyErr_NoMemory();
5591 return 0;
5592 }
5593 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5594 return 0;
5595 }
5596 lnotab = (unsigned char *)
5597 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5598 for (j = 0; j < ncodes; j++) {
5599 *lnotab++ = 255;
5600 *lnotab++ = 0;
5601 }
5602 d_bytecode -= ncodes * 255;
5603 a->a_lnotab_off += ncodes * 2;
5604 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005605 assert(0 <= d_bytecode && d_bytecode <= 255);
5606
5607 if (d_lineno < -128 || 127 < d_lineno) {
5608 int j, nbytes, ncodes, k;
5609 if (d_lineno < 0) {
5610 k = -128;
5611 /* use division on positive numbers */
5612 ncodes = (-d_lineno) / 128;
5613 }
5614 else {
5615 k = 127;
5616 ncodes = d_lineno / 127;
5617 }
5618 d_lineno -= ncodes * k;
5619 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 nbytes = a->a_lnotab_off + 2 * ncodes;
5621 len = PyBytes_GET_SIZE(a->a_lnotab);
5622 if (nbytes >= len) {
5623 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5624 len = nbytes;
5625 else if (len <= INT_MAX / 2)
5626 len *= 2;
5627 else {
5628 PyErr_NoMemory();
5629 return 0;
5630 }
5631 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5632 return 0;
5633 }
5634 lnotab = (unsigned char *)
5635 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5636 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005637 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 d_bytecode = 0;
5639 for (j = 1; j < ncodes; j++) {
5640 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005641 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 a->a_lnotab_off += ncodes * 2;
5644 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005645 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 len = PyBytes_GET_SIZE(a->a_lnotab);
5648 if (a->a_lnotab_off + 2 >= len) {
5649 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5650 return 0;
5651 }
5652 lnotab = (unsigned char *)
5653 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 a->a_lnotab_off += 2;
5656 if (d_bytecode) {
5657 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005658 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 }
5660 else { /* First line of a block; def stmt, etc. */
5661 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005662 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 }
5664 a->a_lineno = i->i_lineno;
5665 a->a_lineno_off = a->a_offset;
5666 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005667}
5668
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005669/* assemble_emit()
5670 Extend the bytecode with a new instruction.
5671 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005672*/
5673
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005674static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005675assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005676{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005677 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005679 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005680
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005681 arg = i->i_oparg;
5682 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 if (i->i_lineno && !assemble_lnotab(a, i))
5684 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005685 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 if (len > PY_SSIZE_T_MAX / 2)
5687 return 0;
5688 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5689 return 0;
5690 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005691 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005693 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005695}
5696
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005697static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005698assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005701 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 /* Compute the size of each block and fixup jump args.
5705 Replace block pointer with position in bytecode. */
5706 do {
5707 totsize = 0;
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005708 for (i = 0; i < a->a_nblocks; i++) {
5709 b = a->a_reverse_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 bsize = blocksize(b);
5711 b->b_offset = totsize;
5712 totsize += bsize;
5713 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005714 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5716 bsize = b->b_offset;
5717 for (i = 0; i < b->b_iused; i++) {
5718 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005719 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 /* Relative jumps are computed relative to
5721 the instruction pointer after fetching
5722 the jump instruction.
5723 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005724 bsize += isize;
5725 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005727 if (instr->i_jrel) {
5728 instr->i_oparg -= bsize;
5729 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005730 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005731 if (instrsize(instr->i_oparg) != isize) {
5732 extended_arg_recompile = 1;
5733 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 }
5736 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 /* XXX: This is an awful hack that could hurt performance, but
5739 on the bright side it should work until we come up
5740 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 The issue is that in the first loop blocksize() is called
5743 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005744 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005747 So we loop until we stop seeing new EXTENDED_ARGs.
5748 The only EXTENDED_ARGs that could be popping up are
5749 ones in jump instructions. So this should converge
5750 fairly quickly.
5751 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005752 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005753}
5754
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005755static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005756dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005759 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 tuple = PyTuple_New(size);
5762 if (tuple == NULL)
5763 return NULL;
5764 while (PyDict_Next(dict, &pos, &k, &v)) {
5765 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005766 Py_INCREF(k);
5767 assert((i - offset) < size);
5768 assert((i - offset) >= 0);
5769 PyTuple_SET_ITEM(tuple, i - offset, k);
5770 }
5771 return tuple;
5772}
5773
5774static PyObject *
5775consts_dict_keys_inorder(PyObject *dict)
5776{
5777 PyObject *consts, *k, *v;
5778 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5779
5780 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5781 if (consts == NULL)
5782 return NULL;
5783 while (PyDict_Next(dict, &pos, &k, &v)) {
5784 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005785 /* The keys of the dictionary can be tuples wrapping a contant.
5786 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5787 * the object we want is always second. */
5788 if (PyTuple_CheckExact(k)) {
5789 k = PyTuple_GET_ITEM(k, 1);
5790 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005792 assert(i < size);
5793 assert(i >= 0);
5794 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005795 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005796 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005797}
5798
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005799static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005800compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005802 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005803 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005804 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005805 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 if (ste->ste_nested)
5807 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005808 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005810 if (!ste->ste_generator && ste->ste_coroutine)
5811 flags |= CO_COROUTINE;
5812 if (ste->ste_generator && ste->ste_coroutine)
5813 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 if (ste->ste_varargs)
5815 flags |= CO_VARARGS;
5816 if (ste->ste_varkeywords)
5817 flags |= CO_VARKEYWORDS;
5818 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 /* (Only) inherit compilerflags in PyCF_MASK */
5821 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005822
Pablo Galindo90235812020-03-15 04:29:22 +00005823 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005824 ste->ste_coroutine &&
5825 !ste->ste_generator) {
5826 flags |= CO_COROUTINE;
5827 }
5828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005829 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005830}
5831
INADA Naokic2e16072018-11-26 21:23:22 +09005832// Merge *tuple* with constant cache.
5833// Unlike merge_consts_recursive(), this function doesn't work recursively.
5834static int
5835merge_const_tuple(struct compiler *c, PyObject **tuple)
5836{
5837 assert(PyTuple_CheckExact(*tuple));
5838
5839 PyObject *key = _PyCode_ConstantKey(*tuple);
5840 if (key == NULL) {
5841 return 0;
5842 }
5843
5844 // t is borrowed reference
5845 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5846 Py_DECREF(key);
5847 if (t == NULL) {
5848 return 0;
5849 }
5850 if (t == key) { // tuple is new constant.
5851 return 1;
5852 }
5853
5854 PyObject *u = PyTuple_GET_ITEM(t, 1);
5855 Py_INCREF(u);
5856 Py_DECREF(*tuple);
5857 *tuple = u;
5858 return 1;
5859}
5860
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005861static PyCodeObject *
5862makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 PyObject *tmp;
5865 PyCodeObject *co = NULL;
5866 PyObject *consts = NULL;
5867 PyObject *names = NULL;
5868 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005869 PyObject *name = NULL;
5870 PyObject *freevars = NULL;
5871 PyObject *cellvars = NULL;
5872 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005873 Py_ssize_t nlocals;
5874 int nlocals_int;
5875 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005876 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005877
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005878 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 names = dict_keys_inorder(c->u->u_names, 0);
5880 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5881 if (!consts || !names || !varnames)
5882 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5885 if (!cellvars)
5886 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005887 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 if (!freevars)
5889 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005890
INADA Naokic2e16072018-11-26 21:23:22 +09005891 if (!merge_const_tuple(c, &names) ||
5892 !merge_const_tuple(c, &varnames) ||
5893 !merge_const_tuple(c, &cellvars) ||
5894 !merge_const_tuple(c, &freevars))
5895 {
5896 goto error;
5897 }
5898
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005899 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005900 assert(nlocals < INT_MAX);
5901 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 flags = compute_code_flags(c);
5904 if (flags < 0)
5905 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5908 if (!bytecode)
5909 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5912 if (!tmp)
5913 goto error;
5914 Py_DECREF(consts);
5915 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005916 if (!merge_const_tuple(c, &consts)) {
5917 goto error;
5918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005920 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005921 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005922 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005923 maxdepth = stackdepth(c);
5924 if (maxdepth < 0) {
5925 goto error;
5926 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005927 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005928 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005929 maxdepth, flags, bytecode, consts, names,
5930 varnames, freevars, cellvars, c->c_filename,
5931 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005932 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 Py_XDECREF(consts);
5934 Py_XDECREF(names);
5935 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 Py_XDECREF(name);
5937 Py_XDECREF(freevars);
5938 Py_XDECREF(cellvars);
5939 Py_XDECREF(bytecode);
5940 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005941}
5942
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005943
5944/* For debugging purposes only */
5945#if 0
5946static void
5947dump_instr(const struct instr *i)
5948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 const char *jrel = i->i_jrel ? "jrel " : "";
5950 const char *jabs = i->i_jabs ? "jabs " : "";
5951 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005954 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5958 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005959}
5960
5961static void
5962dump_basicblock(const basicblock *b)
5963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005964 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005965 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5966 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (b->b_instr) {
5968 int i;
5969 for (i = 0; i < b->b_iused; i++) {
5970 fprintf(stderr, " [%02d] ", i);
5971 dump_instr(b->b_instr + i);
5972 }
5973 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005974}
5975#endif
5976
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005977static PyCodeObject *
5978assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 basicblock *b, *entryblock;
5981 struct assembler a;
5982 int i, j, nblocks;
5983 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 /* Make sure every block that falls off the end returns None.
5986 XXX NEXT_BLOCK() isn't quite right, because if the last
5987 block ends with a jump or return b_next shouldn't set.
5988 */
5989 if (!c->u->u_curblock->b_return) {
5990 NEXT_BLOCK(c);
5991 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005992 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 ADDOP(c, RETURN_VALUE);
5994 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 nblocks = 0;
5997 entryblock = NULL;
5998 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5999 nblocks++;
6000 entryblock = b;
6001 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 /* Set firstlineno if it wasn't explicitly set. */
6004 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006005 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6007 else
6008 c->u->u_firstlineno = 1;
6009 }
6010 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6011 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006012 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 /* Can't modify the bytecode after computing jump offsets. */
6015 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006016
T. Wouters99b54d62019-09-12 07:05:33 -07006017 /* Emit code in reverse postorder from dfs. */
Pablo Galindo60eb9f12020-06-28 01:55:47 +01006018 for (i = 0; i < a.a_nblocks; i++) {
6019 b = a.a_reverse_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006020 for (j = 0; j < b->b_iused; j++)
6021 if (!assemble_emit(&a, &b->b_instr[j]))
6022 goto error;
6023 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006025 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6026 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006027 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006028 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006031 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006032 assemble_free(&a);
6033 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006034}
Georg Brandl8334fd92010-12-04 10:26:46 +00006035
6036#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006037PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006038PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6039 PyArena *arena)
6040{
6041 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6042}