blob: d98cabae6a72a560d1766296fa919e3dbf9e9e6b [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Victor Stinnerc96be812019-05-14 17:34:56 +020026#include "pycore_pystate.h" /* _PyInterpreterState_GET_UNSAFE() */
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Pablo Galindo90235812020-03-15 04:29:22 +000044#define IS_TOP_LEVEL_AWAIT(c) ( \
45 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
46 && (c->u->u_ste->ste_type == ModuleBlock))
47
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000048struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 unsigned i_jabs : 1;
50 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 /* Each basicblock in a compilation unit is linked via b_list in the
59 reverse order that the block are allocated. b_list points to the next
60 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 struct basicblock_ *b_list;
62 /* number of instructions used */
63 int b_iused;
64 /* length of instruction array (b_instr) */
65 int b_ialloc;
66 /* pointer to an array of instructions, initially NULL */
67 struct instr *b_instr;
68 /* If b_next is non-NULL, it is a pointer to the next
69 block reached by normal control flow. */
70 struct basicblock_ *b_next;
71 /* b_seen is used to perform a DFS of basicblocks. */
72 unsigned b_seen : 1;
73 /* b_return is true if a RETURN_VALUE opcode is inserted. */
74 unsigned b_return : 1;
75 /* depth of stack upon entry of block, computed by stackdepth() */
76 int b_startdepth;
77 /* instruction offset for block, computed by assemble_jump_offsets() */
78 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000079} basicblock;
80
81/* fblockinfo tracks the current frame block.
82
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083A frame block is used to handle loops, try/except, and try/finally.
84It's called a frame block to distinguish it from a basic block in the
85compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000086*/
87
Mark Shannonfee55262019-11-21 09:11:43 +000088enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
89 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000090
91struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 enum fblocktype fb_type;
93 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020094 /* (optional) type-specific exit or cleanup block */
95 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000096 /* (optional) additional information required for unwinding */
97 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000098};
99
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100100enum {
101 COMPILER_SCOPE_MODULE,
102 COMPILER_SCOPE_CLASS,
103 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400104 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400105 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 COMPILER_SCOPE_COMPREHENSION,
107};
108
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109/* The following items change on entry and exit of code blocks.
110 They must be saved and restored when returning to a block.
111*/
112struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400116 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100117 int u_scope_type;
118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 /* The following fields are dicts that map objects to
120 the index of them in co_XXX. The index is used as
121 the argument for opcodes that refer to those collections.
122 */
123 PyObject *u_consts; /* all constants */
124 PyObject *u_names; /* all names */
125 PyObject *u_varnames; /* local variables */
126 PyObject *u_cellvars; /* cell variables */
127 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Victor Stinnerf8e32212013-11-19 23:56:34 +0100131 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100132 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100133 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 /* Pointer to the most recently allocated block. By following b_list
135 members, you can reach all early allocated blocks. */
136 basicblock *u_blocks;
137 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 int u_nfblocks;
140 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 int u_firstlineno; /* the first lineno of the block */
143 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000144 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000151managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000152
153Note that we don't track recursion levels during compilation - the
154task of detecting and rejecting excessive levels of nesting is
155handled by the symbol analysis pass.
156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157*/
158
159struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200160 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct symtable *c_st;
162 PyFutureFeatures *c_future; /* pointer to module's __future__ */
163 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164
Georg Brandl8334fd92010-12-04 10:26:46 +0000165 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 int c_interactive; /* true if in interactive mode */
167 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100168 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
169 if this value is different from zero.
170 This can be used to temporarily visit
171 nodes without emitting bytecode to
172 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
INADA Naokic2e16072018-11-26 21:23:22 +0900174 PyObject *c_const_cache; /* Python dict holding all constants,
175 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 struct compiler_unit *u; /* compiler state for current block */
177 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
178 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179};
180
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100181static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000182static void compiler_free(struct compiler *);
183static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500184static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100186static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200189static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
191
192static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
193static int compiler_visit_stmt(struct compiler *, stmt_ty);
194static int compiler_visit_keyword(struct compiler *, keyword_ty);
195static int compiler_visit_expr(struct compiler *, expr_ty);
196static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700197static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200198static int compiler_subscript(struct compiler *, expr_ty);
199static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200
Andy Lester76d58772020-03-10 21:18:12 -0500201static int inplace_binop(operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800202static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200203static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500205static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400206static int compiler_async_with(struct compiler *, stmt_ty, int);
207static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100208static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400210 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500211static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400212static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000213
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700214static int compiler_sync_comprehension_generator(
215 struct compiler *c,
216 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200217 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700218 expr_ty elt, expr_ty val, int type);
219
220static int compiler_async_comprehension_generator(
221 struct compiler *c,
222 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200223 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700224 expr_ty elt, expr_ty val, int type);
225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000227static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400229#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000231PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 /* Name mangling: __private becomes _classname__private.
235 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 PyObject *result;
237 size_t nlen, plen, ipriv;
238 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200240 PyUnicode_READ_CHAR(ident, 0) != '_' ||
241 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_INCREF(ident);
243 return ident;
244 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 nlen = PyUnicode_GET_LENGTH(ident);
246 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 The only time a name with a dot can occur is when
250 we are compiling an import statement that has a
251 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 TODO(jhylton): Decide whether we want to support
254 mangling of the module name, e.g. __M.X.
255 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
257 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
258 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Py_INCREF(ident);
260 return ident; /* Don't mangle __whatever__ */
261 }
262 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 ipriv = 0;
264 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
265 ipriv++;
266 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(ident);
268 return ident; /* Don't mangle if class is just underscores */
269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200270 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000271
Antoine Pitrou55bff892013-04-06 21:21:04 +0200272 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
273 PyErr_SetString(PyExc_OverflowError,
274 "private identifier too large to be mangled");
275 return NULL;
276 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200278 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
279 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
280 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
281
282 result = PyUnicode_New(1 + nlen + plen, maxchar);
283 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
286 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200287 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
288 Py_DECREF(result);
289 return NULL;
290 }
291 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
292 Py_DECREF(result);
293 return NULL;
294 }
Victor Stinner8f825062012-04-27 13:55:39 +0200295 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200296 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000297}
298
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299static int
300compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000303
INADA Naokic2e16072018-11-26 21:23:22 +0900304 c->c_const_cache = PyDict_New();
305 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900307 }
308
309 c->c_stack = PyList_New(0);
310 if (!c->c_stack) {
311 Py_CLEAR(c->c_const_cache);
312 return 0;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316}
317
318PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200319PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
320 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 struct compiler c;
323 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200324 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 int merged;
Victor Stinner331a6a52019-05-27 16:39:22 +0200326 PyConfig *config = &_PyInterpreterState_GET_UNSAFE()->config;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (!__doc__) {
329 __doc__ = PyUnicode_InternFromString("__doc__");
330 if (!__doc__)
331 return NULL;
332 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000333 if (!__annotations__) {
334 __annotations__ = PyUnicode_InternFromString("__annotations__");
335 if (!__annotations__)
336 return NULL;
337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (!compiler_init(&c))
339 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200340 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 c.c_filename = filename;
342 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200343 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (c.c_future == NULL)
345 goto finally;
346 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 flags = &local_flags;
348 }
349 merged = c.c_future->ff_features | flags->cf_flags;
350 c.c_future->ff_features = merged;
351 flags->cf_flags = merged;
352 c.c_flags = flags;
Victor Stinnerc96be812019-05-14 17:34:56 +0200353 c.c_optimize = (optimize == -1) ? config->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100355 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200357 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
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
391PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392PyNode_Compile(struct _node *n, const char *filename)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 PyCodeObject *co = NULL;
395 mod_ty mod;
396 PyArena *arena = PyArena_New();
397 if (!arena)
398 return NULL;
399 mod = PyAST_FromNode(n, NULL, filename, arena);
400 if (mod)
401 co = PyAST_Compile(mod, filename, NULL, arena);
402 PyArena_Free(arena);
403 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000404}
405
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000406static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (c->c_st)
410 PySymtable_Free(c->c_st);
411 if (c->c_future)
412 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200413 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900414 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000416}
417
Guido van Rossum79f25d91997-04-29 20:08:16 +0000418static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_ssize_t i, n;
422 PyObject *v, *k;
423 PyObject *dict = PyDict_New();
424 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 n = PyList_Size(list);
427 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (!v) {
430 Py_DECREF(dict);
431 return NULL;
432 }
433 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300434 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_DECREF(v);
436 Py_DECREF(dict);
437 return NULL;
438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_DECREF(v);
440 }
441 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000442}
443
444/* Return new dict containing names from src that match scope(s).
445
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000446src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000448values are integers, starting at offset and increasing by one for
449each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450*/
451
452static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100453dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700455 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500457 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 assert(offset >= 0);
460 if (dest == NULL)
461 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462
Meador Inge2ca63152012-07-18 14:20:11 -0500463 /* Sort the keys so that we have a deterministic order on the indexes
464 saved in the returned dictionary. These indexes are used as indexes
465 into the free and cell var storage. Therefore if they aren't
466 deterministic, then the generated bytecode is not deterministic.
467 */
468 sorted_keys = PyDict_Keys(src);
469 if (sorted_keys == NULL)
470 return NULL;
471 if (PyList_Sort(sorted_keys) != 0) {
472 Py_DECREF(sorted_keys);
473 return NULL;
474 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500475 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500476
477 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* XXX this should probably be a macro in symtable.h */
479 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500480 k = PyList_GET_ITEM(sorted_keys, key_i);
481 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 assert(PyLong_Check(v));
483 vi = PyLong_AS_LONG(v);
484 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300487 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500489 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 Py_DECREF(dest);
491 return NULL;
492 }
493 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300494 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500495 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 Py_DECREF(item);
497 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return NULL;
499 }
500 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 }
502 }
Meador Inge2ca63152012-07-18 14:20:11 -0500503 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000505}
506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507static void
508compiler_unit_check(struct compiler_unit *u)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 basicblock *block;
511 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700512 assert((uintptr_t)block != 0xcbcbcbcbU);
513 assert((uintptr_t)block != 0xfbfbfbfbU);
514 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (block->b_instr != NULL) {
516 assert(block->b_ialloc > 0);
517 assert(block->b_iused > 0);
518 assert(block->b_ialloc >= block->b_iused);
519 }
520 else {
521 assert (block->b_iused == 0);
522 assert (block->b_ialloc == 0);
523 }
524 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525}
526
527static void
528compiler_unit_free(struct compiler_unit *u)
529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 compiler_unit_check(u);
533 b = u->u_blocks;
534 while (b != NULL) {
535 if (b->b_instr)
536 PyObject_Free((void *)b->b_instr);
537 next = b->b_list;
538 PyObject_Free((void *)b);
539 b = next;
540 }
541 Py_CLEAR(u->u_ste);
542 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400543 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Py_CLEAR(u->u_consts);
545 Py_CLEAR(u->u_names);
546 Py_CLEAR(u->u_varnames);
547 Py_CLEAR(u->u_freevars);
548 Py_CLEAR(u->u_cellvars);
549 Py_CLEAR(u->u_private);
550 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000551}
552
553static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100554compiler_enter_scope(struct compiler *c, identifier name,
555 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100558 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
561 struct compiler_unit));
562 if (!u) {
563 PyErr_NoMemory();
564 return 0;
565 }
566 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100567 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100569 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 u->u_kwonlyargcount = 0;
571 u->u_ste = PySymtable_Lookup(c->c_st, key);
572 if (!u->u_ste) {
573 compiler_unit_free(u);
574 return 0;
575 }
576 Py_INCREF(name);
577 u->u_name = name;
578 u->u_varnames = list2dict(u->u_ste->ste_varnames);
579 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
580 if (!u->u_varnames || !u->u_cellvars) {
581 compiler_unit_free(u);
582 return 0;
583 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000585 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500586 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300587 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 int res;
589 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200590 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500591 name = _PyUnicode_FromId(&PyId___class__);
592 if (!name) {
593 compiler_unit_free(u);
594 return 0;
595 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300596 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500597 if (res < 0) {
598 compiler_unit_free(u);
599 return 0;
600 }
601 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200604 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (!u->u_freevars) {
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_blocks = NULL;
611 u->u_nfblocks = 0;
612 u->u_firstlineno = lineno;
613 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000614 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 u->u_consts = PyDict_New();
616 if (!u->u_consts) {
617 compiler_unit_free(u);
618 return 0;
619 }
620 u->u_names = PyDict_New();
621 if (!u->u_names) {
622 compiler_unit_free(u);
623 return 0;
624 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* Push the old compiler_unit on the stack. */
629 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400630 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
632 Py_XDECREF(capsule);
633 compiler_unit_free(u);
634 return 0;
635 }
636 Py_DECREF(capsule);
637 u->u_private = c->u->u_private;
638 Py_XINCREF(u->u_private);
639 }
640 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100643
644 block = compiler_new_block(c);
645 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100647 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400649 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
650 if (!compiler_set_qualname(c))
651 return 0;
652 }
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000655}
656
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000657static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658compiler_exit_scope(struct compiler *c)
659{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100660 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 c->c_nestlevel--;
664 compiler_unit_free(c->u);
665 /* Restore c->u to the parent unit. */
666 n = PyList_GET_SIZE(c->c_stack) - 1;
667 if (n >= 0) {
668 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400669 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 assert(c->u);
671 /* we are deleting from a list so this really shouldn't fail */
672 if (PySequence_DelItem(c->c_stack, n) < 0)
673 Py_FatalError("compiler_exit_scope()");
674 compiler_unit_check(c->u);
675 }
676 else
677 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679}
680
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681static int
682compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100683{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100684 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685 _Py_static_string(dot_locals, ".<locals>");
686 Py_ssize_t stack_size;
687 struct compiler_unit *u = c->u;
688 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100689
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100691 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400692 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 if (stack_size > 1) {
694 int scope, force_global = 0;
695 struct compiler_unit *parent;
696 PyObject *mangled, *capsule;
697
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400698 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400699 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 assert(parent);
701
Yury Selivanov75445082015-05-11 22:57:16 -0400702 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
703 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
704 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 assert(u->u_name);
706 mangled = _Py_Mangle(parent->u_private, u->u_name);
707 if (!mangled)
708 return 0;
709 scope = PyST_GetScope(parent->u_ste, mangled);
710 Py_DECREF(mangled);
711 assert(scope != GLOBAL_IMPLICIT);
712 if (scope == GLOBAL_EXPLICIT)
713 force_global = 1;
714 }
715
716 if (!force_global) {
717 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400718 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
720 dot_locals_str = _PyUnicode_FromId(&dot_locals);
721 if (dot_locals_str == NULL)
722 return 0;
723 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
724 if (base == NULL)
725 return 0;
726 }
727 else {
728 Py_INCREF(parent->u_qualname);
729 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400730 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100731 }
732 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400733
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 if (base != NULL) {
735 dot_str = _PyUnicode_FromId(&dot);
736 if (dot_str == NULL) {
737 Py_DECREF(base);
738 return 0;
739 }
740 name = PyUnicode_Concat(base, dot_str);
741 Py_DECREF(base);
742 if (name == NULL)
743 return 0;
744 PyUnicode_Append(&name, u->u_name);
745 if (name == NULL)
746 return 0;
747 }
748 else {
749 Py_INCREF(u->u_name);
750 name = u->u_name;
751 }
752 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100753
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400754 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100755}
756
Eric V. Smith235a6f02015-09-19 14:51:32 -0400757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758/* Allocate a new block and return a pointer to it.
759 Returns NULL on error.
760*/
761
762static basicblock *
763compiler_new_block(struct compiler *c)
764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 basicblock *b;
766 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 u = c->u;
769 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
770 if (b == NULL) {
771 PyErr_NoMemory();
772 return NULL;
773 }
774 memset((void *)b, 0, sizeof(basicblock));
775 /* Extend the singly linked list of blocks with new block. */
776 b->b_list = u->u_blocks;
777 u->u_blocks = b;
778 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782compiler_next_block(struct compiler *c)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 basicblock *block = compiler_new_block(c);
785 if (block == NULL)
786 return NULL;
787 c->u->u_curblock->b_next = block;
788 c->u->u_curblock = block;
789 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790}
791
792static basicblock *
793compiler_use_next_block(struct compiler *c, basicblock *block)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(block != NULL);
796 c->u->u_curblock->b_next = block;
797 c->u->u_curblock = block;
798 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799}
800
801/* Returns the offset of the next instruction in the current block's
802 b_instr array. Resizes the b_instr as necessary.
803 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000805
806static int
Andy Lester76d58772020-03-10 21:18:12 -0500807compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(b != NULL);
810 if (b->b_instr == NULL) {
811 b->b_instr = (struct instr *)PyObject_Malloc(
812 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
813 if (b->b_instr == NULL) {
814 PyErr_NoMemory();
815 return -1;
816 }
817 b->b_ialloc = DEFAULT_BLOCK_SIZE;
818 memset((char *)b->b_instr, 0,
819 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
820 }
821 else if (b->b_iused == b->b_ialloc) {
822 struct instr *tmp;
823 size_t oldsize, newsize;
824 oldsize = b->b_ialloc * sizeof(struct instr);
825 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000826
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700827 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyErr_NoMemory();
829 return -1;
830 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (newsize == 0) {
833 PyErr_NoMemory();
834 return -1;
835 }
836 b->b_ialloc <<= 1;
837 tmp = (struct instr *)PyObject_Realloc(
838 (void *)b->b_instr, newsize);
839 if (tmp == NULL) {
840 PyErr_NoMemory();
841 return -1;
842 }
843 b->b_instr = tmp;
844 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
845 }
846 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847}
848
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200849/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850
Christian Heimes2202f872008-02-06 14:31:34 +0000851 The line number is reset in the following cases:
852 - when entering a new scope
853 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200854 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200855 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000856*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200858#define SET_LOC(c, x) \
859 (c)->u->u_lineno = (x)->lineno; \
860 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200862/* Return the stack effect of opcode with argument oparg.
863
864 Some opcodes have different stack effect when jump to the target and
865 when not jump. The 'jump' parameter specifies the case:
866
867 * 0 -- when not jump
868 * 1 -- when jump
869 * -1 -- maximal
870 */
871/* XXX Make the stack effect of WITH_CLEANUP_START and
872 WITH_CLEANUP_FINISH deterministic. */
873static int
874stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300877 case NOP:
878 case EXTENDED_ARG:
879 return 0;
880
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200881 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case POP_TOP:
883 return -1;
884 case ROT_TWO:
885 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200886 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return 0;
888 case DUP_TOP:
889 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000890 case DUP_TOP_TWO:
891 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000892
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200893 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case UNARY_POSITIVE:
895 case UNARY_NEGATIVE:
896 case UNARY_NOT:
897 case UNARY_INVERT:
898 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 case SET_ADD:
901 case LIST_APPEND:
902 return -1;
903 case MAP_ADD:
904 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000905
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200906 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_POWER:
908 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400909 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case BINARY_MODULO:
911 case BINARY_ADD:
912 case BINARY_SUBTRACT:
913 case BINARY_SUBSCR:
914 case BINARY_FLOOR_DIVIDE:
915 case BINARY_TRUE_DIVIDE:
916 return -1;
917 case INPLACE_FLOOR_DIVIDE:
918 case INPLACE_TRUE_DIVIDE:
919 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case INPLACE_ADD:
922 case INPLACE_SUBTRACT:
923 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400924 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_MODULO:
926 return -1;
927 case STORE_SUBSCR:
928 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case DELETE_SUBSCR:
930 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case BINARY_LSHIFT:
933 case BINARY_RSHIFT:
934 case BINARY_AND:
935 case BINARY_XOR:
936 case BINARY_OR:
937 return -1;
938 case INPLACE_POWER:
939 return -1;
940 case GET_ITER:
941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case PRINT_EXPR:
944 return -1;
945 case LOAD_BUILD_CLASS:
946 return 1;
947 case INPLACE_LSHIFT:
948 case INPLACE_RSHIFT:
949 case INPLACE_AND:
950 case INPLACE_XOR:
951 case INPLACE_OR:
952 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 /* 1 in the normal flow.
956 * Restore the stack position and push 6 values before jumping to
957 * the handler if an exception be raised. */
958 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case RETURN_VALUE:
960 return -1;
961 case IMPORT_STAR:
962 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700963 case SETUP_ANNOTATIONS:
964 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 case YIELD_VALUE:
966 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500967 case YIELD_FROM:
968 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case POP_BLOCK:
970 return 0;
971 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200972 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 case STORE_NAME:
975 return -1;
976 case DELETE_NAME:
977 return 0;
978 case UNPACK_SEQUENCE:
979 return oparg-1;
980 case UNPACK_EX:
981 return (oparg&0xFF) + (oparg>>8);
982 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200983 /* -1 at end of iterator, 1 if continue iterating. */
984 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case STORE_ATTR:
987 return -2;
988 case DELETE_ATTR:
989 return -1;
990 case STORE_GLOBAL:
991 return -1;
992 case DELETE_GLOBAL:
993 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 case LOAD_CONST:
995 return 1;
996 case LOAD_NAME:
997 return 1;
998 case BUILD_TUPLE:
999 case BUILD_LIST:
1000 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001001 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return 1-oparg;
1003 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001004 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001005 case BUILD_CONST_KEY_MAP:
1006 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case LOAD_ATTR:
1008 return 0;
1009 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001010 case IS_OP:
1011 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001013 case JUMP_IF_NOT_EXC_MATCH:
1014 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 case IMPORT_NAME:
1016 return -1;
1017 case IMPORT_FROM:
1018 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001020 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case JUMP_ABSOLUTE:
1023 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001024
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001025 case JUMP_IF_TRUE_OR_POP:
1026 case JUMP_IF_FALSE_OR_POP:
1027 return jump ? 0 : -1;
1028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 case POP_JUMP_IF_FALSE:
1030 case POP_JUMP_IF_TRUE:
1031 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case LOAD_GLOBAL:
1034 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001036 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001038 /* 0 in the normal flow.
1039 * Restore the stack position and push 6 values before jumping to
1040 * the handler if an exception be raised. */
1041 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001042 case RERAISE:
1043 return -3;
1044
1045 case WITH_EXCEPT_START:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 case LOAD_FAST:
1049 return 1;
1050 case STORE_FAST:
1051 return -1;
1052 case DELETE_FAST:
1053 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case RAISE_VARARGS:
1056 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001057
1058 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001060 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001061 case CALL_METHOD:
1062 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001064 return -oparg-1;
1065 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001066 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001067 case MAKE_FUNCTION:
1068 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1069 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 case BUILD_SLICE:
1071 if (oparg == 3)
1072 return -2;
1073 else
1074 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001076 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 case LOAD_CLOSURE:
1078 return 1;
1079 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001080 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 return 1;
1082 case STORE_DEREF:
1083 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001084 case DELETE_DEREF:
1085 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001086
1087 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001088 case GET_AWAITABLE:
1089 return 0;
1090 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001091 /* 0 in the normal flow.
1092 * Restore the stack position to the position before the result
1093 * of __aenter__ and push 6 values before jumping to the handler
1094 * if an exception be raised. */
1095 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001096 case BEFORE_ASYNC_WITH:
1097 return 1;
1098 case GET_AITER:
1099 return 0;
1100 case GET_ANEXT:
1101 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001102 case GET_YIELD_FROM_ITER:
1103 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001104 case END_ASYNC_FOR:
1105 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001106 case FORMAT_VALUE:
1107 /* If there's a fmt_spec on the stack, we go from 2->1,
1108 else 1->1. */
1109 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001110 case LOAD_METHOD:
1111 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001112 case LOAD_ASSERTION_ERROR:
1113 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001114 case LIST_TO_TUPLE:
1115 return 0;
1116 case LIST_EXTEND:
1117 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001118 case DICT_MERGE:
1119 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001120 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001122 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 }
Larry Hastings3a907972013-11-23 14:49:22 -08001124 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125}
1126
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001127int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001128PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1129{
1130 return stack_effect(opcode, oparg, jump);
1131}
1132
1133int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001134PyCompile_OpcodeStackEffect(int opcode, int oparg)
1135{
1136 return stack_effect(opcode, oparg, -1);
1137}
1138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139/* Add an opcode with no argument.
1140 Returns 0 on failure, 1 on success.
1141*/
1142
1143static int
1144compiler_addop(struct compiler *c, int opcode)
1145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 basicblock *b;
1147 struct instr *i;
1148 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001149 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001150 if (c->c_do_not_emit_bytecode) {
1151 return 1;
1152 }
Andy Lester76d58772020-03-10 21:18:12 -05001153 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (off < 0)
1155 return 0;
1156 b = c->u->u_curblock;
1157 i = &b->b_instr[off];
1158 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001159 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (opcode == RETURN_VALUE)
1161 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001162 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Victor Stinnerf8e32212013-11-19 23:56:34 +01001166static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001167compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001169 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001174 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001176 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001177 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001178 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return -1;
1181 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
1184 return -1;
1185 }
1186 Py_DECREF(v);
1187 }
1188 else
1189 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001190 return arg;
1191}
1192
INADA Naokic2e16072018-11-26 21:23:22 +09001193// Merge const *o* recursively and return constant key object.
1194static PyObject*
1195merge_consts_recursive(struct compiler *c, PyObject *o)
1196{
1197 // None and Ellipsis are singleton, and key is the singleton.
1198 // No need to merge object and key.
1199 if (o == Py_None || o == Py_Ellipsis) {
1200 Py_INCREF(o);
1201 return o;
1202 }
1203
1204 PyObject *key = _PyCode_ConstantKey(o);
1205 if (key == NULL) {
1206 return NULL;
1207 }
1208
1209 // t is borrowed reference
1210 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1211 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001212 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001213 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001214 Py_DECREF(key);
1215 return t;
1216 }
1217
INADA Naokif7e4d362018-11-29 00:58:46 +09001218 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001219 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001221 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 Py_ssize_t len = PyTuple_GET_SIZE(o);
1223 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001224 PyObject *item = PyTuple_GET_ITEM(o, i);
1225 PyObject *u = merge_consts_recursive(c, item);
1226 if (u == NULL) {
1227 Py_DECREF(key);
1228 return NULL;
1229 }
1230
1231 // See _PyCode_ConstantKey()
1232 PyObject *v; // borrowed
1233 if (PyTuple_CheckExact(u)) {
1234 v = PyTuple_GET_ITEM(u, 1);
1235 }
1236 else {
1237 v = u;
1238 }
1239 if (v != item) {
1240 Py_INCREF(v);
1241 PyTuple_SET_ITEM(o, i, v);
1242 Py_DECREF(item);
1243 }
1244
1245 Py_DECREF(u);
1246 }
1247 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001248 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001249 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001250 // constant keys.
1251 // See _PyCode_ConstantKey() for detail.
1252 assert(PyTuple_CheckExact(key));
1253 assert(PyTuple_GET_SIZE(key) == 2);
1254
1255 Py_ssize_t len = PySet_GET_SIZE(o);
1256 if (len == 0) { // empty frozenset should not be re-created.
1257 return key;
1258 }
1259 PyObject *tuple = PyTuple_New(len);
1260 if (tuple == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264 Py_ssize_t i = 0, pos = 0;
1265 PyObject *item;
1266 Py_hash_t hash;
1267 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1268 PyObject *k = merge_consts_recursive(c, item);
1269 if (k == NULL) {
1270 Py_DECREF(tuple);
1271 Py_DECREF(key);
1272 return NULL;
1273 }
1274 PyObject *u;
1275 if (PyTuple_CheckExact(k)) {
1276 u = PyTuple_GET_ITEM(k, 1);
1277 Py_INCREF(u);
1278 Py_DECREF(k);
1279 }
1280 else {
1281 u = k;
1282 }
1283 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1284 i++;
1285 }
1286
1287 // Instead of rewriting o, we create new frozenset and embed in the
1288 // key tuple. Caller should get merged frozenset from the key tuple.
1289 PyObject *new = PyFrozenSet_New(tuple);
1290 Py_DECREF(tuple);
1291 if (new == NULL) {
1292 Py_DECREF(key);
1293 return NULL;
1294 }
1295 assert(PyTuple_GET_ITEM(key, 1) == o);
1296 Py_DECREF(o);
1297 PyTuple_SET_ITEM(key, 1, new);
1298 }
INADA Naokic2e16072018-11-26 21:23:22 +09001299
1300 return key;
1301}
1302
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001303static Py_ssize_t
1304compiler_add_const(struct compiler *c, PyObject *o)
1305{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001306 if (c->c_do_not_emit_bytecode) {
1307 return 0;
1308 }
1309
INADA Naokic2e16072018-11-26 21:23:22 +09001310 PyObject *key = merge_consts_recursive(c, o);
1311 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001312 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001313 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001314
Andy Lester76d58772020-03-10 21:18:12 -05001315 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001316 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318}
1319
1320static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001321compiler_addop_load_const(struct compiler *c, PyObject *o)
1322{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001323 if (c->c_do_not_emit_bytecode) {
1324 return 1;
1325 }
1326
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001327 Py_ssize_t arg = compiler_add_const(c, o);
1328 if (arg < 0)
1329 return 0;
1330 return compiler_addop_i(c, LOAD_CONST, arg);
1331}
1332
1333static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001337 if (c->c_do_not_emit_bytecode) {
1338 return 1;
1339 }
1340
Andy Lester76d58772020-03-10 21:18:12 -05001341 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001343 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 return compiler_addop_i(c, opcode, arg);
1345}
1346
1347static int
1348compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001351 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001352
1353 if (c->c_do_not_emit_bytecode) {
1354 return 1;
1355 }
1356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1358 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001359 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001360 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361 Py_DECREF(mangled);
1362 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364 return compiler_addop_i(c, opcode, arg);
1365}
1366
1367/* Add an opcode with an integer argument.
1368 Returns 0 on failure, 1 on success.
1369*/
1370
1371static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001372compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 struct instr *i;
1375 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001376
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001377 if (c->c_do_not_emit_bytecode) {
1378 return 1;
1379 }
1380
Victor Stinner2ad474b2016-03-01 23:34:47 +01001381 /* oparg value is unsigned, but a signed C int is usually used to store
1382 it in the C code (like Python/ceval.c).
1383
1384 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1385
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001386 The argument of a concrete bytecode instruction is limited to 8-bit.
1387 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1388 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001389 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001390
Andy Lester76d58772020-03-10 21:18:12 -05001391 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (off < 0)
1393 return 0;
1394 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001395 i->i_opcode = opcode;
1396 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001397 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399}
1400
1401static int
1402compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 struct instr *i;
1405 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001407 if (c->c_do_not_emit_bytecode) {
1408 return 1;
1409 }
1410
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001411 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001413 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (off < 0)
1415 return 0;
1416 i = &c->u->u_curblock->b_instr[off];
1417 i->i_opcode = opcode;
1418 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (absolute)
1420 i->i_jabs = 1;
1421 else
1422 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001423 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425}
1426
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001427/* NEXT_BLOCK() creates an implicit jump from the current block
1428 to the new block.
1429
1430 The returns inside this macro make it impossible to decref objects
1431 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (compiler_next_block((C)) == NULL) \
1435 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436}
1437
1438#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 if (!compiler_addop((C), (OP))) \
1440 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441}
1442
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001443#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!compiler_addop((C), (OP))) { \
1445 compiler_exit_scope(c); \
1446 return 0; \
1447 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001448}
1449
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001450#define ADDOP_LOAD_CONST(C, O) { \
1451 if (!compiler_addop_load_const((C), (O))) \
1452 return 0; \
1453}
1454
1455/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1456#define ADDOP_LOAD_CONST_NEW(C, O) { \
1457 PyObject *__new_const = (O); \
1458 if (__new_const == NULL) { \
1459 return 0; \
1460 } \
1461 if (!compiler_addop_load_const((C), __new_const)) { \
1462 Py_DECREF(__new_const); \
1463 return 0; \
1464 } \
1465 Py_DECREF(__new_const); \
1466}
1467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1470 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001473/* Same as ADDOP_O, but steals a reference. */
1474#define ADDOP_N(C, OP, O, TYPE) { \
1475 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1476 Py_DECREF((O)); \
1477 return 0; \
1478 } \
1479 Py_DECREF((O)); \
1480}
1481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1484 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485}
1486
1487#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (!compiler_addop_i((C), (OP), (O))) \
1489 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490}
1491
1492#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!compiler_addop_j((C), (OP), (O), 1)) \
1494 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495}
1496
1497#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!compiler_addop_j((C), (OP), (O), 0)) \
1499 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
Mark Shannon9af0e472020-01-14 10:12:45 +00001502
1503#define ADDOP_COMPARE(C, CMP) { \
1504 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1505 return 0; \
1506}
1507
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1509 the ASDL name to synthesize the name of the C type and the visit function.
1510*/
1511
1512#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!compiler_visit_ ## TYPE((C), (V))) \
1514 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515}
1516
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001517#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_visit_ ## TYPE((C), (V))) { \
1519 compiler_exit_scope(c); \
1520 return 0; \
1521 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001522}
1523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_visit_slice((C), (V), (CTX))) \
1526 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527}
1528
1529#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 int _i; \
1531 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1532 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1533 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1534 if (!compiler_visit_ ## TYPE((C), elt)) \
1535 return 0; \
1536 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537}
1538
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001539#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 int _i; \
1541 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1542 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1543 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1544 if (!compiler_visit_ ## TYPE((C), elt)) { \
1545 compiler_exit_scope(c); \
1546 return 0; \
1547 } \
1548 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001549}
1550
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001551/* These macros allows to check only for errors and not emmit bytecode
1552 * while visiting nodes.
1553*/
1554
1555#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1556 c->c_do_not_emit_bytecode++;
1557
1558#define END_DO_NOT_EMIT_BYTECODE \
1559 c->c_do_not_emit_bytecode--; \
1560}
1561
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001562/* Search if variable annotations are present statically in a block. */
1563
1564static int
1565find_ann(asdl_seq *stmts)
1566{
1567 int i, j, res = 0;
1568 stmt_ty st;
1569
1570 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1571 st = (stmt_ty)asdl_seq_GET(stmts, i);
1572 switch (st->kind) {
1573 case AnnAssign_kind:
1574 return 1;
1575 case For_kind:
1576 res = find_ann(st->v.For.body) ||
1577 find_ann(st->v.For.orelse);
1578 break;
1579 case AsyncFor_kind:
1580 res = find_ann(st->v.AsyncFor.body) ||
1581 find_ann(st->v.AsyncFor.orelse);
1582 break;
1583 case While_kind:
1584 res = find_ann(st->v.While.body) ||
1585 find_ann(st->v.While.orelse);
1586 break;
1587 case If_kind:
1588 res = find_ann(st->v.If.body) ||
1589 find_ann(st->v.If.orelse);
1590 break;
1591 case With_kind:
1592 res = find_ann(st->v.With.body);
1593 break;
1594 case AsyncWith_kind:
1595 res = find_ann(st->v.AsyncWith.body);
1596 break;
1597 case Try_kind:
1598 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1599 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1600 st->v.Try.handlers, j);
1601 if (find_ann(handler->v.ExceptHandler.body)) {
1602 return 1;
1603 }
1604 }
1605 res = find_ann(st->v.Try.body) ||
1606 find_ann(st->v.Try.finalbody) ||
1607 find_ann(st->v.Try.orelse);
1608 break;
1609 default:
1610 res = 0;
1611 }
1612 if (res) {
1613 break;
1614 }
1615 }
1616 return res;
1617}
1618
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001619/*
1620 * Frame block handling functions
1621 */
1622
1623static int
1624compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001625 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001626{
1627 struct fblockinfo *f;
1628 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1629 PyErr_SetString(PyExc_SyntaxError,
1630 "too many statically nested blocks");
1631 return 0;
1632 }
1633 f = &c->u->u_fblock[c->u->u_nfblocks++];
1634 f->fb_type = t;
1635 f->fb_block = b;
1636 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001637 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001638 return 1;
1639}
1640
1641static void
1642compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1643{
1644 struct compiler_unit *u = c->u;
1645 assert(u->u_nfblocks > 0);
1646 u->u_nfblocks--;
1647 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1648 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1649}
1650
Mark Shannonfee55262019-11-21 09:11:43 +00001651static int
1652compiler_call_exit_with_nones(struct compiler *c) {
1653 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1654 ADDOP(c, DUP_TOP);
1655 ADDOP(c, DUP_TOP);
1656 ADDOP_I(c, CALL_FUNCTION, 3);
1657 return 1;
1658}
1659
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001661 * popping the blocks will be restored afterwards, unless another
1662 * return, break or continue is found. In which case, the TOS will
1663 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001664 */
1665static int
1666compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1667 int preserve_tos)
1668{
1669 switch (info->fb_type) {
1670 case WHILE_LOOP:
1671 return 1;
1672
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001673 case FOR_LOOP:
1674 /* Pop the iterator */
1675 if (preserve_tos) {
1676 ADDOP(c, ROT_TWO);
1677 }
1678 ADDOP(c, POP_TOP);
1679 return 1;
1680
1681 case EXCEPT:
1682 ADDOP(c, POP_BLOCK);
1683 return 1;
1684
1685 case FINALLY_TRY:
1686 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001687 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001688 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1689 return 0;
1690 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001691 }
Mark Shannon88dce262019-12-30 09:53:36 +00001692 /* Emit the finally block, restoring the line number when done */
1693 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001694 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001695 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001696 if (preserve_tos) {
1697 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001698 }
1699 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001700
Mark Shannonfee55262019-11-21 09:11:43 +00001701 case FINALLY_END:
1702 if (preserve_tos) {
1703 ADDOP(c, ROT_FOUR);
1704 }
1705 ADDOP(c, POP_TOP);
1706 ADDOP(c, POP_TOP);
1707 ADDOP(c, POP_TOP);
1708 if (preserve_tos) {
1709 ADDOP(c, ROT_FOUR);
1710 }
1711 ADDOP(c, POP_EXCEPT);
1712 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001713
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001714 case WITH:
1715 case ASYNC_WITH:
1716 ADDOP(c, POP_BLOCK);
1717 if (preserve_tos) {
1718 ADDOP(c, ROT_TWO);
1719 }
Mark Shannonfee55262019-11-21 09:11:43 +00001720 if(!compiler_call_exit_with_nones(c)) {
1721 return 0;
1722 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001723 if (info->fb_type == ASYNC_WITH) {
1724 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001725 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001726 ADDOP(c, YIELD_FROM);
1727 }
Mark Shannonfee55262019-11-21 09:11:43 +00001728 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001729 return 1;
1730
1731 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001732 if (info->fb_datum) {
1733 ADDOP(c, POP_BLOCK);
1734 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001735 if (preserve_tos) {
1736 ADDOP(c, ROT_FOUR);
1737 }
Mark Shannonfee55262019-11-21 09:11:43 +00001738 ADDOP(c, POP_EXCEPT);
1739 if (info->fb_datum) {
1740 ADDOP_LOAD_CONST(c, Py_None);
1741 compiler_nameop(c, info->fb_datum, Store);
1742 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001743 }
Mark Shannonfee55262019-11-21 09:11:43 +00001744 return 1;
1745
1746 case POP_VALUE:
1747 if (preserve_tos) {
1748 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 }
Mark Shannonfee55262019-11-21 09:11:43 +00001750 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001751 return 1;
1752 }
1753 Py_UNREACHABLE();
1754}
1755
Mark Shannonfee55262019-11-21 09:11:43 +00001756/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1757static int
1758compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1759 if (c->u->u_nfblocks == 0) {
1760 return 1;
1761 }
1762 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1763 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1764 *loop = top;
1765 return 1;
1766 }
1767 struct fblockinfo copy = *top;
1768 c->u->u_nfblocks--;
1769 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1770 return 0;
1771 }
1772 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1773 return 0;
1774 }
1775 c->u->u_fblock[c->u->u_nfblocks] = copy;
1776 c->u->u_nfblocks++;
1777 return 1;
1778}
1779
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001780/* Compile a sequence of statements, checking for a docstring
1781 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782
1783static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001784compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001786 int i = 0;
1787 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001788 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001789
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001790 /* Set current line number to the line number of first statement.
1791 This way line number for SETUP_ANNOTATIONS will always
1792 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301793 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001794 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001795 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001796 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001797 }
1798 /* Every annotated class and module should have __annotations__. */
1799 if (find_ann(stmts)) {
1800 ADDOP(c, SETUP_ANNOTATIONS);
1801 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001802 if (!asdl_seq_LEN(stmts))
1803 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001804 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001805 if (c->c_optimize < 2) {
1806 docstring = _PyAST_GetDocString(stmts);
1807 if (docstring) {
1808 i = 1;
1809 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1810 assert(st->kind == Expr_kind);
1811 VISIT(c, expr, st->v.Expr.value);
1812 if (!compiler_nameop(c, __doc__, Store))
1813 return 0;
1814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001816 for (; i < asdl_seq_LEN(stmts); i++)
1817 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819}
1820
1821static PyCodeObject *
1822compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyCodeObject *co;
1825 int addNone = 1;
1826 static PyObject *module;
1827 if (!module) {
1828 module = PyUnicode_InternFromString("<module>");
1829 if (!module)
1830 return NULL;
1831 }
1832 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001833 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 return NULL;
1835 switch (mod->kind) {
1836 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001837 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 compiler_exit_scope(c);
1839 return 0;
1840 }
1841 break;
1842 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001843 if (find_ann(mod->v.Interactive.body)) {
1844 ADDOP(c, SETUP_ANNOTATIONS);
1845 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 c->c_interactive = 1;
1847 VISIT_SEQ_IN_SCOPE(c, stmt,
1848 mod->v.Interactive.body);
1849 break;
1850 case Expression_kind:
1851 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1852 addNone = 0;
1853 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 default:
1855 PyErr_Format(PyExc_SystemError,
1856 "module kind %d should not be possible",
1857 mod->kind);
1858 return 0;
1859 }
1860 co = assemble(c, addNone);
1861 compiler_exit_scope(c);
1862 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001863}
1864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865/* The test for LOCAL must come before the test for FREE in order to
1866 handle classes where name is both local and free. The local var is
1867 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001868*/
1869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870static int
1871get_ref_type(struct compiler *c, PyObject *name)
1872{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001873 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001875 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001876 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001877 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (scope == 0) {
1879 char buf[350];
1880 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001881 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001883 PyUnicode_AsUTF8(name),
1884 PyUnicode_AsUTF8(c->u->u_name),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1887 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1888 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 );
1890 Py_FatalError(buf);
1891 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894}
1895
1896static int
1897compiler_lookup_arg(PyObject *dict, PyObject *name)
1898{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001899 PyObject *v;
1900 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001902 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001903 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904}
1905
1906static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001907compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001909 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001910 if (qualname == NULL)
1911 qualname = co->co_name;
1912
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 if (free) {
1914 for (i = 0; i < free; ++i) {
1915 /* Bypass com_addop_varname because it will generate
1916 LOAD_DEREF but LOAD_CLOSURE is needed.
1917 */
1918 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1919 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921 /* Special case: If a class contains a method with a
1922 free variable that has the same name as a method,
1923 the name will be considered free *and* local in the
1924 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001925 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001926 */
1927 reftype = get_ref_type(c, name);
1928 if (reftype == CELL)
1929 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1930 else /* (reftype == FREE) */
1931 arg = compiler_lookup_arg(c->u->u_freevars, name);
1932 if (arg == -1) {
1933 fprintf(stderr,
1934 "lookup %s in %s %d %d\n"
1935 "freevars of %s: %s\n",
1936 PyUnicode_AsUTF8(PyObject_Repr(name)),
1937 PyUnicode_AsUTF8(c->u->u_name),
1938 reftype, arg,
1939 PyUnicode_AsUTF8(co->co_name),
1940 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1941 Py_FatalError("compiler_make_closure()");
1942 }
1943 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 flags |= 0x08;
1946 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001948 ADDOP_LOAD_CONST(c, (PyObject*)co);
1949 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001950 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952}
1953
1954static int
1955compiler_decorators(struct compiler *c, asdl_seq* decos)
1956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (!decos)
1960 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1963 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1964 }
1965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001969compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001971{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001972 /* Push a dict of keyword-only default values.
1973
1974 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1975 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001976 int i;
1977 PyObject *keys = NULL;
1978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1980 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1981 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1982 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001983 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001984 if (!mangled) {
1985 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 if (keys == NULL) {
1988 keys = PyList_New(1);
1989 if (keys == NULL) {
1990 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001991 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001992 }
1993 PyList_SET_ITEM(keys, 0, mangled);
1994 }
1995 else {
1996 int res = PyList_Append(keys, mangled);
1997 Py_DECREF(mangled);
1998 if (res == -1) {
1999 goto error;
2000 }
2001 }
2002 if (!compiler_visit_expr(c, default_)) {
2003 goto error;
2004 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
2006 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002007 if (keys != NULL) {
2008 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2009 PyObject *keys_tuple = PyList_AsTuple(keys);
2010 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002011 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002013 assert(default_count > 0);
2014 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 }
2016 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002017 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 }
2019
2020error:
2021 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002022 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002023}
2024
2025static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002026compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2027{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002028 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002029 return 1;
2030}
2031
2032static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002033compiler_visit_argannotation(struct compiler *c, identifier id,
2034 expr_ty annotation, PyObject *names)
2035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002037 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002038 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2039 VISIT(c, annexpr, annotation)
2040 }
2041 else {
2042 VISIT(c, expr, annotation);
2043 }
Victor Stinner065efc32014-02-18 22:07:56 +01002044 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002045 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002046 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002047 if (PyList_Append(names, mangled) < 0) {
2048 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002050 }
2051 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002053 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002054}
2055
2056static int
2057compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2058 PyObject *names)
2059{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 for (i = 0; i < asdl_seq_LEN(args); i++) {
2062 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 c,
2065 arg->arg,
2066 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 names))
2068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002070 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002071}
2072
2073static int
2074compiler_visit_annotations(struct compiler *c, arguments_ty args,
2075 expr_ty returns)
2076{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002077 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002078 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002079
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002080 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 */
2082 static identifier return_str;
2083 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002084 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 names = PyList_New(0);
2086 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002087 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002088
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002089 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002091 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2092 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002093 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002094 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002095 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002097 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002099 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002101 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (!return_str) {
2105 return_str = PyUnicode_InternFromString("return");
2106 if (!return_str)
2107 goto error;
2108 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002109 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 goto error;
2111 }
2112
2113 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002115 PyObject *keytuple = PyList_AsTuple(names);
2116 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002117 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002119 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002121 else {
2122 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002123 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002124 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002125
2126error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002128 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002129}
2130
2131static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002132compiler_visit_defaults(struct compiler *c, arguments_ty args)
2133{
2134 VISIT_SEQ(c, expr, args->defaults);
2135 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2136 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137}
2138
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139static Py_ssize_t
2140compiler_default_arguments(struct compiler *c, arguments_ty args)
2141{
2142 Py_ssize_t funcflags = 0;
2143 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002144 if (!compiler_visit_defaults(c, args))
2145 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002146 funcflags |= 0x01;
2147 }
2148 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002149 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002150 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002151 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002152 return -1;
2153 }
2154 else if (res > 0) {
2155 funcflags |= 0x02;
2156 }
2157 }
2158 return funcflags;
2159}
2160
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161static int
Yury Selivanov75445082015-05-11 22:57:16 -04002162compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002165 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002166 arguments_ty args;
2167 expr_ty returns;
2168 identifier name;
2169 asdl_seq* decos;
2170 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002171 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002172 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002173 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002174 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175
Yury Selivanov75445082015-05-11 22:57:16 -04002176 if (is_async) {
2177 assert(s->kind == AsyncFunctionDef_kind);
2178
2179 args = s->v.AsyncFunctionDef.args;
2180 returns = s->v.AsyncFunctionDef.returns;
2181 decos = s->v.AsyncFunctionDef.decorator_list;
2182 name = s->v.AsyncFunctionDef.name;
2183 body = s->v.AsyncFunctionDef.body;
2184
2185 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2186 } else {
2187 assert(s->kind == FunctionDef_kind);
2188
2189 args = s->v.FunctionDef.args;
2190 returns = s->v.FunctionDef.returns;
2191 decos = s->v.FunctionDef.decorator_list;
2192 name = s->v.FunctionDef.name;
2193 body = s->v.FunctionDef.body;
2194
2195 scope_type = COMPILER_SCOPE_FUNCTION;
2196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (!compiler_decorators(c, decos))
2199 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002200
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002201 firstlineno = s->lineno;
2202 if (asdl_seq_LEN(decos)) {
2203 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2204 }
2205
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002206 funcflags = compiler_default_arguments(c, args);
2207 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002209 }
2210
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002211 annotations = compiler_visit_annotations(c, args, returns);
2212 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002213 return 0;
2214 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002215 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002216 funcflags |= 0x04;
2217 }
2218
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002219 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002220 return 0;
2221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222
INADA Naokicb41b272017-02-23 00:31:59 +09002223 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002224 if (c->c_optimize < 2) {
2225 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002226 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002227 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 compiler_exit_scope(c);
2229 return 0;
2230 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002233 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002235 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002237 qualname = c->u->u_qualname;
2238 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002240 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002241 Py_XDECREF(qualname);
2242 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002244 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002246 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002247 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* decorators */
2251 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2252 ADDOP_I(c, CALL_FUNCTION, 1);
2253 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254
Yury Selivanov75445082015-05-11 22:57:16 -04002255 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256}
2257
2258static int
2259compiler_class(struct compiler *c, stmt_ty s)
2260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 PyCodeObject *co;
2262 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002263 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (!compiler_decorators(c, decos))
2267 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002268
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002269 firstlineno = s->lineno;
2270 if (asdl_seq_LEN(decos)) {
2271 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2272 }
2273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* ultimately generate code for:
2275 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2276 where:
2277 <func> is a function/closure created from the class body;
2278 it has a single argument (__locals__) where the dict
2279 (or MutableSequence) representing the locals is passed
2280 <name> is the class name
2281 <bases> is the positional arguments and *varargs argument
2282 <keywords> is the keyword arguments and **kwds argument
2283 This borrows from compiler_call.
2284 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002287 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002288 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 return 0;
2290 /* this block represents what we do in the new scope */
2291 {
2292 /* use the class name for name mangling */
2293 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002294 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* load (global) __name__ ... */
2296 str = PyUnicode_InternFromString("__name__");
2297 if (!str || !compiler_nameop(c, str, Load)) {
2298 Py_XDECREF(str);
2299 compiler_exit_scope(c);
2300 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 Py_DECREF(str);
2303 /* ... and store it as __module__ */
2304 str = PyUnicode_InternFromString("__module__");
2305 if (!str || !compiler_nameop(c, str, Store)) {
2306 Py_XDECREF(str);
2307 compiler_exit_scope(c);
2308 return 0;
2309 }
2310 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002311 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002312 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002313 str = PyUnicode_InternFromString("__qualname__");
2314 if (!str || !compiler_nameop(c, str, Store)) {
2315 Py_XDECREF(str);
2316 compiler_exit_scope(c);
2317 return 0;
2318 }
2319 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002321 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 compiler_exit_scope(c);
2323 return 0;
2324 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002325 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002326 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002327 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002328 str = PyUnicode_InternFromString("__class__");
2329 if (str == NULL) {
2330 compiler_exit_scope(c);
2331 return 0;
2332 }
2333 i = compiler_lookup_arg(c->u->u_cellvars, str);
2334 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002335 if (i < 0) {
2336 compiler_exit_scope(c);
2337 return 0;
2338 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002339 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002342 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002343 str = PyUnicode_InternFromString("__classcell__");
2344 if (!str || !compiler_nameop(c, str, Store)) {
2345 Py_XDECREF(str);
2346 compiler_exit_scope(c);
2347 return 0;
2348 }
2349 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002351 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002352 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002353 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002354 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002355 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* create the code object */
2358 co = assemble(c, 1);
2359 }
2360 /* leave the new scope */
2361 compiler_exit_scope(c);
2362 if (co == NULL)
2363 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* 2. load the 'build_class' function */
2366 ADDOP(c, LOAD_BUILD_CLASS);
2367
2368 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002369 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 Py_DECREF(co);
2371
2372 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002373 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374
2375 /* 5. generate the rest of the code for the call */
2376 if (!compiler_call_helper(c, 2,
2377 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002378 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 return 0;
2380
2381 /* 6. apply decorators */
2382 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2383 ADDOP_I(c, CALL_FUNCTION, 1);
2384 }
2385
2386 /* 7. store into <name> */
2387 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2388 return 0;
2389 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390}
2391
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002392/* Return 0 if the expression is a constant value except named singletons.
2393 Return 1 otherwise. */
2394static int
2395check_is_arg(expr_ty e)
2396{
2397 if (e->kind != Constant_kind) {
2398 return 1;
2399 }
2400 PyObject *value = e->v.Constant.value;
2401 return (value == Py_None
2402 || value == Py_False
2403 || value == Py_True
2404 || value == Py_Ellipsis);
2405}
2406
2407/* Check operands of identity chacks ("is" and "is not").
2408 Emit a warning if any operand is a constant except named singletons.
2409 Return 0 on error.
2410 */
2411static int
2412check_compare(struct compiler *c, expr_ty e)
2413{
2414 Py_ssize_t i, n;
2415 int left = check_is_arg(e->v.Compare.left);
2416 n = asdl_seq_LEN(e->v.Compare.ops);
2417 for (i = 0; i < n; i++) {
2418 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2419 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2420 if (op == Is || op == IsNot) {
2421 if (!right || !left) {
2422 const char *msg = (op == Is)
2423 ? "\"is\" with a literal. Did you mean \"==\"?"
2424 : "\"is not\" with a literal. Did you mean \"!=\"?";
2425 return compiler_warn(c, msg);
2426 }
2427 }
2428 left = right;
2429 }
2430 return 1;
2431}
2432
Mark Shannon9af0e472020-01-14 10:12:45 +00002433static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002434{
Mark Shannon9af0e472020-01-14 10:12:45 +00002435 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002436 switch (op) {
2437 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002438 cmp = Py_EQ;
2439 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002440 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002441 cmp = Py_NE;
2442 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002443 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002444 cmp = Py_LT;
2445 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002446 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002447 cmp = Py_LE;
2448 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002450 cmp = Py_GT;
2451 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002452 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002453 cmp = Py_GE;
2454 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002455 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002456 ADDOP_I(c, IS_OP, 0);
2457 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002458 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002459 ADDOP_I(c, IS_OP, 1);
2460 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 ADDOP_I(c, CONTAINS_OP, 0);
2463 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002464 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 ADDOP_I(c, CONTAINS_OP, 1);
2466 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002470 ADDOP_I(c, COMPARE_OP, cmp);
2471 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002472}
2473
Mark Shannon9af0e472020-01-14 10:12:45 +00002474
2475
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476static int
2477compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2478{
2479 switch (e->kind) {
2480 case UnaryOp_kind:
2481 if (e->v.UnaryOp.op == Not)
2482 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2483 /* fallback to general implementation */
2484 break;
2485 case BoolOp_kind: {
2486 asdl_seq *s = e->v.BoolOp.values;
2487 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2488 assert(n >= 0);
2489 int cond2 = e->v.BoolOp.op == Or;
2490 basicblock *next2 = next;
2491 if (!cond2 != !cond) {
2492 next2 = compiler_new_block(c);
2493 if (next2 == NULL)
2494 return 0;
2495 }
2496 for (i = 0; i < n; ++i) {
2497 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2498 return 0;
2499 }
2500 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2501 return 0;
2502 if (next2 != next)
2503 compiler_use_next_block(c, next2);
2504 return 1;
2505 }
2506 case IfExp_kind: {
2507 basicblock *end, *next2;
2508 end = compiler_new_block(c);
2509 if (end == NULL)
2510 return 0;
2511 next2 = compiler_new_block(c);
2512 if (next2 == NULL)
2513 return 0;
2514 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2515 return 0;
2516 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2517 return 0;
2518 ADDOP_JREL(c, JUMP_FORWARD, end);
2519 compiler_use_next_block(c, next2);
2520 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2521 return 0;
2522 compiler_use_next_block(c, end);
2523 return 1;
2524 }
2525 case Compare_kind: {
2526 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2527 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002528 if (!check_compare(c, e)) {
2529 return 0;
2530 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002531 basicblock *cleanup = compiler_new_block(c);
2532 if (cleanup == NULL)
2533 return 0;
2534 VISIT(c, expr, e->v.Compare.left);
2535 for (i = 0; i < n; i++) {
2536 VISIT(c, expr,
2537 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2538 ADDOP(c, DUP_TOP);
2539 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002540 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002541 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2542 NEXT_BLOCK(c);
2543 }
2544 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002545 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2547 basicblock *end = compiler_new_block(c);
2548 if (end == NULL)
2549 return 0;
2550 ADDOP_JREL(c, JUMP_FORWARD, end);
2551 compiler_use_next_block(c, cleanup);
2552 ADDOP(c, POP_TOP);
2553 if (!cond) {
2554 ADDOP_JREL(c, JUMP_FORWARD, next);
2555 }
2556 compiler_use_next_block(c, end);
2557 return 1;
2558 }
2559 /* fallback to general implementation */
2560 break;
2561 }
2562 default:
2563 /* fallback to general implementation */
2564 break;
2565 }
2566
2567 /* general implementation */
2568 VISIT(c, expr, e);
2569 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2570 return 1;
2571}
2572
2573static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002574compiler_ifexp(struct compiler *c, expr_ty e)
2575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 basicblock *end, *next;
2577
2578 assert(e->kind == IfExp_kind);
2579 end = compiler_new_block(c);
2580 if (end == NULL)
2581 return 0;
2582 next = compiler_new_block(c);
2583 if (next == NULL)
2584 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002585 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2586 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 VISIT(c, expr, e->v.IfExp.body);
2588 ADDOP_JREL(c, JUMP_FORWARD, end);
2589 compiler_use_next_block(c, next);
2590 VISIT(c, expr, e->v.IfExp.orelse);
2591 compiler_use_next_block(c, end);
2592 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002593}
2594
2595static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596compiler_lambda(struct compiler *c, expr_ty e)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002599 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002601 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 arguments_ty args = e->v.Lambda.args;
2603 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (!name) {
2606 name = PyUnicode_InternFromString("<lambda>");
2607 if (!name)
2608 return 0;
2609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002611 funcflags = compiler_default_arguments(c, args);
2612 if (funcflags == -1) {
2613 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002615
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002616 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002617 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 /* Make None the first constant, so the lambda can't have a
2621 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002622 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002626 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2628 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2629 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002630 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 }
2632 else {
2633 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002634 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002636 qualname = c->u->u_qualname;
2637 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002639 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002642 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002643 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 Py_DECREF(co);
2645
2646 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647}
2648
2649static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650compiler_if(struct compiler *c, stmt_ty s)
2651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 basicblock *end, *next;
2653 int constant;
2654 assert(s->kind == If_kind);
2655 end = compiler_new_block(c);
2656 if (end == NULL)
2657 return 0;
2658
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002659 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002660 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 * constant = 1: "if 1", "if 2", ...
2662 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002663 if (constant == 0) {
2664 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002666 END_DO_NOT_EMIT_BYTECODE
2667 if (s->v.If.orelse) {
2668 VISIT_SEQ(c, stmt, s->v.If.orelse);
2669 }
2670 } else if (constant == 1) {
2671 VISIT_SEQ(c, stmt, s->v.If.body);
2672 if (s->v.If.orelse) {
2673 BEGIN_DO_NOT_EMIT_BYTECODE
2674 VISIT_SEQ(c, stmt, s->v.If.orelse);
2675 END_DO_NOT_EMIT_BYTECODE
2676 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002678 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 next = compiler_new_block(c);
2680 if (next == NULL)
2681 return 0;
2682 }
Mark Shannonfee55262019-11-21 09:11:43 +00002683 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002685 }
2686 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002687 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002688 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002690 if (asdl_seq_LEN(s->v.If.orelse)) {
2691 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 compiler_use_next_block(c, next);
2693 VISIT_SEQ(c, stmt, s->v.If.orelse);
2694 }
2695 }
2696 compiler_use_next_block(c, end);
2697 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698}
2699
2700static int
2701compiler_for(struct compiler *c, stmt_ty s)
2702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 start = compiler_new_block(c);
2706 cleanup = compiler_new_block(c);
2707 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002708 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002710 }
2711 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 VISIT(c, expr, s->v.For.iter);
2715 ADDOP(c, GET_ITER);
2716 compiler_use_next_block(c, start);
2717 ADDOP_JREL(c, FOR_ITER, cleanup);
2718 VISIT(c, expr, s->v.For.target);
2719 VISIT_SEQ(c, stmt, s->v.For.body);
2720 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2721 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002722
2723 compiler_pop_fblock(c, FOR_LOOP, start);
2724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 VISIT_SEQ(c, stmt, s->v.For.orelse);
2726 compiler_use_next_block(c, end);
2727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728}
2729
Yury Selivanov75445082015-05-11 22:57:16 -04002730
2731static int
2732compiler_async_for(struct compiler *c, stmt_ty s)
2733{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002734 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002735 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002736 c->u->u_ste->ste_coroutine = 1;
2737 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002738 return compiler_error(c, "'async for' outside async function");
2739 }
2740
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002741 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002742 except = compiler_new_block(c);
2743 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002744
Mark Shannonfee55262019-11-21 09:11:43 +00002745 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002746 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002747 }
Yury Selivanov75445082015-05-11 22:57:16 -04002748 VISIT(c, expr, s->v.AsyncFor.iter);
2749 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002750
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002751 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002752 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002753 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002754 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002755 /* SETUP_FINALLY to guard the __anext__ call */
2756 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002757 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002758 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002759 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002760 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002761
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002762 /* Success block for __anext__ */
2763 VISIT(c, expr, s->v.AsyncFor.target);
2764 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2765 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2766
2767 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002768
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002769 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002770 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002771 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002772
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002774 VISIT_SEQ(c, stmt, s->v.For.orelse);
2775
2776 compiler_use_next_block(c, end);
2777
2778 return 1;
2779}
2780
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781static int
2782compiler_while(struct compiler *c, stmt_ty s)
2783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002785 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002788 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002789 // Push a dummy block so the VISIT_SEQ knows that we are
2790 // inside a while loop so it can correctly evaluate syntax
2791 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002792 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002793 return 0;
2794 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002795 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002796 // Remove the dummy block now that is not needed.
2797 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002798 END_DO_NOT_EMIT_BYTECODE
2799 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 return 1;
2803 }
2804 loop = compiler_new_block(c);
2805 end = compiler_new_block(c);
2806 if (constant == -1) {
2807 anchor = compiler_new_block(c);
2808 if (anchor == NULL)
2809 return 0;
2810 }
2811 if (loop == NULL || end == NULL)
2812 return 0;
2813 if (s->v.While.orelse) {
2814 orelse = compiler_new_block(c);
2815 if (orelse == NULL)
2816 return 0;
2817 }
2818 else
2819 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002822 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 return 0;
2824 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002825 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2826 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
2828 VISIT_SEQ(c, stmt, s->v.While.body);
2829 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 /* XXX should the two POP instructions be in a separate block
2832 if there is no else clause ?
2833 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002835 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002837 compiler_pop_fblock(c, WHILE_LOOP, loop);
2838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 if (orelse != NULL) /* what if orelse is just pass? */
2840 VISIT_SEQ(c, stmt, s->v.While.orelse);
2841 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844}
2845
2846static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002847compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002849 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002850 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002851 if (c->u->u_ste->ste_type != FunctionBlock)
2852 return compiler_error(c, "'return' outside function");
2853 if (s->v.Return.value != NULL &&
2854 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2855 {
2856 return compiler_error(
2857 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 if (preserve_tos) {
2860 VISIT(c, expr, s->v.Return.value);
2861 }
Mark Shannonfee55262019-11-21 09:11:43 +00002862 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2863 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002864 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002865 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002866 }
2867 else if (!preserve_tos) {
2868 VISIT(c, expr, s->v.Return.value);
2869 }
2870 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873}
2874
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875static int
2876compiler_break(struct compiler *c)
2877{
Mark Shannonfee55262019-11-21 09:11:43 +00002878 struct fblockinfo *loop = NULL;
2879 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2880 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 }
Mark Shannonfee55262019-11-21 09:11:43 +00002882 if (loop == NULL) {
2883 return compiler_error(c, "'break' outside loop");
2884 }
2885 if (!compiler_unwind_fblock(c, loop, 0)) {
2886 return 0;
2887 }
2888 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2889 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890}
2891
2892static int
2893compiler_continue(struct compiler *c)
2894{
Mark Shannonfee55262019-11-21 09:11:43 +00002895 struct fblockinfo *loop = NULL;
2896 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2897 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002898 }
Mark Shannonfee55262019-11-21 09:11:43 +00002899 if (loop == NULL) {
2900 return compiler_error(c, "'continue' not properly in loop");
2901 }
2902 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2903 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002904}
2905
2906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908
2909 SETUP_FINALLY L
2910 <code for body>
2911 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002912 <code for finalbody>
2913 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 L:
2915 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002916 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 The special instructions use the block stack. Each block
2919 stack entry contains the instruction that created it (here
2920 SETUP_FINALLY), the level of the value stack at the time the
2921 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 Pushes the current value stack level and the label
2925 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002930 when a SETUP_FINALLY entry is found, the raised and the caught
2931 exceptions are pushed onto the value stack (and the exception
2932 condition is cleared), and the interpreter jumps to the label
2933 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934*/
2935
2936static int
2937compiler_try_finally(struct compiler *c, stmt_ty s)
2938{
Mark Shannonfee55262019-11-21 09:11:43 +00002939 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 body = compiler_new_block(c);
2942 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002943 exit = compiler_new_block(c);
2944 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 ADDOP_JREL(c, SETUP_FINALLY, end);
2949 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002950 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002952 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2953 if (!compiler_try_except(c, s))
2954 return 0;
2955 }
2956 else {
2957 VISIT_SEQ(c, stmt, s->v.Try.body);
2958 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002960 compiler_pop_fblock(c, FINALLY_TRY, body);
2961 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2962 ADDOP_JREL(c, JUMP_FORWARD, exit);
2963 /* `finally` block */
2964 compiler_use_next_block(c, end);
2965 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2966 return 0;
2967 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2968 compiler_pop_fblock(c, FINALLY_END, end);
2969 ADDOP(c, RERAISE);
2970 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972}
2973
2974/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002975 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 (The contents of the value stack is shown in [], with the top
2977 at the right; 'tb' is trace-back info, 'val' the exception's
2978 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979
2980 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002981 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 [] <code for S>
2983 [] POP_BLOCK
2984 [] JUMP_FORWARD L0
2985
2986 [tb, val, exc] L1: DUP )
2987 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00002988 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 [tb, val, exc] POP
2990 [tb, val] <assign to V1> (or POP if no V1)
2991 [tb] POP
2992 [] <code for S1>
2993 JUMP_FORWARD L0
2994
2995 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 .............................etc.......................
2997
Mark Shannonfee55262019-11-21 09:11:43 +00002998 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999
3000 [] L0: <next statement>
3001
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003002 Of course, parts are not generated if Vi or Ei is not present.
3003*/
3004static int
3005compiler_try_except(struct compiler *c, stmt_ty s)
3006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003008 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 body = compiler_new_block(c);
3011 except = compiler_new_block(c);
3012 orelse = compiler_new_block(c);
3013 end = compiler_new_block(c);
3014 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3015 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003016 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003018 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003020 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 ADDOP(c, POP_BLOCK);
3022 compiler_pop_fblock(c, EXCEPT, body);
3023 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003024 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 compiler_use_next_block(c, except);
3026 for (i = 0; i < n; i++) {
3027 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003028 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 if (!handler->v.ExceptHandler.type && i < n-1)
3030 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003031 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 except = compiler_new_block(c);
3033 if (except == NULL)
3034 return 0;
3035 if (handler->v.ExceptHandler.type) {
3036 ADDOP(c, DUP_TOP);
3037 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003038 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 }
3040 ADDOP(c, POP_TOP);
3041 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003042 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003043
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003044 cleanup_end = compiler_new_block(c);
3045 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003046 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003048 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003049
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003050 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3051 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003053 /*
3054 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003055 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003056 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003057 try:
3058 # body
3059 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003060 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003061 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003062 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003064 /* second try: */
3065 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3066 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003067 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 /* second # body */
3071 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003072 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003073 ADDOP(c, POP_BLOCK);
3074 ADDOP(c, POP_EXCEPT);
3075 /* name = None; del name */
3076 ADDOP_LOAD_CONST(c, Py_None);
3077 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3078 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3079 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080
Mark Shannonfee55262019-11-21 09:11:43 +00003081 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003082 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003084 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003085 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088
Mark Shannonfee55262019-11-21 09:11:43 +00003089 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 }
3091 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003092 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003095 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003096 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Guido van Rossumb940e112007-01-10 16:19:56 +00003098 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 ADDOP(c, POP_TOP);
3100 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003101 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 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_EXCEPT);
3106 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 compiler_use_next_block(c, except);
3109 }
Mark Shannonfee55262019-11-21 09:11:43 +00003110 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003112 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 compiler_use_next_block(c, end);
3114 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115}
3116
3117static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003118compiler_try(struct compiler *c, stmt_ty s) {
3119 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3120 return compiler_try_finally(c, s);
3121 else
3122 return compiler_try_except(c, s);
3123}
3124
3125
3126static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127compiler_import_as(struct compiler *c, identifier name, identifier asname)
3128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 /* The IMPORT_NAME opcode was already generated. This function
3130 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003133 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003135 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3136 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003137 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003138 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003139 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003141 while (1) {
3142 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003144 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003145 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003146 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003147 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003149 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003150 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003151 if (dot == -1) {
3152 break;
3153 }
3154 ADDOP(c, ROT_TWO);
3155 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003157 if (!compiler_nameop(c, asname, Store)) {
3158 return 0;
3159 }
3160 ADDOP(c, POP_TOP);
3161 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 }
3163 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164}
3165
3166static int
3167compiler_import(struct compiler *c, stmt_ty s)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 /* The Import node stores a module name like a.b.c as a single
3170 string. This is convenient for all cases except
3171 import a.b.c as d
3172 where we need to parse that string to extract the individual
3173 module names.
3174 XXX Perhaps change the representation to make this case simpler?
3175 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003176 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 for (i = 0; i < n; i++) {
3179 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3180 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003182 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3183 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 if (alias->asname) {
3187 r = compiler_import_as(c, alias->name, alias->asname);
3188 if (!r)
3189 return r;
3190 }
3191 else {
3192 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003193 Py_ssize_t dot = PyUnicode_FindChar(
3194 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003195 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003196 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003197 if (tmp == NULL)
3198 return 0;
3199 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003201 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 Py_DECREF(tmp);
3203 }
3204 if (!r)
3205 return r;
3206 }
3207 }
3208 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209}
3210
3211static int
3212compiler_from_import(struct compiler *c, stmt_ty s)
3213{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003214 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003215 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 if (!empty_string) {
3219 empty_string = PyUnicode_FromString("");
3220 if (!empty_string)
3221 return 0;
3222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003224 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003225
3226 names = PyTuple_New(n);
3227 if (!names)
3228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 /* build up the names */
3231 for (i = 0; i < n; i++) {
3232 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3233 Py_INCREF(alias->name);
3234 PyTuple_SET_ITEM(names, i, alias->name);
3235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003238 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 Py_DECREF(names);
3240 return compiler_error(c, "from __future__ imports must occur "
3241 "at the beginning of the file");
3242 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003243 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 if (s->v.ImportFrom.module) {
3246 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3247 }
3248 else {
3249 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3250 }
3251 for (i = 0; i < n; i++) {
3252 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3253 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003255 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 assert(n == 1);
3257 ADDOP(c, IMPORT_STAR);
3258 return 1;
3259 }
3260
3261 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3262 store_name = alias->name;
3263 if (alias->asname)
3264 store_name = alias->asname;
3265
3266 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 return 0;
3268 }
3269 }
3270 /* remove imported module */
3271 ADDOP(c, POP_TOP);
3272 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273}
3274
3275static int
3276compiler_assert(struct compiler *c, stmt_ty s)
3277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
Georg Brandl8334fd92010-12-04 10:26:46 +00003280 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003283 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3284 {
3285 if (!compiler_warn(c, "assertion is always true, "
3286 "perhaps remove parentheses?"))
3287 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003288 return 0;
3289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 end = compiler_new_block(c);
3292 if (end == NULL)
3293 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003294 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3295 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003296 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 if (s->v.Assert.msg) {
3298 VISIT(c, expr, s->v.Assert.msg);
3299 ADDOP_I(c, CALL_FUNCTION, 1);
3300 }
3301 ADDOP_I(c, RAISE_VARARGS, 1);
3302 compiler_use_next_block(c, end);
3303 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304}
3305
3306static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003307compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3308{
3309 if (c->c_interactive && c->c_nestlevel <= 1) {
3310 VISIT(c, expr, value);
3311 ADDOP(c, PRINT_EXPR);
3312 return 1;
3313 }
3314
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003315 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003316 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003317 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003318 }
3319
3320 VISIT(c, expr, value);
3321 ADDOP(c, POP_TOP);
3322 return 1;
3323}
3324
3325static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326compiler_visit_stmt(struct compiler *c, stmt_ty s)
3327{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003328 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003331 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 switch (s->kind) {
3334 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003335 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 case ClassDef_kind:
3337 return compiler_class(c, s);
3338 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003339 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 case Delete_kind:
3341 VISIT_SEQ(c, expr, s->v.Delete.targets)
3342 break;
3343 case Assign_kind:
3344 n = asdl_seq_LEN(s->v.Assign.targets);
3345 VISIT(c, expr, s->v.Assign.value);
3346 for (i = 0; i < n; i++) {
3347 if (i < n - 1)
3348 ADDOP(c, DUP_TOP);
3349 VISIT(c, expr,
3350 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3351 }
3352 break;
3353 case AugAssign_kind:
3354 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003355 case AnnAssign_kind:
3356 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 case For_kind:
3358 return compiler_for(c, s);
3359 case While_kind:
3360 return compiler_while(c, s);
3361 case If_kind:
3362 return compiler_if(c, s);
3363 case Raise_kind:
3364 n = 0;
3365 if (s->v.Raise.exc) {
3366 VISIT(c, expr, s->v.Raise.exc);
3367 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003368 if (s->v.Raise.cause) {
3369 VISIT(c, expr, s->v.Raise.cause);
3370 n++;
3371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003373 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003375 case Try_kind:
3376 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 case Assert_kind:
3378 return compiler_assert(c, s);
3379 case Import_kind:
3380 return compiler_import(c, s);
3381 case ImportFrom_kind:
3382 return compiler_from_import(c, s);
3383 case Global_kind:
3384 case Nonlocal_kind:
3385 break;
3386 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003387 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 case Pass_kind:
3389 break;
3390 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003391 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Continue_kind:
3393 return compiler_continue(c);
3394 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003395 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003396 case AsyncFunctionDef_kind:
3397 return compiler_function(c, s, 1);
3398 case AsyncWith_kind:
3399 return compiler_async_with(c, s, 0);
3400 case AsyncFor_kind:
3401 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 }
Yury Selivanov75445082015-05-11 22:57:16 -04003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405}
3406
3407static int
3408unaryop(unaryop_ty op)
3409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 switch (op) {
3411 case Invert:
3412 return UNARY_INVERT;
3413 case Not:
3414 return UNARY_NOT;
3415 case UAdd:
3416 return UNARY_POSITIVE;
3417 case USub:
3418 return UNARY_NEGATIVE;
3419 default:
3420 PyErr_Format(PyExc_SystemError,
3421 "unary op %d should not be possible", op);
3422 return 0;
3423 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424}
3425
3426static int
Andy Lester76d58772020-03-10 21:18:12 -05003427binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 switch (op) {
3430 case Add:
3431 return BINARY_ADD;
3432 case Sub:
3433 return BINARY_SUBTRACT;
3434 case Mult:
3435 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003436 case MatMult:
3437 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 case Div:
3439 return BINARY_TRUE_DIVIDE;
3440 case Mod:
3441 return BINARY_MODULO;
3442 case Pow:
3443 return BINARY_POWER;
3444 case LShift:
3445 return BINARY_LSHIFT;
3446 case RShift:
3447 return BINARY_RSHIFT;
3448 case BitOr:
3449 return BINARY_OR;
3450 case BitXor:
3451 return BINARY_XOR;
3452 case BitAnd:
3453 return BINARY_AND;
3454 case FloorDiv:
3455 return BINARY_FLOOR_DIVIDE;
3456 default:
3457 PyErr_Format(PyExc_SystemError,
3458 "binary op %d should not be possible", op);
3459 return 0;
3460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461}
3462
3463static int
Andy Lester76d58772020-03-10 21:18:12 -05003464inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 switch (op) {
3467 case Add:
3468 return INPLACE_ADD;
3469 case Sub:
3470 return INPLACE_SUBTRACT;
3471 case Mult:
3472 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003473 case MatMult:
3474 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 case Div:
3476 return INPLACE_TRUE_DIVIDE;
3477 case Mod:
3478 return INPLACE_MODULO;
3479 case Pow:
3480 return INPLACE_POWER;
3481 case LShift:
3482 return INPLACE_LSHIFT;
3483 case RShift:
3484 return INPLACE_RSHIFT;
3485 case BitOr:
3486 return INPLACE_OR;
3487 case BitXor:
3488 return INPLACE_XOR;
3489 case BitAnd:
3490 return INPLACE_AND;
3491 case FloorDiv:
3492 return INPLACE_FLOOR_DIVIDE;
3493 default:
3494 PyErr_Format(PyExc_SystemError,
3495 "inplace binary op %d should not be possible", op);
3496 return 0;
3497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498}
3499
3500static int
3501compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3502{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003503 int op, scope;
3504 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 PyObject *dict = c->u->u_names;
3508 PyObject *mangled;
3509 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003511 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3512 !_PyUnicode_EqualToASCIIString(name, "True") &&
3513 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003514
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003515 mangled = _Py_Mangle(c->u->u_private, name);
3516 if (!mangled)
3517 return 0;
3518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 op = 0;
3520 optype = OP_NAME;
3521 scope = PyST_GetScope(c->u->u_ste, mangled);
3522 switch (scope) {
3523 case FREE:
3524 dict = c->u->u_freevars;
3525 optype = OP_DEREF;
3526 break;
3527 case CELL:
3528 dict = c->u->u_cellvars;
3529 optype = OP_DEREF;
3530 break;
3531 case LOCAL:
3532 if (c->u->u_ste->ste_type == FunctionBlock)
3533 optype = OP_FAST;
3534 break;
3535 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003536 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 optype = OP_GLOBAL;
3538 break;
3539 case GLOBAL_EXPLICIT:
3540 optype = OP_GLOBAL;
3541 break;
3542 default:
3543 /* scope can be 0 */
3544 break;
3545 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003548 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 switch (optype) {
3551 case OP_DEREF:
3552 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003553 case Load:
3554 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3555 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003556 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003557 op = STORE_DEREF;
3558 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 case AugLoad:
3560 case AugStore:
3561 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003562 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003564 PyErr_Format(PyExc_SystemError,
3565 "expr_context kind %d should not be possible",
3566 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 return 0;
3568 }
3569 break;
3570 case OP_FAST:
3571 switch (ctx) {
3572 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003573 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003574 op = STORE_FAST;
3575 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 case Del: op = DELETE_FAST; break;
3577 case AugLoad:
3578 case AugStore:
3579 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003581 PyErr_Format(PyExc_SystemError,
3582 "expr_context kind %d should not be possible",
3583 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 return 0;
3585 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003586 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 return 1;
3588 case OP_GLOBAL:
3589 switch (ctx) {
3590 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003591 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003592 op = STORE_GLOBAL;
3593 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 case Del: op = DELETE_GLOBAL; break;
3595 case AugLoad:
3596 case AugStore:
3597 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003599 PyErr_Format(PyExc_SystemError,
3600 "expr_context kind %d should not be possible",
3601 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 return 0;
3603 }
3604 break;
3605 case OP_NAME:
3606 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003607 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003608 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003609 op = STORE_NAME;
3610 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 case Del: op = DELETE_NAME; break;
3612 case AugLoad:
3613 case AugStore:
3614 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03003616 PyErr_Format(PyExc_SystemError,
3617 "expr_context kind %d should not be possible",
3618 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 return 0;
3620 }
3621 break;
3622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003625 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 Py_DECREF(mangled);
3627 if (arg < 0)
3628 return 0;
3629 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
3633compiler_boolop(struct compiler *c, expr_ty e)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003636 int jumpi;
3637 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 assert(e->kind == BoolOp_kind);
3641 if (e->v.BoolOp.op == And)
3642 jumpi = JUMP_IF_FALSE_OR_POP;
3643 else
3644 jumpi = JUMP_IF_TRUE_OR_POP;
3645 end = compiler_new_block(c);
3646 if (end == NULL)
3647 return 0;
3648 s = e->v.BoolOp.values;
3649 n = asdl_seq_LEN(s) - 1;
3650 assert(n >= 0);
3651 for (i = 0; i < n; ++i) {
3652 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3653 ADDOP_JABS(c, jumpi, end);
3654 }
3655 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3656 compiler_use_next_block(c, end);
3657 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658}
3659
3660static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003661starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3662 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003663{
3664 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003665 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003666 if (n > 2 && are_all_items_const(elts, 0, n)) {
3667 PyObject *folded = PyTuple_New(n);
3668 if (folded == NULL) {
3669 return 0;
3670 }
3671 PyObject *val;
3672 for (i = 0; i < n; i++) {
3673 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3674 Py_INCREF(val);
3675 PyTuple_SET_ITEM(folded, i, val);
3676 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003677 if (tuple) {
3678 ADDOP_LOAD_CONST_NEW(c, folded);
3679 } else {
3680 if (add == SET_ADD) {
3681 Py_SETREF(folded, PyFrozenSet_New(folded));
3682 if (folded == NULL) {
3683 return 0;
3684 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003686 ADDOP_I(c, build, pushed);
3687 ADDOP_LOAD_CONST_NEW(c, folded);
3688 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003689 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 return 1;
3691 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003692
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003693 for (i = 0; i < n; i++) {
3694 expr_ty elt = asdl_seq_GET(elts, i);
3695 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003696 seen_star = 1;
3697 }
3698 }
3699 if (seen_star) {
3700 seen_star = 0;
3701 for (i = 0; i < n; i++) {
3702 expr_ty elt = asdl_seq_GET(elts, i);
3703 if (elt->kind == Starred_kind) {
3704 if (seen_star == 0) {
3705 ADDOP_I(c, build, i+pushed);
3706 seen_star = 1;
3707 }
3708 VISIT(c, expr, elt->v.Starred.value);
3709 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003711 else {
3712 VISIT(c, expr, elt);
3713 if (seen_star) {
3714 ADDOP_I(c, add, 1);
3715 }
3716 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003718 assert(seen_star);
3719 if (tuple) {
3720 ADDOP(c, LIST_TO_TUPLE);
3721 }
3722 }
3723 else {
3724 for (i = 0; i < n; i++) {
3725 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003726 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003727 }
3728 if (tuple) {
3729 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3730 } else {
3731 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003732 }
3733 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 return 1;
3735}
3736
3737static int
3738assignment_helper(struct compiler *c, asdl_seq *elts)
3739{
3740 Py_ssize_t n = asdl_seq_LEN(elts);
3741 Py_ssize_t i;
3742 int seen_star = 0;
3743 for (i = 0; i < n; i++) {
3744 expr_ty elt = asdl_seq_GET(elts, i);
3745 if (elt->kind == Starred_kind && !seen_star) {
3746 if ((i >= (1 << 8)) ||
3747 (n-i-1 >= (INT_MAX >> 8)))
3748 return compiler_error(c,
3749 "too many expressions in "
3750 "star-unpacking assignment");
3751 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3752 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 }
3754 else if (elt->kind == Starred_kind) {
3755 return compiler_error(c,
3756 "two starred expressions in assignment");
3757 }
3758 }
3759 if (!seen_star) {
3760 ADDOP_I(c, UNPACK_SEQUENCE, n);
3761 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003762 for (i = 0; i < n; i++) {
3763 expr_ty elt = asdl_seq_GET(elts, i);
3764 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3765 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003766 return 1;
3767}
3768
3769static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770compiler_list(struct compiler *c, expr_ty e)
3771{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003772 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003773 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003774 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003776 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003777 return starunpack_helper(c, elts, 0, BUILD_LIST,
3778 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003780 else
3781 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783}
3784
3785static int
3786compiler_tuple(struct compiler *c, expr_ty e)
3787{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003788 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003789 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 return assignment_helper(c, elts);
3791 }
3792 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003793 return starunpack_helper(c, elts, 0, BUILD_LIST,
3794 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 }
3796 else
3797 VISIT_SEQ(c, expr, elts);
3798 return 1;
3799}
3800
3801static int
3802compiler_set(struct compiler *c, expr_ty e)
3803{
Mark Shannon13bc1392020-01-23 09:25:17 +00003804 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3805 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003806}
3807
3808static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003809are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3810{
3811 Py_ssize_t i;
3812 for (i = begin; i < end; i++) {
3813 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003814 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003815 return 0;
3816 }
3817 return 1;
3818}
3819
3820static int
3821compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3822{
3823 Py_ssize_t i, n = end - begin;
3824 PyObject *keys, *key;
3825 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3826 for (i = begin; i < end; i++) {
3827 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3828 }
3829 keys = PyTuple_New(n);
3830 if (keys == NULL) {
3831 return 0;
3832 }
3833 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003834 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003835 Py_INCREF(key);
3836 PyTuple_SET_ITEM(keys, i - begin, key);
3837 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003838 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003839 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3840 }
3841 else {
3842 for (i = begin; i < end; i++) {
3843 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3844 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3845 }
3846 ADDOP_I(c, BUILD_MAP, n);
3847 }
3848 return 1;
3849}
3850
3851static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003852compiler_dict(struct compiler *c, expr_ty e)
3853{
Victor Stinner976bb402016-03-23 11:36:19 +01003854 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003855 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003856 int is_unpacking = 0;
3857 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003858 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003859 elements = 0;
3860 for (i = 0; i < n; i++) {
3861 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003862 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003863 if (elements) {
3864 if (!compiler_subdict(c, e, i - elements, i)) {
3865 return 0;
3866 }
3867 if (have_dict) {
3868 ADDOP_I(c, DICT_UPDATE, 1);
3869 }
3870 have_dict = 1;
3871 elements = 0;
3872 }
3873 if (have_dict == 0) {
3874 ADDOP_I(c, BUILD_MAP, 0);
3875 have_dict = 1;
3876 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879 }
3880 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003881 if (elements == 0xFFFF) {
3882 if (!compiler_subdict(c, e, i - elements, i)) {
3883 return 0;
3884 }
3885 if (have_dict) {
3886 ADDOP_I(c, DICT_UPDATE, 1);
3887 }
3888 have_dict = 1;
3889 elements = 0;
3890 }
3891 else {
3892 elements++;
3893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 }
3895 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003896 if (elements) {
3897 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003898 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003899 }
3900 if (have_dict) {
3901 ADDOP_I(c, DICT_UPDATE, 1);
3902 }
3903 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003904 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003905 if (!have_dict) {
3906 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 }
3908 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909}
3910
3911static int
3912compiler_compare(struct compiler *c, expr_ty e)
3913{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003914 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003916 if (!check_compare(c, e)) {
3917 return 0;
3918 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003920 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3921 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3922 if (n == 0) {
3923 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003924 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 }
3926 else {
3927 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (cleanup == NULL)
3929 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003930 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 VISIT(c, expr,
3932 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003933 ADDOP(c, DUP_TOP);
3934 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003935 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003936 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3937 NEXT_BLOCK(c);
3938 }
3939 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003940 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 basicblock *end = compiler_new_block(c);
3942 if (end == NULL)
3943 return 0;
3944 ADDOP_JREL(c, JUMP_FORWARD, end);
3945 compiler_use_next_block(c, cleanup);
3946 ADDOP(c, ROT_TWO);
3947 ADDOP(c, POP_TOP);
3948 compiler_use_next_block(c, end);
3949 }
3950 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003951}
3952
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003953static PyTypeObject *
3954infer_type(expr_ty e)
3955{
3956 switch (e->kind) {
3957 case Tuple_kind:
3958 return &PyTuple_Type;
3959 case List_kind:
3960 case ListComp_kind:
3961 return &PyList_Type;
3962 case Dict_kind:
3963 case DictComp_kind:
3964 return &PyDict_Type;
3965 case Set_kind:
3966 case SetComp_kind:
3967 return &PySet_Type;
3968 case GeneratorExp_kind:
3969 return &PyGen_Type;
3970 case Lambda_kind:
3971 return &PyFunction_Type;
3972 case JoinedStr_kind:
3973 case FormattedValue_kind:
3974 return &PyUnicode_Type;
3975 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003976 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003977 default:
3978 return NULL;
3979 }
3980}
3981
3982static int
3983check_caller(struct compiler *c, expr_ty e)
3984{
3985 switch (e->kind) {
3986 case Constant_kind:
3987 case Tuple_kind:
3988 case List_kind:
3989 case ListComp_kind:
3990 case Dict_kind:
3991 case DictComp_kind:
3992 case Set_kind:
3993 case SetComp_kind:
3994 case GeneratorExp_kind:
3995 case JoinedStr_kind:
3996 case FormattedValue_kind:
3997 return compiler_warn(c, "'%.200s' object is not callable; "
3998 "perhaps you missed a comma?",
3999 infer_type(e)->tp_name);
4000 default:
4001 return 1;
4002 }
4003}
4004
4005static int
4006check_subscripter(struct compiler *c, expr_ty e)
4007{
4008 PyObject *v;
4009
4010 switch (e->kind) {
4011 case Constant_kind:
4012 v = e->v.Constant.value;
4013 if (!(v == Py_None || v == Py_Ellipsis ||
4014 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4015 PyAnySet_Check(v)))
4016 {
4017 return 1;
4018 }
4019 /* fall through */
4020 case Set_kind:
4021 case SetComp_kind:
4022 case GeneratorExp_kind:
4023 case Lambda_kind:
4024 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4025 "perhaps you missed a comma?",
4026 infer_type(e)->tp_name);
4027 default:
4028 return 1;
4029 }
4030}
4031
4032static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004033check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004034{
4035 PyObject *v;
4036
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004037 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004038 if (index_type == NULL
4039 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4040 || index_type == &PySlice_Type) {
4041 return 1;
4042 }
4043
4044 switch (e->kind) {
4045 case Constant_kind:
4046 v = e->v.Constant.value;
4047 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4048 return 1;
4049 }
4050 /* fall through */
4051 case Tuple_kind:
4052 case List_kind:
4053 case ListComp_kind:
4054 case JoinedStr_kind:
4055 case FormattedValue_kind:
4056 return compiler_warn(c, "%.200s indices must be integers or slices, "
4057 "not %.200s; "
4058 "perhaps you missed a comma?",
4059 infer_type(e)->tp_name,
4060 index_type->tp_name);
4061 default:
4062 return 1;
4063 }
4064}
4065
Zackery Spytz97f5de02019-03-22 01:30:32 -06004066// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004068maybe_optimize_method_call(struct compiler *c, expr_ty e)
4069{
4070 Py_ssize_t argsl, i;
4071 expr_ty meth = e->v.Call.func;
4072 asdl_seq *args = e->v.Call.args;
4073
4074 /* Check that the call node is an attribute access, and that
4075 the call doesn't have keyword parameters. */
4076 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4077 asdl_seq_LEN(e->v.Call.keywords))
4078 return -1;
4079
4080 /* Check that there are no *varargs types of arguments. */
4081 argsl = asdl_seq_LEN(args);
4082 for (i = 0; i < argsl; i++) {
4083 expr_ty elt = asdl_seq_GET(args, i);
4084 if (elt->kind == Starred_kind) {
4085 return -1;
4086 }
4087 }
4088
4089 /* Alright, we can optimize the code. */
4090 VISIT(c, expr, meth->v.Attribute.value);
4091 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4092 VISIT_SEQ(c, expr, e->v.Call.args);
4093 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4094 return 1;
4095}
4096
4097static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098compiler_call(struct compiler *c, expr_ty e)
4099{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004100 int ret = maybe_optimize_method_call(c, e);
4101 if (ret >= 0) {
4102 return ret;
4103 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004104 if (!check_caller(c, e->v.Call.func)) {
4105 return 0;
4106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 VISIT(c, expr, e->v.Call.func);
4108 return compiler_call_helper(c, 0,
4109 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004110 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004111}
4112
Eric V. Smith235a6f02015-09-19 14:51:32 -04004113static int
4114compiler_joined_str(struct compiler *c, expr_ty e)
4115{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004116 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004117 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4118 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004119 return 1;
4120}
4121
Eric V. Smitha78c7952015-11-03 12:45:05 -05004122/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004123static int
4124compiler_formatted_value(struct compiler *c, expr_ty e)
4125{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004126 /* Our oparg encodes 2 pieces of information: the conversion
4127 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004128
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004129 Convert the conversion char to 3 bits:
4130 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004131 !s : 001 0x1 FVC_STR
4132 !r : 010 0x2 FVC_REPR
4133 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004134
Eric V. Smitha78c7952015-11-03 12:45:05 -05004135 next bit is whether or not we have a format spec:
4136 yes : 100 0x4
4137 no : 000 0x0
4138 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004139
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004140 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004141 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004142
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004143 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004144 VISIT(c, expr, e->v.FormattedValue.value);
4145
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004146 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004147 case 's': oparg = FVC_STR; break;
4148 case 'r': oparg = FVC_REPR; break;
4149 case 'a': oparg = FVC_ASCII; break;
4150 case -1: oparg = FVC_NONE; break;
4151 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004152 PyErr_Format(PyExc_SystemError,
4153 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004154 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004155 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004156 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004157 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004160 }
4161
Eric V. Smitha78c7952015-11-03 12:45:05 -05004162 /* And push our opcode and oparg */
4163 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004164
Eric V. Smith235a6f02015-09-19 14:51:32 -04004165 return 1;
4166}
4167
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004168static int
4169compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4170{
4171 Py_ssize_t i, n = end - begin;
4172 keyword_ty kw;
4173 PyObject *keys, *key;
4174 assert(n > 0);
4175 if (n > 1) {
4176 for (i = begin; i < end; i++) {
4177 kw = asdl_seq_GET(keywords, i);
4178 VISIT(c, expr, kw->value);
4179 }
4180 keys = PyTuple_New(n);
4181 if (keys == NULL) {
4182 return 0;
4183 }
4184 for (i = begin; i < end; i++) {
4185 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4186 Py_INCREF(key);
4187 PyTuple_SET_ITEM(keys, i - begin, key);
4188 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004189 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004190 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4191 }
4192 else {
4193 /* a for loop only executes once */
4194 for (i = begin; i < end; i++) {
4195 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004196 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004197 VISIT(c, expr, kw->value);
4198 }
4199 ADDOP_I(c, BUILD_MAP, n);
4200 }
4201 return 1;
4202}
4203
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004204/* shared code between compiler_call and compiler_class */
4205static int
4206compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004207 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004208 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004209 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004210{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004211 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004212
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004213 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004214 nkwelts = asdl_seq_LEN(keywords);
4215
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004216 for (i = 0; i < nelts; i++) {
4217 expr_ty elt = asdl_seq_GET(args, i);
4218 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004219 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004220 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004221 }
4222 for (i = 0; i < nkwelts; i++) {
4223 keyword_ty kw = asdl_seq_GET(keywords, i);
4224 if (kw->arg == NULL) {
4225 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004228
Mark Shannon13bc1392020-01-23 09:25:17 +00004229 /* No * or ** args, so can use faster calling sequence */
4230 for (i = 0; i < nelts; i++) {
4231 expr_ty elt = asdl_seq_GET(args, i);
4232 assert(elt->kind != Starred_kind);
4233 VISIT(c, expr, elt);
4234 }
4235 if (nkwelts) {
4236 PyObject *names;
4237 VISIT_SEQ(c, keyword, keywords);
4238 names = PyTuple_New(nkwelts);
4239 if (names == NULL) {
4240 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004241 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004242 for (i = 0; i < nkwelts; i++) {
4243 keyword_ty kw = asdl_seq_GET(keywords, i);
4244 Py_INCREF(kw->arg);
4245 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004246 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004247 ADDOP_LOAD_CONST_NEW(c, names);
4248 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4249 return 1;
4250 }
4251 else {
4252 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4253 return 1;
4254 }
4255
4256ex_call:
4257
4258 /* Do positional arguments. */
4259 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4260 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4261 }
4262 else if (starunpack_helper(c, args, n, BUILD_LIST,
4263 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4264 return 0;
4265 }
4266 /* Then keyword arguments */
4267 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004268 /* Has a new dict been pushed */
4269 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004270
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004271 nseen = 0; /* the number of keyword arguments on the stack following */
4272 for (i = 0; i < nkwelts; i++) {
4273 keyword_ty kw = asdl_seq_GET(keywords, i);
4274 if (kw->arg == NULL) {
4275 /* A keyword argument unpacking. */
4276 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004277 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004278 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004279 }
4280 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004281 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004282 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004283 if (!have_dict) {
4284 ADDOP_I(c, BUILD_MAP, 0);
4285 have_dict = 1;
4286 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004287 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004288 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004289 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004290 else {
4291 nseen++;
4292 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004293 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004294 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004295 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004296 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004297 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004298 }
4299 if (have_dict) {
4300 ADDOP_I(c, DICT_MERGE, 1);
4301 }
4302 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004303 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004304 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004306 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308}
4309
Nick Coghlan650f0d02007-04-15 12:05:43 +00004310
4311/* List and set comprehensions and generator expressions work by creating a
4312 nested function to perform the actual iteration. This means that the
4313 iteration variables don't leak into the current scope.
4314 The defined function is called immediately following its definition, with the
4315 result of that call being the result of the expression.
4316 The LC/SC version returns the populated container, while the GE version is
4317 flagged in symtable.c as a generator, so it returns the generator object
4318 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004319
4320 Possible cleanups:
4321 - iterate over the generator sequence instead of using recursion
4322*/
4323
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326compiler_comprehension_generator(struct compiler *c,
4327 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004328 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004331 comprehension_ty gen;
4332 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4333 if (gen->is_async) {
4334 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004335 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004336 } else {
4337 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004338 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004339 }
4340}
4341
4342static int
4343compiler_sync_comprehension_generator(struct compiler *c,
4344 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004345 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004346 expr_ty elt, expr_ty val, int type)
4347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 /* generate code for the iterator, then each of the ifs,
4349 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 comprehension_ty gen;
4352 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004353 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 start = compiler_new_block(c);
4356 skip = compiler_new_block(c);
4357 if_cleanup = compiler_new_block(c);
4358 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4361 anchor == NULL)
4362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 if (gen_index == 0) {
4367 /* Receive outermost iter as an implicit argument */
4368 c->u->u_argcount = 1;
4369 ADDOP_I(c, LOAD_FAST, 0);
4370 }
4371 else {
4372 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004373 /* Fast path for the temporary variable assignment idiom:
4374 for y in [f(x)]
4375 */
4376 asdl_seq *elts;
4377 switch (gen->iter->kind) {
4378 case List_kind:
4379 elts = gen->iter->v.List.elts;
4380 break;
4381 case Tuple_kind:
4382 elts = gen->iter->v.Tuple.elts;
4383 break;
4384 default:
4385 elts = NULL;
4386 }
4387 if (asdl_seq_LEN(elts) == 1) {
4388 expr_ty elt = asdl_seq_GET(elts, 0);
4389 if (elt->kind != Starred_kind) {
4390 VISIT(c, expr, elt);
4391 start = NULL;
4392 }
4393 }
4394 if (start) {
4395 VISIT(c, expr, gen->iter);
4396 ADDOP(c, GET_ITER);
4397 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004399 if (start) {
4400 depth++;
4401 compiler_use_next_block(c, start);
4402 ADDOP_JREL(c, FOR_ITER, anchor);
4403 NEXT_BLOCK(c);
4404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 /* XXX this needs to be cleaned up...a lot! */
4408 n = asdl_seq_LEN(gen->ifs);
4409 for (i = 0; i < n; i++) {
4410 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004411 if (!compiler_jump_if(c, e, if_cleanup, 0))
4412 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 NEXT_BLOCK(c);
4414 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 if (++gen_index < asdl_seq_LEN(generators))
4417 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004418 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 elt, val, type))
4420 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 /* only append after the last for generator */
4423 if (gen_index >= asdl_seq_LEN(generators)) {
4424 /* comprehension specific code */
4425 switch (type) {
4426 case COMP_GENEXP:
4427 VISIT(c, expr, elt);
4428 ADDOP(c, YIELD_VALUE);
4429 ADDOP(c, POP_TOP);
4430 break;
4431 case COMP_LISTCOMP:
4432 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004433 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 break;
4435 case COMP_SETCOMP:
4436 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004437 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 break;
4439 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004440 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004443 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004444 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 break;
4446 default:
4447 return 0;
4448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 compiler_use_next_block(c, skip);
4451 }
4452 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004453 if (start) {
4454 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4455 compiler_use_next_block(c, anchor);
4456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457
4458 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004459}
4460
4461static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462compiler_async_comprehension_generator(struct compiler *c,
4463 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004464 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004465 expr_ty elt, expr_ty val, int type)
4466{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004467 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004468 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004469 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004470 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004471 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004472 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004473
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004474 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004475 return 0;
4476 }
4477
4478 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4479
4480 if (gen_index == 0) {
4481 /* Receive outermost iter as an implicit argument */
4482 c->u->u_argcount = 1;
4483 ADDOP_I(c, LOAD_FAST, 0);
4484 }
4485 else {
4486 /* Sub-iter - calculate on the fly */
4487 VISIT(c, expr, gen->iter);
4488 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004489 }
4490
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004491 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004493 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004495 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004496 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004498 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004499
4500 n = asdl_seq_LEN(gen->ifs);
4501 for (i = 0; i < n; i++) {
4502 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004503 if (!compiler_jump_if(c, e, if_cleanup, 0))
4504 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505 NEXT_BLOCK(c);
4506 }
4507
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004508 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509 if (++gen_index < asdl_seq_LEN(generators))
4510 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004511 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 elt, val, type))
4513 return 0;
4514
4515 /* only append after the last for generator */
4516 if (gen_index >= asdl_seq_LEN(generators)) {
4517 /* comprehension specific code */
4518 switch (type) {
4519 case COMP_GENEXP:
4520 VISIT(c, expr, elt);
4521 ADDOP(c, YIELD_VALUE);
4522 ADDOP(c, POP_TOP);
4523 break;
4524 case COMP_LISTCOMP:
4525 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004526 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 break;
4528 case COMP_SETCOMP:
4529 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004530 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 break;
4532 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004533 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004536 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004537 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004538 break;
4539 default:
4540 return 0;
4541 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004542 }
4543 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004544 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4545
4546 compiler_use_next_block(c, except);
4547 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548
4549 return 1;
4550}
4551
4552static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004553compiler_comprehension(struct compiler *c, expr_ty e, int type,
4554 identifier name, asdl_seq *generators, expr_ty elt,
4555 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004559 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004560 int is_async_function = c->u->u_ste->ste_coroutine;
4561 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004562
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004563 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004564
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004565 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4566 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004567 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 }
4570
4571 is_async_generator = c->u->u_ste->ste_coroutine;
4572
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004573 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 compiler_error(c, "asynchronous comprehension outside of "
4575 "an asynchronous function");
4576 goto error_in_scope;
4577 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 if (type != COMP_GENEXP) {
4580 int op;
4581 switch (type) {
4582 case COMP_LISTCOMP:
4583 op = BUILD_LIST;
4584 break;
4585 case COMP_SETCOMP:
4586 op = BUILD_SET;
4587 break;
4588 case COMP_DICTCOMP:
4589 op = BUILD_MAP;
4590 break;
4591 default:
4592 PyErr_Format(PyExc_SystemError,
4593 "unknown comprehension type %d", type);
4594 goto error_in_scope;
4595 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 ADDOP_I(c, op, 0);
4598 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004599
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004600 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 val, type))
4602 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 if (type != COMP_GENEXP) {
4605 ADDOP(c, RETURN_VALUE);
4606 }
4607
4608 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004609 qualname = c->u->u_qualname;
4610 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004612 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 goto error;
4614
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004615 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004617 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 Py_DECREF(co);
4619
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004620 VISIT(c, expr, outermost->iter);
4621
4622 if (outermost->is_async) {
4623 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004624 } else {
4625 ADDOP(c, GET_ITER);
4626 }
4627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004629
4630 if (is_async_generator && type != COMP_GENEXP) {
4631 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004632 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004633 ADDOP(c, YIELD_FROM);
4634 }
4635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004637error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004639error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004640 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 Py_XDECREF(co);
4642 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004643}
4644
4645static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004646compiler_genexp(struct compiler *c, expr_ty e)
4647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 static identifier name;
4649 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004650 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 if (!name)
4652 return 0;
4653 }
4654 assert(e->kind == GeneratorExp_kind);
4655 return compiler_comprehension(c, e, COMP_GENEXP, name,
4656 e->v.GeneratorExp.generators,
4657 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004658}
4659
4660static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004661compiler_listcomp(struct compiler *c, expr_ty e)
4662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 static identifier name;
4664 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004665 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 if (!name)
4667 return 0;
4668 }
4669 assert(e->kind == ListComp_kind);
4670 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4671 e->v.ListComp.generators,
4672 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004673}
4674
4675static int
4676compiler_setcomp(struct compiler *c, expr_ty e)
4677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 static identifier name;
4679 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004680 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 if (!name)
4682 return 0;
4683 }
4684 assert(e->kind == SetComp_kind);
4685 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4686 e->v.SetComp.generators,
4687 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004688}
4689
4690
4691static int
4692compiler_dictcomp(struct compiler *c, expr_ty e)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 static identifier name;
4695 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004696 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (!name)
4698 return 0;
4699 }
4700 assert(e->kind == DictComp_kind);
4701 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4702 e->v.DictComp.generators,
4703 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004704}
4705
4706
4707static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004708compiler_visit_keyword(struct compiler *c, keyword_ty k)
4709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 VISIT(c, expr, k->value);
4711 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004712}
4713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715 whether they are true or false.
4716
4717 Return values: 1 for true, 0 for false, -1 for non-constant.
4718 */
4719
4720static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004721expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004722{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004723 if (e->kind == Constant_kind) {
4724 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004725 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004726 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004727}
4728
Mark Shannonfee55262019-11-21 09:11:43 +00004729static int
4730compiler_with_except_finish(struct compiler *c) {
4731 basicblock *exit;
4732 exit = compiler_new_block(c);
4733 if (exit == NULL)
4734 return 0;
4735 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4736 ADDOP(c, RERAISE);
4737 compiler_use_next_block(c, exit);
4738 ADDOP(c, POP_TOP);
4739 ADDOP(c, POP_TOP);
4740 ADDOP(c, POP_TOP);
4741 ADDOP(c, POP_EXCEPT);
4742 ADDOP(c, POP_TOP);
4743 return 1;
4744}
Yury Selivanov75445082015-05-11 22:57:16 -04004745
4746/*
4747 Implements the async with statement.
4748
4749 The semantics outlined in that PEP are as follows:
4750
4751 async with EXPR as VAR:
4752 BLOCK
4753
4754 It is implemented roughly as:
4755
4756 context = EXPR
4757 exit = context.__aexit__ # not calling it
4758 value = await context.__aenter__()
4759 try:
4760 VAR = value # if VAR present in the syntax
4761 BLOCK
4762 finally:
4763 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004764 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004765 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004766 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004767 if not (await exit(*exc)):
4768 raise
4769 */
4770static int
4771compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4772{
Mark Shannonfee55262019-11-21 09:11:43 +00004773 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004774 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4775
4776 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004777 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004778 c->u->u_ste->ste_coroutine = 1;
4779 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004780 return compiler_error(c, "'async with' outside async function");
4781 }
Yury Selivanov75445082015-05-11 22:57:16 -04004782
4783 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004784 final = compiler_new_block(c);
4785 exit = compiler_new_block(c);
4786 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004787 return 0;
4788
4789 /* Evaluate EXPR */
4790 VISIT(c, expr, item->context_expr);
4791
4792 ADDOP(c, BEFORE_ASYNC_WITH);
4793 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004794 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004795 ADDOP(c, YIELD_FROM);
4796
Mark Shannonfee55262019-11-21 09:11:43 +00004797 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004798
4799 /* SETUP_ASYNC_WITH pushes a finally block. */
4800 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004801 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004802 return 0;
4803 }
4804
4805 if (item->optional_vars) {
4806 VISIT(c, expr, item->optional_vars);
4807 }
4808 else {
4809 /* Discard result from context.__aenter__() */
4810 ADDOP(c, POP_TOP);
4811 }
4812
4813 pos++;
4814 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4815 /* BLOCK code */
4816 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4817 else if (!compiler_async_with(c, s, pos))
4818 return 0;
4819
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004820 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004821 ADDOP(c, POP_BLOCK);
4822 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004823
Mark Shannonfee55262019-11-21 09:11:43 +00004824 /* For successful outcome:
4825 * call __exit__(None, None, None)
4826 */
4827 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004828 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004829 ADDOP(c, GET_AWAITABLE);
4830 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4831 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004832
Mark Shannonfee55262019-11-21 09:11:43 +00004833 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004834
Mark Shannonfee55262019-11-21 09:11:43 +00004835 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4836
4837 /* For exceptional outcome: */
4838 compiler_use_next_block(c, final);
4839
4840 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004841 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004842 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004843 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004844 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004845
Mark Shannonfee55262019-11-21 09:11:43 +00004846compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004847 return 1;
4848}
4849
4850
Guido van Rossumc2e20742006-02-27 22:32:47 +00004851/*
4852 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004853 with EXPR as VAR:
4854 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004855 is implemented as:
4856 <code for EXPR>
4857 SETUP_WITH E
4858 <code to store to VAR> or POP_TOP
4859 <code for BLOCK>
4860 LOAD_CONST (None, None, None)
4861 CALL_FUNCTION_EX 0
4862 JUMP_FORWARD EXIT
4863 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4864 POP_JUMP_IF_TRUE T:
4865 RERAISE
4866 T: POP_TOP * 3 (remove exception from stack)
4867 POP_EXCEPT
4868 POP_TOP
4869 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004870 */
Mark Shannonfee55262019-11-21 09:11:43 +00004871
Guido van Rossumc2e20742006-02-27 22:32:47 +00004872static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004873compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004874{
Mark Shannonfee55262019-11-21 09:11:43 +00004875 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004876 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004877
4878 assert(s->kind == With_kind);
4879
Guido van Rossumc2e20742006-02-27 22:32:47 +00004880 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004881 final = compiler_new_block(c);
4882 exit = compiler_new_block(c);
4883 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004884 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004885
Thomas Wouters477c8d52006-05-27 19:21:47 +00004886 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004887 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004888 /* Will push bound __exit__ */
4889 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004891 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004892 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004893 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004894 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004895 }
4896
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004897 if (item->optional_vars) {
4898 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004899 }
4900 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004902 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004903 }
4904
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004905 pos++;
4906 if (pos == asdl_seq_LEN(s->v.With.items))
4907 /* BLOCK code */
4908 VISIT_SEQ(c, stmt, s->v.With.body)
4909 else if (!compiler_with(c, s, pos))
4910 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911
Guido van Rossumc2e20742006-02-27 22:32:47 +00004912 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004913 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004914
Mark Shannonfee55262019-11-21 09:11:43 +00004915 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004916
Mark Shannonfee55262019-11-21 09:11:43 +00004917 /* For successful outcome:
4918 * call __exit__(None, None, None)
4919 */
4920 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004921 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004922 ADDOP(c, POP_TOP);
4923 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004924
Mark Shannonfee55262019-11-21 09:11:43 +00004925 /* For exceptional outcome: */
4926 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927
Mark Shannonfee55262019-11-21 09:11:43 +00004928 ADDOP(c, WITH_EXCEPT_START);
4929 compiler_with_except_finish(c);
4930
4931 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004932 return 1;
4933}
4934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004935static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004936compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004939 case NamedExpr_kind:
4940 VISIT(c, expr, e->v.NamedExpr.value);
4941 ADDOP(c, DUP_TOP);
4942 VISIT(c, expr, e->v.NamedExpr.target);
4943 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 case BoolOp_kind:
4945 return compiler_boolop(c, e);
4946 case BinOp_kind:
4947 VISIT(c, expr, e->v.BinOp.left);
4948 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004949 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004950 break;
4951 case UnaryOp_kind:
4952 VISIT(c, expr, e->v.UnaryOp.operand);
4953 ADDOP(c, unaryop(e->v.UnaryOp.op));
4954 break;
4955 case Lambda_kind:
4956 return compiler_lambda(c, e);
4957 case IfExp_kind:
4958 return compiler_ifexp(c, e);
4959 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004960 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004962 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004963 case GeneratorExp_kind:
4964 return compiler_genexp(c, e);
4965 case ListComp_kind:
4966 return compiler_listcomp(c, e);
4967 case SetComp_kind:
4968 return compiler_setcomp(c, e);
4969 case DictComp_kind:
4970 return compiler_dictcomp(c, e);
4971 case Yield_kind:
4972 if (c->u->u_ste->ste_type != FunctionBlock)
4973 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004974 if (e->v.Yield.value) {
4975 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 }
4977 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004978 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004980 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004982 case YieldFrom_kind:
4983 if (c->u->u_ste->ste_type != FunctionBlock)
4984 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004985
4986 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4987 return compiler_error(c, "'yield from' inside async function");
4988
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004989 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004990 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004991 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004992 ADDOP(c, YIELD_FROM);
4993 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004994 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00004995 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004996 if (c->u->u_ste->ste_type != FunctionBlock){
4997 return compiler_error(c, "'await' outside function");
4998 }
Yury Selivanov75445082015-05-11 22:57:16 -04004999
Victor Stinner331a6a52019-05-27 16:39:22 +02005000 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005001 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5002 return compiler_error(c, "'await' outside async function");
5003 }
5004 }
Yury Selivanov75445082015-05-11 22:57:16 -04005005
5006 VISIT(c, expr, e->v.Await.value);
5007 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005008 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005009 ADDOP(c, YIELD_FROM);
5010 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 case Compare_kind:
5012 return compiler_compare(c, e);
5013 case Call_kind:
5014 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005015 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005016 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005017 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005018 case JoinedStr_kind:
5019 return compiler_joined_str(c, e);
5020 case FormattedValue_kind:
5021 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 /* The following exprs can be assignment targets. */
5023 case Attribute_kind:
5024 if (e->v.Attribute.ctx != AugStore)
5025 VISIT(c, expr, e->v.Attribute.value);
5026 switch (e->v.Attribute.ctx) {
5027 case AugLoad:
5028 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02005029 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 case Load:
5031 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5032 break;
5033 case AugStore:
5034 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02005035 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 case Store:
5037 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5038 break;
5039 case Del:
5040 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5041 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 default:
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03005043 PyErr_Format(PyExc_SystemError,
5044 "expr_context kind %d should not be possible",
5045 e->v.Attribute.ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 return 0;
5047 }
5048 break;
5049 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005050 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 case Starred_kind:
5052 switch (e->v.Starred.ctx) {
5053 case Store:
5054 /* In all legitimate cases, the Starred node was already replaced
5055 * by compiler_list/compiler_tuple. XXX: is that okay? */
5056 return compiler_error(c,
5057 "starred assignment target must be in a list or tuple");
5058 default:
5059 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005060 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005062 break;
5063 case Slice_kind:
5064 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 case Name_kind:
5066 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5067 /* child nodes of List and Tuple will have expr_context set */
5068 case List_kind:
5069 return compiler_list(c, e);
5070 case Tuple_kind:
5071 return compiler_tuple(c, e);
5072 }
5073 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005074}
5075
5076static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005077compiler_visit_expr(struct compiler *c, expr_ty e)
5078{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005079 int old_lineno = c->u->u_lineno;
5080 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005081 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005082 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005083 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005084 c->u->u_col_offset = old_col_offset;
5085 return res;
5086}
5087
5088static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005089compiler_augassign(struct compiler *c, stmt_ty s)
5090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 expr_ty e = s->v.AugAssign.target;
5092 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 switch (e->kind) {
5097 case Attribute_kind:
5098 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005099 AugLoad, e->lineno, e->col_offset,
5100 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 if (auge == NULL)
5102 return 0;
5103 VISIT(c, expr, auge);
5104 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005105 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 auge->v.Attribute.ctx = AugStore;
5107 VISIT(c, expr, auge);
5108 break;
5109 case Subscript_kind:
5110 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00005111 AugLoad, e->lineno, e->col_offset,
5112 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 if (auge == NULL)
5114 return 0;
5115 VISIT(c, expr, auge);
5116 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005117 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 auge->v.Subscript.ctx = AugStore;
5119 VISIT(c, expr, auge);
5120 break;
5121 case Name_kind:
5122 if (!compiler_nameop(c, e->v.Name.id, Load))
5123 return 0;
5124 VISIT(c, expr, s->v.AugAssign.value);
Andy Lester76d58772020-03-10 21:18:12 -05005125 ADDOP(c, inplace_binop(s->v.AugAssign.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 return compiler_nameop(c, e->v.Name.id, Store);
5127 default:
5128 PyErr_Format(PyExc_SystemError,
5129 "invalid node type (%d) for augmented assignment",
5130 e->kind);
5131 return 0;
5132 }
5133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005134}
5135
5136static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005137check_ann_expr(struct compiler *c, expr_ty e)
5138{
5139 VISIT(c, expr, e);
5140 ADDOP(c, POP_TOP);
5141 return 1;
5142}
5143
5144static int
5145check_annotation(struct compiler *c, stmt_ty s)
5146{
5147 /* Annotations are only evaluated in a module or class. */
5148 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5149 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5150 return check_ann_expr(c, s->v.AnnAssign.annotation);
5151 }
5152 return 1;
5153}
5154
5155static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005156check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005157{
5158 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005159 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005160 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005161 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005162 return 0;
5163 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005164 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5165 return 0;
5166 }
5167 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5168 return 0;
5169 }
5170 return 1;
5171 case Tuple_kind: {
5172 /* extended slice */
5173 asdl_seq *elts = e->v.Tuple.elts;
5174 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005175 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005176 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005177 return 0;
5178 }
5179 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005180 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005181 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005182 default:
5183 return check_ann_expr(c, e);
5184 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005185}
5186
5187static int
5188compiler_annassign(struct compiler *c, stmt_ty s)
5189{
5190 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005191 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005192
5193 assert(s->kind == AnnAssign_kind);
5194
5195 /* We perform the actual assignment first. */
5196 if (s->v.AnnAssign.value) {
5197 VISIT(c, expr, s->v.AnnAssign.value);
5198 VISIT(c, expr, targ);
5199 }
5200 switch (targ->kind) {
5201 case Name_kind:
5202 /* If we have a simple name in a module or class, store annotation. */
5203 if (s->v.AnnAssign.simple &&
5204 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5205 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005206 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5207 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5208 }
5209 else {
5210 VISIT(c, expr, s->v.AnnAssign.annotation);
5211 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005212 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005213 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005214 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005215 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005216 }
5217 break;
5218 case Attribute_kind:
5219 if (!s->v.AnnAssign.value &&
5220 !check_ann_expr(c, targ->v.Attribute.value)) {
5221 return 0;
5222 }
5223 break;
5224 case Subscript_kind:
5225 if (!s->v.AnnAssign.value &&
5226 (!check_ann_expr(c, targ->v.Subscript.value) ||
5227 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5228 return 0;
5229 }
5230 break;
5231 default:
5232 PyErr_Format(PyExc_SystemError,
5233 "invalid node type (%d) for annotated assignment",
5234 targ->kind);
5235 return 0;
5236 }
5237 /* Annotation is evaluated last. */
5238 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5239 return 0;
5240 }
5241 return 1;
5242}
5243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005244/* Raises a SyntaxError and returns 0.
5245 If something goes wrong, a different exception may be raised.
5246*/
5247
5248static int
5249compiler_error(struct compiler *c, const char *errstr)
5250{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005251 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005253
Victor Stinner14e461d2013-08-26 22:28:21 +02005254 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 if (!loc) {
5256 Py_INCREF(Py_None);
5257 loc = Py_None;
5258 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005259 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005260 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 if (!u)
5262 goto exit;
5263 v = Py_BuildValue("(zO)", errstr, u);
5264 if (!v)
5265 goto exit;
5266 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005267 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 Py_DECREF(loc);
5269 Py_XDECREF(u);
5270 Py_XDECREF(v);
5271 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005272}
5273
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005274/* Emits a SyntaxWarning and returns 1 on success.
5275 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5276 and returns 0.
5277*/
5278static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005279compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005280{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005281 va_list vargs;
5282#ifdef HAVE_STDARG_PROTOTYPES
5283 va_start(vargs, format);
5284#else
5285 va_start(vargs);
5286#endif
5287 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5288 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005289 if (msg == NULL) {
5290 return 0;
5291 }
5292 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5293 c->u->u_lineno, NULL, NULL) < 0)
5294 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005295 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005296 /* Replace the SyntaxWarning exception with a SyntaxError
5297 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005298 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005299 assert(PyUnicode_AsUTF8(msg) != NULL);
5300 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005301 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005302 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005303 return 0;
5304 }
5305 Py_DECREF(msg);
5306 return 1;
5307}
5308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005309static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005310compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005311{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005312 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005315 if (ctx == Load) {
5316 if (!check_subscripter(c, e->v.Subscript.value)) {
5317 return 0;
5318 }
5319 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5320 return 0;
5321 }
5322 }
5323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005324 switch (ctx) {
5325 case AugLoad: /* fall through to Load */
5326 case Load: op = BINARY_SUBSCR; break;
5327 case AugStore:/* fall through to Store */
5328 case Store: op = STORE_SUBSCR; break;
5329 case Del: op = DELETE_SUBSCR; break;
Batuhan TaÅŸkaya86892092020-03-15 22:32:17 +03005330 default:
5331 PyErr_Format(PyExc_SystemError,
5332 "expr_context kind %d should not be possible",
5333 ctx);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 return 0;
5335 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005336 if (ctx == AugStore) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005337 ADDOP(c, ROT_THREE);
5338 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005339 else {
5340 VISIT(c, expr, e->v.Subscript.value);
5341 VISIT(c, expr, e->v.Subscript.slice);
5342 if (ctx == AugLoad) {
5343 ADDOP(c, DUP_TOP_TWO);
5344 }
5345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 ADDOP(c, op);
5347 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005348}
5349
5350static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005351compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 int n = 2;
5354 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 /* only handles the cases where BUILD_SLICE is emitted */
5357 if (s->v.Slice.lower) {
5358 VISIT(c, expr, s->v.Slice.lower);
5359 }
5360 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005361 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 if (s->v.Slice.upper) {
5365 VISIT(c, expr, s->v.Slice.upper);
5366 }
5367 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005368 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 }
5370
5371 if (s->v.Slice.step) {
5372 n++;
5373 VISIT(c, expr, s->v.Slice.step);
5374 }
5375 ADDOP_I(c, BUILD_SLICE, n);
5376 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377}
5378
Thomas Wouters89f507f2006-12-13 04:49:30 +00005379/* End of the compiler section, beginning of the assembler section */
5380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005381/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005382 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005383
5384 XXX must handle implicit jumps from one block to next
5385*/
5386
Thomas Wouters89f507f2006-12-13 04:49:30 +00005387struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 PyObject *a_bytecode; /* string containing bytecode */
5389 int a_offset; /* offset into bytecode */
5390 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005391 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 PyObject *a_lnotab; /* string containing lnotab */
5393 int a_lnotab_off; /* offset into lnotab */
5394 int a_lineno; /* last lineno of emitted instruction */
5395 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005396};
5397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398static void
T. Wouters99b54d62019-09-12 07:05:33 -07005399dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400{
T. Wouters99b54d62019-09-12 07:05:33 -07005401 int i, j;
5402
5403 /* Get rid of recursion for normal control flow.
5404 Since the number of blocks is limited, unused space in a_postorder
5405 (from a_nblocks to end) can be used as a stack for still not ordered
5406 blocks. */
5407 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005408 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005409 assert(a->a_nblocks < j);
5410 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 }
T. Wouters99b54d62019-09-12 07:05:33 -07005412 while (j < end) {
5413 b = a->a_postorder[j++];
5414 for (i = 0; i < b->b_iused; i++) {
5415 struct instr *instr = &b->b_instr[i];
5416 if (instr->i_jrel || instr->i_jabs)
5417 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005418 }
T. Wouters99b54d62019-09-12 07:05:33 -07005419 assert(a->a_nblocks < j);
5420 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005422}
5423
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005424Py_LOCAL_INLINE(void)
5425stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005426{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005427 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005428 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005429 assert(b->b_startdepth < 0);
5430 b->b_startdepth = depth;
5431 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005432 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433}
5434
5435/* Find the flow path that needs the largest stack. We assume that
5436 * cycles in the flow graph have no net effect on the stack depth.
5437 */
5438static int
5439stackdepth(struct compiler *c)
5440{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005441 basicblock *b, *entryblock = NULL;
5442 basicblock **stack, **sp;
5443 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 b->b_startdepth = INT_MIN;
5446 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005447 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 }
5449 if (!entryblock)
5450 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005451 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5452 if (!stack) {
5453 PyErr_NoMemory();
5454 return -1;
5455 }
5456
5457 sp = stack;
5458 stackdepth_push(&sp, entryblock, 0);
5459 while (sp != stack) {
5460 b = *--sp;
5461 int depth = b->b_startdepth;
5462 assert(depth >= 0);
5463 basicblock *next = b->b_next;
5464 for (int i = 0; i < b->b_iused; i++) {
5465 struct instr *instr = &b->b_instr[i];
5466 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5467 if (effect == PY_INVALID_STACK_EFFECT) {
5468 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5469 Py_FatalError("PyCompile_OpcodeStackEffect()");
5470 }
5471 int new_depth = depth + effect;
5472 if (new_depth > maxdepth) {
5473 maxdepth = new_depth;
5474 }
5475 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5476 if (instr->i_jrel || instr->i_jabs) {
5477 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5478 assert(effect != PY_INVALID_STACK_EFFECT);
5479 int target_depth = depth + effect;
5480 if (target_depth > maxdepth) {
5481 maxdepth = target_depth;
5482 }
5483 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005484 stackdepth_push(&sp, instr->i_target, target_depth);
5485 }
5486 depth = new_depth;
5487 if (instr->i_opcode == JUMP_ABSOLUTE ||
5488 instr->i_opcode == JUMP_FORWARD ||
5489 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005490 instr->i_opcode == RAISE_VARARGS ||
5491 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005492 {
5493 /* remaining code is dead */
5494 next = NULL;
5495 break;
5496 }
5497 }
5498 if (next != NULL) {
5499 stackdepth_push(&sp, next, depth);
5500 }
5501 }
5502 PyObject_Free(stack);
5503 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005504}
5505
5506static int
5507assemble_init(struct assembler *a, int nblocks, int firstlineno)
5508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 memset(a, 0, sizeof(struct assembler));
5510 a->a_lineno = firstlineno;
5511 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5512 if (!a->a_bytecode)
5513 return 0;
5514 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5515 if (!a->a_lnotab)
5516 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005517 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 PyErr_NoMemory();
5519 return 0;
5520 }
T. Wouters99b54d62019-09-12 07:05:33 -07005521 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005523 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 PyErr_NoMemory();
5525 return 0;
5526 }
5527 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005528}
5529
5530static void
5531assemble_free(struct assembler *a)
5532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 Py_XDECREF(a->a_bytecode);
5534 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005535 if (a->a_postorder)
5536 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005537}
5538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005539static int
5540blocksize(basicblock *b)
5541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 int i;
5543 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005546 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005548}
5549
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005550/* Appends a pair to the end of the line number table, a_lnotab, representing
5551 the instruction's bytecode offset and line number. See
5552 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005553
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005554static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005557 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005558 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005559 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005562 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005563 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005564 }
5565
5566 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5567 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 if (d_bytecode > 255) {
5570 int j, nbytes, ncodes = d_bytecode / 255;
5571 nbytes = a->a_lnotab_off + 2 * ncodes;
5572 len = PyBytes_GET_SIZE(a->a_lnotab);
5573 if (nbytes >= len) {
5574 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5575 len = nbytes;
5576 else if (len <= INT_MAX / 2)
5577 len *= 2;
5578 else {
5579 PyErr_NoMemory();
5580 return 0;
5581 }
5582 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5583 return 0;
5584 }
5585 lnotab = (unsigned char *)
5586 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5587 for (j = 0; j < ncodes; j++) {
5588 *lnotab++ = 255;
5589 *lnotab++ = 0;
5590 }
5591 d_bytecode -= ncodes * 255;
5592 a->a_lnotab_off += ncodes * 2;
5593 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005594 assert(0 <= d_bytecode && d_bytecode <= 255);
5595
5596 if (d_lineno < -128 || 127 < d_lineno) {
5597 int j, nbytes, ncodes, k;
5598 if (d_lineno < 0) {
5599 k = -128;
5600 /* use division on positive numbers */
5601 ncodes = (-d_lineno) / 128;
5602 }
5603 else {
5604 k = 127;
5605 ncodes = d_lineno / 127;
5606 }
5607 d_lineno -= ncodes * k;
5608 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 nbytes = a->a_lnotab_off + 2 * ncodes;
5610 len = PyBytes_GET_SIZE(a->a_lnotab);
5611 if (nbytes >= len) {
5612 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5613 len = nbytes;
5614 else if (len <= INT_MAX / 2)
5615 len *= 2;
5616 else {
5617 PyErr_NoMemory();
5618 return 0;
5619 }
5620 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5621 return 0;
5622 }
5623 lnotab = (unsigned char *)
5624 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5625 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005626 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 d_bytecode = 0;
5628 for (j = 1; j < ncodes; j++) {
5629 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005630 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 a->a_lnotab_off += ncodes * 2;
5633 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005634 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 len = PyBytes_GET_SIZE(a->a_lnotab);
5637 if (a->a_lnotab_off + 2 >= len) {
5638 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5639 return 0;
5640 }
5641 lnotab = (unsigned char *)
5642 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 a->a_lnotab_off += 2;
5645 if (d_bytecode) {
5646 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005647 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 }
5649 else { /* First line of a block; def stmt, etc. */
5650 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005651 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 }
5653 a->a_lineno = i->i_lineno;
5654 a->a_lineno_off = a->a_offset;
5655 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005656}
5657
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005658/* assemble_emit()
5659 Extend the bytecode with a new instruction.
5660 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005661*/
5662
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005663static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005664assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005665{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005666 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005668 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005669
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005670 arg = i->i_oparg;
5671 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 if (i->i_lineno && !assemble_lnotab(a, i))
5673 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005674 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 if (len > PY_SSIZE_T_MAX / 2)
5676 return 0;
5677 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5678 return 0;
5679 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005680 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005682 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005684}
5685
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005686static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005687assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005690 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 /* Compute the size of each block and fixup jump args.
5694 Replace block pointer with position in bytecode. */
5695 do {
5696 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005697 for (i = a->a_nblocks - 1; i >= 0; i--) {
5698 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 bsize = blocksize(b);
5700 b->b_offset = totsize;
5701 totsize += bsize;
5702 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005703 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5705 bsize = b->b_offset;
5706 for (i = 0; i < b->b_iused; i++) {
5707 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005708 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 /* Relative jumps are computed relative to
5710 the instruction pointer after fetching
5711 the jump instruction.
5712 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005713 bsize += isize;
5714 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005716 if (instr->i_jrel) {
5717 instr->i_oparg -= bsize;
5718 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005719 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005720 if (instrsize(instr->i_oparg) != isize) {
5721 extended_arg_recompile = 1;
5722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 }
5725 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 /* XXX: This is an awful hack that could hurt performance, but
5728 on the bright side it should work until we come up
5729 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 The issue is that in the first loop blocksize() is called
5732 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005733 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 So we loop until we stop seeing new EXTENDED_ARGs.
5737 The only EXTENDED_ARGs that could be popping up are
5738 ones in jump instructions. So this should converge
5739 fairly quickly.
5740 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005741 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005742}
5743
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005744static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005745dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005747 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005748 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 tuple = PyTuple_New(size);
5751 if (tuple == NULL)
5752 return NULL;
5753 while (PyDict_Next(dict, &pos, &k, &v)) {
5754 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005755 Py_INCREF(k);
5756 assert((i - offset) < size);
5757 assert((i - offset) >= 0);
5758 PyTuple_SET_ITEM(tuple, i - offset, k);
5759 }
5760 return tuple;
5761}
5762
5763static PyObject *
5764consts_dict_keys_inorder(PyObject *dict)
5765{
5766 PyObject *consts, *k, *v;
5767 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5768
5769 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5770 if (consts == NULL)
5771 return NULL;
5772 while (PyDict_Next(dict, &pos, &k, &v)) {
5773 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005774 /* The keys of the dictionary can be tuples wrapping a contant.
5775 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5776 * the object we want is always second. */
5777 if (PyTuple_CheckExact(k)) {
5778 k = PyTuple_GET_ITEM(k, 1);
5779 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005781 assert(i < size);
5782 assert(i >= 0);
5783 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005784 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005785 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005786}
5787
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005788static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005789compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005792 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005794 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005795 if (ste->ste_nested)
5796 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005797 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005799 if (!ste->ste_generator && ste->ste_coroutine)
5800 flags |= CO_COROUTINE;
5801 if (ste->ste_generator && ste->ste_coroutine)
5802 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 if (ste->ste_varargs)
5804 flags |= CO_VARARGS;
5805 if (ste->ste_varkeywords)
5806 flags |= CO_VARKEYWORDS;
5807 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 /* (Only) inherit compilerflags in PyCF_MASK */
5810 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005811
Pablo Galindo90235812020-03-15 04:29:22 +00005812 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005813 ste->ste_coroutine &&
5814 !ste->ste_generator) {
5815 flags |= CO_COROUTINE;
5816 }
5817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005819}
5820
INADA Naokic2e16072018-11-26 21:23:22 +09005821// Merge *tuple* with constant cache.
5822// Unlike merge_consts_recursive(), this function doesn't work recursively.
5823static int
5824merge_const_tuple(struct compiler *c, PyObject **tuple)
5825{
5826 assert(PyTuple_CheckExact(*tuple));
5827
5828 PyObject *key = _PyCode_ConstantKey(*tuple);
5829 if (key == NULL) {
5830 return 0;
5831 }
5832
5833 // t is borrowed reference
5834 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5835 Py_DECREF(key);
5836 if (t == NULL) {
5837 return 0;
5838 }
5839 if (t == key) { // tuple is new constant.
5840 return 1;
5841 }
5842
5843 PyObject *u = PyTuple_GET_ITEM(t, 1);
5844 Py_INCREF(u);
5845 Py_DECREF(*tuple);
5846 *tuple = u;
5847 return 1;
5848}
5849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005850static PyCodeObject *
5851makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 PyObject *tmp;
5854 PyCodeObject *co = NULL;
5855 PyObject *consts = NULL;
5856 PyObject *names = NULL;
5857 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 PyObject *name = NULL;
5859 PyObject *freevars = NULL;
5860 PyObject *cellvars = NULL;
5861 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005862 Py_ssize_t nlocals;
5863 int nlocals_int;
5864 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005865 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005866
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005867 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 names = dict_keys_inorder(c->u->u_names, 0);
5869 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5870 if (!consts || !names || !varnames)
5871 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5874 if (!cellvars)
5875 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005876 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 if (!freevars)
5878 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005879
INADA Naokic2e16072018-11-26 21:23:22 +09005880 if (!merge_const_tuple(c, &names) ||
5881 !merge_const_tuple(c, &varnames) ||
5882 !merge_const_tuple(c, &cellvars) ||
5883 !merge_const_tuple(c, &freevars))
5884 {
5885 goto error;
5886 }
5887
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005888 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005889 assert(nlocals < INT_MAX);
5890 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 flags = compute_code_flags(c);
5893 if (flags < 0)
5894 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5897 if (!bytecode)
5898 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5901 if (!tmp)
5902 goto error;
5903 Py_DECREF(consts);
5904 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005905 if (!merge_const_tuple(c, &consts)) {
5906 goto error;
5907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005909 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005910 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005911 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005912 maxdepth = stackdepth(c);
5913 if (maxdepth < 0) {
5914 goto error;
5915 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005916 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005917 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005918 maxdepth, flags, bytecode, consts, names,
5919 varnames, freevars, cellvars, c->c_filename,
5920 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005921 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 Py_XDECREF(consts);
5923 Py_XDECREF(names);
5924 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 Py_XDECREF(name);
5926 Py_XDECREF(freevars);
5927 Py_XDECREF(cellvars);
5928 Py_XDECREF(bytecode);
5929 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005930}
5931
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005932
5933/* For debugging purposes only */
5934#if 0
5935static void
5936dump_instr(const struct instr *i)
5937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 const char *jrel = i->i_jrel ? "jrel " : "";
5939 const char *jabs = i->i_jabs ? "jabs " : "";
5940 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005943 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5947 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005948}
5949
5950static void
5951dump_basicblock(const basicblock *b)
5952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 const char *seen = b->b_seen ? "seen " : "";
5954 const char *b_return = b->b_return ? "return " : "";
5955 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5956 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5957 if (b->b_instr) {
5958 int i;
5959 for (i = 0; i < b->b_iused; i++) {
5960 fprintf(stderr, " [%02d] ", i);
5961 dump_instr(b->b_instr + i);
5962 }
5963 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005964}
5965#endif
5966
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005967static PyCodeObject *
5968assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005970 basicblock *b, *entryblock;
5971 struct assembler a;
5972 int i, j, nblocks;
5973 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 /* Make sure every block that falls off the end returns None.
5976 XXX NEXT_BLOCK() isn't quite right, because if the last
5977 block ends with a jump or return b_next shouldn't set.
5978 */
5979 if (!c->u->u_curblock->b_return) {
5980 NEXT_BLOCK(c);
5981 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005982 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005983 ADDOP(c, RETURN_VALUE);
5984 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 nblocks = 0;
5987 entryblock = NULL;
5988 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5989 nblocks++;
5990 entryblock = b;
5991 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 /* Set firstlineno if it wasn't explicitly set. */
5994 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005995 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5997 else
5998 c->u->u_firstlineno = 1;
5999 }
6000 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6001 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006002 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 /* Can't modify the bytecode after computing jump offsets. */
6005 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006006
T. Wouters99b54d62019-09-12 07:05:33 -07006007 /* Emit code in reverse postorder from dfs. */
6008 for (i = a.a_nblocks - 1; i >= 0; i--) {
6009 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 for (j = 0; j < b->b_iused; j++)
6011 if (!assemble_emit(&a, &b->b_instr[j]))
6012 goto error;
6013 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6016 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006017 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006020 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006021 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 assemble_free(&a);
6023 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006024}
Georg Brandl8334fd92010-12-04 10:26:46 +00006025
6026#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006027PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006028PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6029 PyArena *arena)
6030{
6031 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6032}