blob: a8ab873f319f9037aa9e55090ded0537b3a1f11a [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
Pablo Galindod112c602020-03-18 23:02:09 +0000357 _PyASTOptimizeState state;
358 state.optimize = c.c_optimize;
359 state.ff_features = merged;
360
361 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900362 goto finally;
363 }
364
Victor Stinner14e461d2013-08-26 22:28:21 +0200365 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (c.c_st == NULL) {
367 if (!PyErr_Occurred())
368 PyErr_SetString(PyExc_SystemError, "no symtable");
369 goto finally;
370 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373
Thomas Wouters1175c432006-02-27 22:49:54 +0000374 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 compiler_free(&c);
376 assert(co || PyErr_Occurred());
377 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378}
379
380PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200381PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
382 int optimize, PyArena *arena)
383{
384 PyObject *filename;
385 PyCodeObject *co;
386 filename = PyUnicode_DecodeFSDefault(filename_str);
387 if (filename == NULL)
388 return NULL;
389 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
390 Py_DECREF(filename);
391 return co;
392
393}
394
395PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396PyNode_Compile(struct _node *n, const char *filename)
397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyCodeObject *co = NULL;
399 mod_ty mod;
400 PyArena *arena = PyArena_New();
401 if (!arena)
402 return NULL;
403 mod = PyAST_FromNode(n, NULL, filename, arena);
404 if (mod)
405 co = PyAST_Compile(mod, filename, NULL, arena);
406 PyArena_Free(arena);
407 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000408}
409
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000410static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000411compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (c->c_st)
414 PySymtable_Free(c->c_st);
415 if (c->c_future)
416 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200417 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900418 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000420}
421
Guido van Rossum79f25d91997-04-29 20:08:16 +0000422static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_ssize_t i, n;
426 PyObject *v, *k;
427 PyObject *dict = PyDict_New();
428 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 n = PyList_Size(list);
431 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100432 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (!v) {
434 Py_DECREF(dict);
435 return NULL;
436 }
437 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300438 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_DECREF(v);
440 Py_DECREF(dict);
441 return NULL;
442 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_DECREF(v);
444 }
445 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000446}
447
448/* Return new dict containing names from src that match scope(s).
449
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000452values are integers, starting at offset and increasing by one for
453each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454*/
455
456static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100457dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700459 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500461 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 assert(offset >= 0);
464 if (dest == NULL)
465 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466
Meador Inge2ca63152012-07-18 14:20:11 -0500467 /* Sort the keys so that we have a deterministic order on the indexes
468 saved in the returned dictionary. These indexes are used as indexes
469 into the free and cell var storage. Therefore if they aren't
470 deterministic, then the generated bytecode is not deterministic.
471 */
472 sorted_keys = PyDict_Keys(src);
473 if (sorted_keys == NULL)
474 return NULL;
475 if (PyList_Sort(sorted_keys) != 0) {
476 Py_DECREF(sorted_keys);
477 return NULL;
478 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500479 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500480
481 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* XXX this should probably be a macro in symtable.h */
483 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500484 k = PyList_GET_ITEM(sorted_keys, key_i);
485 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 assert(PyLong_Check(v));
487 vi = PyLong_AS_LONG(v);
488 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300491 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500493 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 Py_DECREF(dest);
495 return NULL;
496 }
497 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300498 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_DECREF(item);
501 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 return NULL;
503 }
504 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 }
506 }
Meador Inge2ca63152012-07-18 14:20:11 -0500507 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000509}
510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511static void
512compiler_unit_check(struct compiler_unit *u)
513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 basicblock *block;
515 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700516 assert((uintptr_t)block != 0xcbcbcbcbU);
517 assert((uintptr_t)block != 0xfbfbfbfbU);
518 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (block->b_instr != NULL) {
520 assert(block->b_ialloc > 0);
521 assert(block->b_iused > 0);
522 assert(block->b_ialloc >= block->b_iused);
523 }
524 else {
525 assert (block->b_iused == 0);
526 assert (block->b_ialloc == 0);
527 }
528 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static void
532compiler_unit_free(struct compiler_unit *u)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 compiler_unit_check(u);
537 b = u->u_blocks;
538 while (b != NULL) {
539 if (b->b_instr)
540 PyObject_Free((void *)b->b_instr);
541 next = b->b_list;
542 PyObject_Free((void *)b);
543 b = next;
544 }
545 Py_CLEAR(u->u_ste);
546 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400547 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_CLEAR(u->u_consts);
549 Py_CLEAR(u->u_names);
550 Py_CLEAR(u->u_varnames);
551 Py_CLEAR(u->u_freevars);
552 Py_CLEAR(u->u_cellvars);
553 Py_CLEAR(u->u_private);
554 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555}
556
557static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100558compiler_enter_scope(struct compiler *c, identifier name,
559 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100562 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
565 struct compiler_unit));
566 if (!u) {
567 PyErr_NoMemory();
568 return 0;
569 }
570 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100571 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100573 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 u->u_kwonlyargcount = 0;
575 u->u_ste = PySymtable_Lookup(c->c_st, key);
576 if (!u->u_ste) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 Py_INCREF(name);
581 u->u_name = name;
582 u->u_varnames = list2dict(u->u_ste->ste_varnames);
583 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
584 if (!u->u_varnames || !u->u_cellvars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000589 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300591 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500592 int res;
593 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200594 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500595 name = _PyUnicode_FromId(&PyId___class__);
596 if (!name) {
597 compiler_unit_free(u);
598 return 0;
599 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300600 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 if (res < 0) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200608 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (!u->u_freevars) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_blocks = NULL;
615 u->u_nfblocks = 0;
616 u->u_firstlineno = lineno;
617 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000618 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 u->u_consts = PyDict_New();
620 if (!u->u_consts) {
621 compiler_unit_free(u);
622 return 0;
623 }
624 u->u_names = PyDict_New();
625 if (!u->u_names) {
626 compiler_unit_free(u);
627 return 0;
628 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* Push the old compiler_unit on the stack. */
633 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400634 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
636 Py_XDECREF(capsule);
637 compiler_unit_free(u);
638 return 0;
639 }
640 Py_DECREF(capsule);
641 u->u_private = c->u->u_private;
642 Py_XINCREF(u->u_private);
643 }
644 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100647
648 block = compiler_new_block(c);
649 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100651 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400653 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
654 if (!compiler_set_qualname(c))
655 return 0;
656 }
657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659}
660
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000661static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662compiler_exit_scope(struct compiler *c)
663{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100664 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 c->c_nestlevel--;
668 compiler_unit_free(c->u);
669 /* Restore c->u to the parent unit. */
670 n = PyList_GET_SIZE(c->c_stack) - 1;
671 if (n >= 0) {
672 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400673 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 assert(c->u);
675 /* we are deleting from a list so this really shouldn't fail */
676 if (PySequence_DelItem(c->c_stack, n) < 0)
677 Py_FatalError("compiler_exit_scope()");
678 compiler_unit_check(c->u);
679 }
680 else
681 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683}
684
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400685static int
686compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100687{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100688 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400689 _Py_static_string(dot_locals, ".<locals>");
690 Py_ssize_t stack_size;
691 struct compiler_unit *u = c->u;
692 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100695 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400696 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400697 if (stack_size > 1) {
698 int scope, force_global = 0;
699 struct compiler_unit *parent;
700 PyObject *mangled, *capsule;
701
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400702 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400703 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 assert(parent);
705
Yury Selivanov75445082015-05-11 22:57:16 -0400706 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
707 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
708 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 assert(u->u_name);
710 mangled = _Py_Mangle(parent->u_private, u->u_name);
711 if (!mangled)
712 return 0;
713 scope = PyST_GetScope(parent->u_ste, mangled);
714 Py_DECREF(mangled);
715 assert(scope != GLOBAL_IMPLICIT);
716 if (scope == GLOBAL_EXPLICIT)
717 force_global = 1;
718 }
719
720 if (!force_global) {
721 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400722 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400723 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
724 dot_locals_str = _PyUnicode_FromId(&dot_locals);
725 if (dot_locals_str == NULL)
726 return 0;
727 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
728 if (base == NULL)
729 return 0;
730 }
731 else {
732 Py_INCREF(parent->u_qualname);
733 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400734 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100735 }
736 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400737
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400738 if (base != NULL) {
739 dot_str = _PyUnicode_FromId(&dot);
740 if (dot_str == NULL) {
741 Py_DECREF(base);
742 return 0;
743 }
744 name = PyUnicode_Concat(base, dot_str);
745 Py_DECREF(base);
746 if (name == NULL)
747 return 0;
748 PyUnicode_Append(&name, u->u_name);
749 if (name == NULL)
750 return 0;
751 }
752 else {
753 Py_INCREF(u->u_name);
754 name = u->u_name;
755 }
756 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100757
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400758 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100759}
760
Eric V. Smith235a6f02015-09-19 14:51:32 -0400761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762/* Allocate a new block and return a pointer to it.
763 Returns NULL on error.
764*/
765
766static basicblock *
767compiler_new_block(struct compiler *c)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 basicblock *b;
770 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 u = c->u;
773 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
774 if (b == NULL) {
775 PyErr_NoMemory();
776 return NULL;
777 }
778 memset((void *)b, 0, sizeof(basicblock));
779 /* Extend the singly linked list of blocks with new block. */
780 b->b_list = u->u_blocks;
781 u->u_blocks = b;
782 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786compiler_next_block(struct compiler *c)
787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 basicblock *block = compiler_new_block(c);
789 if (block == NULL)
790 return NULL;
791 c->u->u_curblock->b_next = block;
792 c->u->u_curblock = block;
793 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794}
795
796static basicblock *
797compiler_use_next_block(struct compiler *c, basicblock *block)
798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 assert(block != NULL);
800 c->u->u_curblock->b_next = block;
801 c->u->u_curblock = block;
802 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803}
804
805/* Returns the offset of the next instruction in the current block's
806 b_instr array. Resizes the b_instr as necessary.
807 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000808*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000809
810static int
Andy Lester76d58772020-03-10 21:18:12 -0500811compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 assert(b != NULL);
814 if (b->b_instr == NULL) {
815 b->b_instr = (struct instr *)PyObject_Malloc(
816 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
817 if (b->b_instr == NULL) {
818 PyErr_NoMemory();
819 return -1;
820 }
821 b->b_ialloc = DEFAULT_BLOCK_SIZE;
822 memset((char *)b->b_instr, 0,
823 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
824 }
825 else if (b->b_iused == b->b_ialloc) {
826 struct instr *tmp;
827 size_t oldsize, newsize;
828 oldsize = b->b_ialloc * sizeof(struct instr);
829 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000830
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700831 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 PyErr_NoMemory();
833 return -1;
834 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (newsize == 0) {
837 PyErr_NoMemory();
838 return -1;
839 }
840 b->b_ialloc <<= 1;
841 tmp = (struct instr *)PyObject_Realloc(
842 (void *)b->b_instr, newsize);
843 if (tmp == NULL) {
844 PyErr_NoMemory();
845 return -1;
846 }
847 b->b_instr = tmp;
848 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
849 }
850 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000851}
852
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200853/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854
Christian Heimes2202f872008-02-06 14:31:34 +0000855 The line number is reset in the following cases:
856 - when entering a new scope
857 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200858 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200859 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000860*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200862#define SET_LOC(c, x) \
863 (c)->u->u_lineno = (x)->lineno; \
864 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200866/* Return the stack effect of opcode with argument oparg.
867
868 Some opcodes have different stack effect when jump to the target and
869 when not jump. The 'jump' parameter specifies the case:
870
871 * 0 -- when not jump
872 * 1 -- when jump
873 * -1 -- maximal
874 */
875/* XXX Make the stack effect of WITH_CLEANUP_START and
876 WITH_CLEANUP_FINISH deterministic. */
877static int
878stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300881 case NOP:
882 case EXTENDED_ARG:
883 return 0;
884
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200885 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 case POP_TOP:
887 return -1;
888 case ROT_TWO:
889 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200890 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return 0;
892 case DUP_TOP:
893 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000894 case DUP_TOP_TWO:
895 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000896
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200897 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case UNARY_POSITIVE:
899 case UNARY_NEGATIVE:
900 case UNARY_NOT:
901 case UNARY_INVERT:
902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case SET_ADD:
905 case LIST_APPEND:
906 return -1;
907 case MAP_ADD:
908 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000909
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200910 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case BINARY_POWER:
912 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400913 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_MODULO:
915 case BINARY_ADD:
916 case BINARY_SUBTRACT:
917 case BINARY_SUBSCR:
918 case BINARY_FLOOR_DIVIDE:
919 case BINARY_TRUE_DIVIDE:
920 return -1;
921 case INPLACE_FLOOR_DIVIDE:
922 case INPLACE_TRUE_DIVIDE:
923 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case INPLACE_ADD:
926 case INPLACE_SUBTRACT:
927 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400928 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 case INPLACE_MODULO:
930 return -1;
931 case STORE_SUBSCR:
932 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case DELETE_SUBSCR:
934 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 case BINARY_LSHIFT:
937 case BINARY_RSHIFT:
938 case BINARY_AND:
939 case BINARY_XOR:
940 case BINARY_OR:
941 return -1;
942 case INPLACE_POWER:
943 return -1;
944 case GET_ITER:
945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 case PRINT_EXPR:
948 return -1;
949 case LOAD_BUILD_CLASS:
950 return 1;
951 case INPLACE_LSHIFT:
952 case INPLACE_RSHIFT:
953 case INPLACE_AND:
954 case INPLACE_XOR:
955 case INPLACE_OR:
956 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 /* 1 in the normal flow.
960 * Restore the stack position and push 6 values before jumping to
961 * the handler if an exception be raised. */
962 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case RETURN_VALUE:
964 return -1;
965 case IMPORT_STAR:
966 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700967 case SETUP_ANNOTATIONS:
968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case YIELD_VALUE:
970 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500971 case YIELD_FROM:
972 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case POP_BLOCK:
974 return 0;
975 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case STORE_NAME:
979 return -1;
980 case DELETE_NAME:
981 return 0;
982 case UNPACK_SEQUENCE:
983 return oparg-1;
984 case UNPACK_EX:
985 return (oparg&0xFF) + (oparg>>8);
986 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200987 /* -1 at end of iterator, 1 if continue iterating. */
988 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case STORE_ATTR:
991 return -2;
992 case DELETE_ATTR:
993 return -1;
994 case STORE_GLOBAL:
995 return -1;
996 case DELETE_GLOBAL:
997 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case LOAD_CONST:
999 return 1;
1000 case LOAD_NAME:
1001 return 1;
1002 case BUILD_TUPLE:
1003 case BUILD_LIST:
1004 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001005 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return 1-oparg;
1007 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001008 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001009 case BUILD_CONST_KEY_MAP:
1010 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 case LOAD_ATTR:
1012 return 0;
1013 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001014 case IS_OP:
1015 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001017 case JUMP_IF_NOT_EXC_MATCH:
1018 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case IMPORT_NAME:
1020 return -1;
1021 case IMPORT_FROM:
1022 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001024 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 case JUMP_ABSOLUTE:
1027 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001029 case JUMP_IF_TRUE_OR_POP:
1030 case JUMP_IF_FALSE_OR_POP:
1031 return jump ? 0 : -1;
1032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case POP_JUMP_IF_FALSE:
1034 case POP_JUMP_IF_TRUE:
1035 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case LOAD_GLOBAL:
1038 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001039
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001040 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001042 /* 0 in the normal flow.
1043 * Restore the stack position and push 6 values before jumping to
1044 * the handler if an exception be raised. */
1045 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001046 case RERAISE:
1047 return -3;
1048
1049 case WITH_EXCEPT_START:
1050 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case LOAD_FAST:
1053 return 1;
1054 case STORE_FAST:
1055 return -1;
1056 case DELETE_FAST:
1057 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 case RAISE_VARARGS:
1060 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001061
1062 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001064 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001065 case CALL_METHOD:
1066 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001068 return -oparg-1;
1069 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001070 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001071 case MAKE_FUNCTION:
1072 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1073 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 case BUILD_SLICE:
1075 if (oparg == 3)
1076 return -2;
1077 else
1078 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001080 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 case LOAD_CLOSURE:
1082 return 1;
1083 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001084 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 return 1;
1086 case STORE_DEREF:
1087 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001088 case DELETE_DEREF:
1089 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001090
1091 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001092 case GET_AWAITABLE:
1093 return 0;
1094 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001095 /* 0 in the normal flow.
1096 * Restore the stack position to the position before the result
1097 * of __aenter__ and push 6 values before jumping to the handler
1098 * if an exception be raised. */
1099 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001100 case BEFORE_ASYNC_WITH:
1101 return 1;
1102 case GET_AITER:
1103 return 0;
1104 case GET_ANEXT:
1105 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001106 case GET_YIELD_FROM_ITER:
1107 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001108 case END_ASYNC_FOR:
1109 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001110 case FORMAT_VALUE:
1111 /* If there's a fmt_spec on the stack, we go from 2->1,
1112 else 1->1. */
1113 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001114 case LOAD_METHOD:
1115 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001116 case LOAD_ASSERTION_ERROR:
1117 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001118 case LIST_TO_TUPLE:
1119 return 0;
1120 case LIST_EXTEND:
1121 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001122 case DICT_MERGE:
1123 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001124 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001126 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 }
Larry Hastings3a907972013-11-23 14:49:22 -08001128 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129}
1130
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001131int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001132PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1133{
1134 return stack_effect(opcode, oparg, jump);
1135}
1136
1137int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001138PyCompile_OpcodeStackEffect(int opcode, int oparg)
1139{
1140 return stack_effect(opcode, oparg, -1);
1141}
1142
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143/* Add an opcode with no argument.
1144 Returns 0 on failure, 1 on success.
1145*/
1146
1147static int
1148compiler_addop(struct compiler *c, int opcode)
1149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 basicblock *b;
1151 struct instr *i;
1152 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001153 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001154 if (c->c_do_not_emit_bytecode) {
1155 return 1;
1156 }
Andy Lester76d58772020-03-10 21:18:12 -05001157 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (off < 0)
1159 return 0;
1160 b = c->u->u_curblock;
1161 i = &b->b_instr[off];
1162 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001163 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (opcode == RETURN_VALUE)
1165 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001166 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168}
1169
Victor Stinnerf8e32212013-11-19 23:56:34 +01001170static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001171compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001173 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001176 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001178 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001180 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001181 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001182 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return -1;
1185 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001186 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_DECREF(v);
1188 return -1;
1189 }
1190 Py_DECREF(v);
1191 }
1192 else
1193 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001194 return arg;
1195}
1196
INADA Naokic2e16072018-11-26 21:23:22 +09001197// Merge const *o* recursively and return constant key object.
1198static PyObject*
1199merge_consts_recursive(struct compiler *c, PyObject *o)
1200{
1201 // None and Ellipsis are singleton, and key is the singleton.
1202 // No need to merge object and key.
1203 if (o == Py_None || o == Py_Ellipsis) {
1204 Py_INCREF(o);
1205 return o;
1206 }
1207
1208 PyObject *key = _PyCode_ConstantKey(o);
1209 if (key == NULL) {
1210 return NULL;
1211 }
1212
1213 // t is borrowed reference
1214 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1215 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001216 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001217 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001218 Py_DECREF(key);
1219 return t;
1220 }
1221
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001223 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001225 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001226 Py_ssize_t len = PyTuple_GET_SIZE(o);
1227 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001228 PyObject *item = PyTuple_GET_ITEM(o, i);
1229 PyObject *u = merge_consts_recursive(c, item);
1230 if (u == NULL) {
1231 Py_DECREF(key);
1232 return NULL;
1233 }
1234
1235 // See _PyCode_ConstantKey()
1236 PyObject *v; // borrowed
1237 if (PyTuple_CheckExact(u)) {
1238 v = PyTuple_GET_ITEM(u, 1);
1239 }
1240 else {
1241 v = u;
1242 }
1243 if (v != item) {
1244 Py_INCREF(v);
1245 PyTuple_SET_ITEM(o, i, v);
1246 Py_DECREF(item);
1247 }
1248
1249 Py_DECREF(u);
1250 }
1251 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001253 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // constant keys.
1255 // See _PyCode_ConstantKey() for detail.
1256 assert(PyTuple_CheckExact(key));
1257 assert(PyTuple_GET_SIZE(key) == 2);
1258
1259 Py_ssize_t len = PySet_GET_SIZE(o);
1260 if (len == 0) { // empty frozenset should not be re-created.
1261 return key;
1262 }
1263 PyObject *tuple = PyTuple_New(len);
1264 if (tuple == NULL) {
1265 Py_DECREF(key);
1266 return NULL;
1267 }
1268 Py_ssize_t i = 0, pos = 0;
1269 PyObject *item;
1270 Py_hash_t hash;
1271 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1272 PyObject *k = merge_consts_recursive(c, item);
1273 if (k == NULL) {
1274 Py_DECREF(tuple);
1275 Py_DECREF(key);
1276 return NULL;
1277 }
1278 PyObject *u;
1279 if (PyTuple_CheckExact(k)) {
1280 u = PyTuple_GET_ITEM(k, 1);
1281 Py_INCREF(u);
1282 Py_DECREF(k);
1283 }
1284 else {
1285 u = k;
1286 }
1287 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1288 i++;
1289 }
1290
1291 // Instead of rewriting o, we create new frozenset and embed in the
1292 // key tuple. Caller should get merged frozenset from the key tuple.
1293 PyObject *new = PyFrozenSet_New(tuple);
1294 Py_DECREF(tuple);
1295 if (new == NULL) {
1296 Py_DECREF(key);
1297 return NULL;
1298 }
1299 assert(PyTuple_GET_ITEM(key, 1) == o);
1300 Py_DECREF(o);
1301 PyTuple_SET_ITEM(key, 1, new);
1302 }
INADA Naokic2e16072018-11-26 21:23:22 +09001303
1304 return key;
1305}
1306
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001307static Py_ssize_t
1308compiler_add_const(struct compiler *c, PyObject *o)
1309{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001310 if (c->c_do_not_emit_bytecode) {
1311 return 0;
1312 }
1313
INADA Naokic2e16072018-11-26 21:23:22 +09001314 PyObject *key = merge_consts_recursive(c, o);
1315 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001316 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001317 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001318
Andy Lester76d58772020-03-10 21:18:12 -05001319 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001320 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325compiler_addop_load_const(struct compiler *c, PyObject *o)
1326{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001327 if (c->c_do_not_emit_bytecode) {
1328 return 1;
1329 }
1330
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001331 Py_ssize_t arg = compiler_add_const(c, o);
1332 if (arg < 0)
1333 return 0;
1334 return compiler_addop_i(c, LOAD_CONST, arg);
1335}
1336
1337static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001341 if (c->c_do_not_emit_bytecode) {
1342 return 1;
1343 }
1344
Andy Lester76d58772020-03-10 21:18:12 -05001345 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001347 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348 return compiler_addop_i(c, opcode, arg);
1349}
1350
1351static int
1352compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001355 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001356
1357 if (c->c_do_not_emit_bytecode) {
1358 return 1;
1359 }
1360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1362 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001363 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001364 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365 Py_DECREF(mangled);
1366 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001367 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 return compiler_addop_i(c, opcode, arg);
1369}
1370
1371/* Add an opcode with an integer argument.
1372 Returns 0 on failure, 1 on success.
1373*/
1374
1375static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001376compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 struct instr *i;
1379 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001380
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001381 if (c->c_do_not_emit_bytecode) {
1382 return 1;
1383 }
1384
Victor Stinner2ad474b2016-03-01 23:34:47 +01001385 /* oparg value is unsigned, but a signed C int is usually used to store
1386 it in the C code (like Python/ceval.c).
1387
1388 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1389
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001390 The argument of a concrete bytecode instruction is limited to 8-bit.
1391 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1392 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001393 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001394
Andy Lester76d58772020-03-10 21:18:12 -05001395 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (off < 0)
1397 return 0;
1398 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001399 i->i_opcode = opcode;
1400 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001401 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403}
1404
1405static int
1406compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 struct instr *i;
1409 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001411 if (c->c_do_not_emit_bytecode) {
1412 return 1;
1413 }
1414
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001415 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001417 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (off < 0)
1419 return 0;
1420 i = &c->u->u_curblock->b_instr[off];
1421 i->i_opcode = opcode;
1422 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (absolute)
1424 i->i_jabs = 1;
1425 else
1426 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001427 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429}
1430
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001431/* NEXT_BLOCK() creates an implicit jump from the current block
1432 to the new block.
1433
1434 The returns inside this macro make it impossible to decref objects
1435 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (compiler_next_block((C)) == NULL) \
1439 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
1442#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (!compiler_addop((C), (OP))) \
1444 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445}
1446
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001447#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (!compiler_addop((C), (OP))) { \
1449 compiler_exit_scope(c); \
1450 return 0; \
1451 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001452}
1453
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001454#define ADDOP_LOAD_CONST(C, O) { \
1455 if (!compiler_addop_load_const((C), (O))) \
1456 return 0; \
1457}
1458
1459/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1460#define ADDOP_LOAD_CONST_NEW(C, O) { \
1461 PyObject *__new_const = (O); \
1462 if (__new_const == NULL) { \
1463 return 0; \
1464 } \
1465 if (!compiler_addop_load_const((C), __new_const)) { \
1466 Py_DECREF(__new_const); \
1467 return 0; \
1468 } \
1469 Py_DECREF(__new_const); \
1470}
1471
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1474 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475}
1476
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001477/* Same as ADDOP_O, but steals a reference. */
1478#define ADDOP_N(C, OP, O, TYPE) { \
1479 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1480 Py_DECREF((O)); \
1481 return 0; \
1482 } \
1483 Py_DECREF((O)); \
1484}
1485
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1488 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489}
1490
1491#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 if (!compiler_addop_i((C), (OP), (O))) \
1493 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494}
1495
1496#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (!compiler_addop_j((C), (OP), (O), 1)) \
1498 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499}
1500
1501#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (!compiler_addop_j((C), (OP), (O), 0)) \
1503 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504}
1505
Mark Shannon9af0e472020-01-14 10:12:45 +00001506
1507#define ADDOP_COMPARE(C, CMP) { \
1508 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1509 return 0; \
1510}
1511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1513 the ASDL name to synthesize the name of the C type and the visit function.
1514*/
1515
1516#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (!compiler_visit_ ## TYPE((C), (V))) \
1518 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001521#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_visit_ ## TYPE((C), (V))) { \
1523 compiler_exit_scope(c); \
1524 return 0; \
1525 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001526}
1527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (!compiler_visit_slice((C), (V), (CTX))) \
1530 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531}
1532
1533#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 int _i; \
1535 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1536 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1537 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1538 if (!compiler_visit_ ## TYPE((C), elt)) \
1539 return 0; \
1540 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001541}
1542
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001543#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 int _i; \
1545 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1546 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1547 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1548 if (!compiler_visit_ ## TYPE((C), elt)) { \
1549 compiler_exit_scope(c); \
1550 return 0; \
1551 } \
1552 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001553}
1554
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001555/* These macros allows to check only for errors and not emmit bytecode
1556 * while visiting nodes.
1557*/
1558
1559#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1560 c->c_do_not_emit_bytecode++;
1561
1562#define END_DO_NOT_EMIT_BYTECODE \
1563 c->c_do_not_emit_bytecode--; \
1564}
1565
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001566/* Search if variable annotations are present statically in a block. */
1567
1568static int
1569find_ann(asdl_seq *stmts)
1570{
1571 int i, j, res = 0;
1572 stmt_ty st;
1573
1574 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1575 st = (stmt_ty)asdl_seq_GET(stmts, i);
1576 switch (st->kind) {
1577 case AnnAssign_kind:
1578 return 1;
1579 case For_kind:
1580 res = find_ann(st->v.For.body) ||
1581 find_ann(st->v.For.orelse);
1582 break;
1583 case AsyncFor_kind:
1584 res = find_ann(st->v.AsyncFor.body) ||
1585 find_ann(st->v.AsyncFor.orelse);
1586 break;
1587 case While_kind:
1588 res = find_ann(st->v.While.body) ||
1589 find_ann(st->v.While.orelse);
1590 break;
1591 case If_kind:
1592 res = find_ann(st->v.If.body) ||
1593 find_ann(st->v.If.orelse);
1594 break;
1595 case With_kind:
1596 res = find_ann(st->v.With.body);
1597 break;
1598 case AsyncWith_kind:
1599 res = find_ann(st->v.AsyncWith.body);
1600 break;
1601 case Try_kind:
1602 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1603 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1604 st->v.Try.handlers, j);
1605 if (find_ann(handler->v.ExceptHandler.body)) {
1606 return 1;
1607 }
1608 }
1609 res = find_ann(st->v.Try.body) ||
1610 find_ann(st->v.Try.finalbody) ||
1611 find_ann(st->v.Try.orelse);
1612 break;
1613 default:
1614 res = 0;
1615 }
1616 if (res) {
1617 break;
1618 }
1619 }
1620 return res;
1621}
1622
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001623/*
1624 * Frame block handling functions
1625 */
1626
1627static int
1628compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001629 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001630{
1631 struct fblockinfo *f;
1632 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1633 PyErr_SetString(PyExc_SyntaxError,
1634 "too many statically nested blocks");
1635 return 0;
1636 }
1637 f = &c->u->u_fblock[c->u->u_nfblocks++];
1638 f->fb_type = t;
1639 f->fb_block = b;
1640 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001641 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001642 return 1;
1643}
1644
1645static void
1646compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1647{
1648 struct compiler_unit *u = c->u;
1649 assert(u->u_nfblocks > 0);
1650 u->u_nfblocks--;
1651 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1652 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1653}
1654
Mark Shannonfee55262019-11-21 09:11:43 +00001655static int
1656compiler_call_exit_with_nones(struct compiler *c) {
1657 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1658 ADDOP(c, DUP_TOP);
1659 ADDOP(c, DUP_TOP);
1660 ADDOP_I(c, CALL_FUNCTION, 3);
1661 return 1;
1662}
1663
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001664/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001665 * popping the blocks will be restored afterwards, unless another
1666 * return, break or continue is found. In which case, the TOS will
1667 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001668 */
1669static int
1670compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1671 int preserve_tos)
1672{
1673 switch (info->fb_type) {
1674 case WHILE_LOOP:
1675 return 1;
1676
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001677 case FOR_LOOP:
1678 /* Pop the iterator */
1679 if (preserve_tos) {
1680 ADDOP(c, ROT_TWO);
1681 }
1682 ADDOP(c, POP_TOP);
1683 return 1;
1684
1685 case EXCEPT:
1686 ADDOP(c, POP_BLOCK);
1687 return 1;
1688
1689 case FINALLY_TRY:
1690 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001691 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001692 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1693 return 0;
1694 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001695 }
Mark Shannon88dce262019-12-30 09:53:36 +00001696 /* Emit the finally block, restoring the line number when done */
1697 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001698 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001699 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001700 if (preserve_tos) {
1701 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001702 }
1703 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001704
Mark Shannonfee55262019-11-21 09:11:43 +00001705 case FINALLY_END:
1706 if (preserve_tos) {
1707 ADDOP(c, ROT_FOUR);
1708 }
1709 ADDOP(c, POP_TOP);
1710 ADDOP(c, POP_TOP);
1711 ADDOP(c, POP_TOP);
1712 if (preserve_tos) {
1713 ADDOP(c, ROT_FOUR);
1714 }
1715 ADDOP(c, POP_EXCEPT);
1716 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001717
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001718 case WITH:
1719 case ASYNC_WITH:
1720 ADDOP(c, POP_BLOCK);
1721 if (preserve_tos) {
1722 ADDOP(c, ROT_TWO);
1723 }
Mark Shannonfee55262019-11-21 09:11:43 +00001724 if(!compiler_call_exit_with_nones(c)) {
1725 return 0;
1726 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 if (info->fb_type == ASYNC_WITH) {
1728 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001729 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001730 ADDOP(c, YIELD_FROM);
1731 }
Mark Shannonfee55262019-11-21 09:11:43 +00001732 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 return 1;
1734
1735 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001736 if (info->fb_datum) {
1737 ADDOP(c, POP_BLOCK);
1738 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001739 if (preserve_tos) {
1740 ADDOP(c, ROT_FOUR);
1741 }
Mark Shannonfee55262019-11-21 09:11:43 +00001742 ADDOP(c, POP_EXCEPT);
1743 if (info->fb_datum) {
1744 ADDOP_LOAD_CONST(c, Py_None);
1745 compiler_nameop(c, info->fb_datum, Store);
1746 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001747 }
Mark Shannonfee55262019-11-21 09:11:43 +00001748 return 1;
1749
1750 case POP_VALUE:
1751 if (preserve_tos) {
1752 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001753 }
Mark Shannonfee55262019-11-21 09:11:43 +00001754 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001755 return 1;
1756 }
1757 Py_UNREACHABLE();
1758}
1759
Mark Shannonfee55262019-11-21 09:11:43 +00001760/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1761static int
1762compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1763 if (c->u->u_nfblocks == 0) {
1764 return 1;
1765 }
1766 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1767 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1768 *loop = top;
1769 return 1;
1770 }
1771 struct fblockinfo copy = *top;
1772 c->u->u_nfblocks--;
1773 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1774 return 0;
1775 }
1776 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1777 return 0;
1778 }
1779 c->u->u_fblock[c->u->u_nfblocks] = copy;
1780 c->u->u_nfblocks++;
1781 return 1;
1782}
1783
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001784/* Compile a sequence of statements, checking for a docstring
1785 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786
1787static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001788compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001790 int i = 0;
1791 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001792 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001793
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001794 /* Set current line number to the line number of first statement.
1795 This way line number for SETUP_ANNOTATIONS will always
1796 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301797 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001798 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001799 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001800 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001801 }
1802 /* Every annotated class and module should have __annotations__. */
1803 if (find_ann(stmts)) {
1804 ADDOP(c, SETUP_ANNOTATIONS);
1805 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001806 if (!asdl_seq_LEN(stmts))
1807 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001808 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001809 if (c->c_optimize < 2) {
1810 docstring = _PyAST_GetDocString(stmts);
1811 if (docstring) {
1812 i = 1;
1813 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1814 assert(st->kind == Expr_kind);
1815 VISIT(c, expr, st->v.Expr.value);
1816 if (!compiler_nameop(c, __doc__, Store))
1817 return 0;
1818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001820 for (; i < asdl_seq_LEN(stmts); i++)
1821 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823}
1824
1825static PyCodeObject *
1826compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyCodeObject *co;
1829 int addNone = 1;
1830 static PyObject *module;
1831 if (!module) {
1832 module = PyUnicode_InternFromString("<module>");
1833 if (!module)
1834 return NULL;
1835 }
1836 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001837 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 return NULL;
1839 switch (mod->kind) {
1840 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001841 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 compiler_exit_scope(c);
1843 return 0;
1844 }
1845 break;
1846 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001847 if (find_ann(mod->v.Interactive.body)) {
1848 ADDOP(c, SETUP_ANNOTATIONS);
1849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 c->c_interactive = 1;
1851 VISIT_SEQ_IN_SCOPE(c, stmt,
1852 mod->v.Interactive.body);
1853 break;
1854 case Expression_kind:
1855 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1856 addNone = 0;
1857 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 default:
1859 PyErr_Format(PyExc_SystemError,
1860 "module kind %d should not be possible",
1861 mod->kind);
1862 return 0;
1863 }
1864 co = assemble(c, addNone);
1865 compiler_exit_scope(c);
1866 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001867}
1868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869/* The test for LOCAL must come before the test for FREE in order to
1870 handle classes where name is both local and free. The local var is
1871 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001872*/
1873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874static int
1875get_ref_type(struct compiler *c, PyObject *name)
1876{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001877 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001878 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001879 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001880 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001881 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (scope == 0) {
1883 char buf[350];
1884 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001885 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001887 PyUnicode_AsUTF8(name),
1888 PyUnicode_AsUTF8(c->u->u_name),
1889 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1890 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1891 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1892 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 );
1894 Py_FatalError(buf);
1895 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898}
1899
1900static int
1901compiler_lookup_arg(PyObject *dict, PyObject *name)
1902{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001903 PyObject *v;
1904 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001906 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001907 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908}
1909
1910static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001913 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001914 if (qualname == NULL)
1915 qualname = co->co_name;
1916
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001917 if (free) {
1918 for (i = 0; i < free; ++i) {
1919 /* Bypass com_addop_varname because it will generate
1920 LOAD_DEREF but LOAD_CLOSURE is needed.
1921 */
1922 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1923 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001924
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001925 /* Special case: If a class contains a method with a
1926 free variable that has the same name as a method,
1927 the name will be considered free *and* local in the
1928 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001929 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001930 */
1931 reftype = get_ref_type(c, name);
1932 if (reftype == CELL)
1933 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1934 else /* (reftype == FREE) */
1935 arg = compiler_lookup_arg(c->u->u_freevars, name);
1936 if (arg == -1) {
1937 fprintf(stderr,
1938 "lookup %s in %s %d %d\n"
1939 "freevars of %s: %s\n",
1940 PyUnicode_AsUTF8(PyObject_Repr(name)),
1941 PyUnicode_AsUTF8(c->u->u_name),
1942 reftype, arg,
1943 PyUnicode_AsUTF8(co->co_name),
1944 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1945 Py_FatalError("compiler_make_closure()");
1946 }
1947 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001949 flags |= 0x08;
1950 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001952 ADDOP_LOAD_CONST(c, (PyObject*)co);
1953 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001954 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956}
1957
1958static int
1959compiler_decorators(struct compiler *c, asdl_seq* decos)
1960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (!decos)
1964 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1967 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1968 }
1969 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970}
1971
1972static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001973compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001975{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001976 /* Push a dict of keyword-only default values.
1977
1978 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1979 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 int i;
1981 PyObject *keys = NULL;
1982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1984 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1985 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1986 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001987 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 if (!mangled) {
1989 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 if (keys == NULL) {
1992 keys = PyList_New(1);
1993 if (keys == NULL) {
1994 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001995 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001996 }
1997 PyList_SET_ITEM(keys, 0, mangled);
1998 }
1999 else {
2000 int res = PyList_Append(keys, mangled);
2001 Py_DECREF(mangled);
2002 if (res == -1) {
2003 goto error;
2004 }
2005 }
2006 if (!compiler_visit_expr(c, default_)) {
2007 goto error;
2008 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 }
2010 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 if (keys != NULL) {
2012 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2013 PyObject *keys_tuple = PyList_AsTuple(keys);
2014 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002015 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002016 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002017 assert(default_count > 0);
2018 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002019 }
2020 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002021 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 }
2023
2024error:
2025 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002027}
2028
2029static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002030compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2031{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002032 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002033 return 1;
2034}
2035
2036static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002037compiler_visit_argannotation(struct compiler *c, identifier id,
2038 expr_ty annotation, PyObject *names)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002041 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002042 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2043 VISIT(c, annexpr, annotation)
2044 }
2045 else {
2046 VISIT(c, expr, annotation);
2047 }
Victor Stinner065efc32014-02-18 22:07:56 +01002048 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002049 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002050 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002051 if (PyList_Append(names, mangled) < 0) {
2052 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002053 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002054 }
2055 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002058}
2059
2060static int
2061compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2062 PyObject *names)
2063{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 for (i = 0; i < asdl_seq_LEN(args); i++) {
2066 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 c,
2069 arg->arg,
2070 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 names))
2072 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002075}
2076
2077static int
2078compiler_visit_annotations(struct compiler *c, arguments_ty args,
2079 expr_ty returns)
2080{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002081 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002082 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002083
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002084 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 */
2086 static identifier return_str;
2087 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002088 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 names = PyList_New(0);
2090 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002091 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002092
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002093 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002095 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2096 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002097 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002098 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002099 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002101 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002103 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002104 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002105 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (!return_str) {
2109 return_str = PyUnicode_InternFromString("return");
2110 if (!return_str)
2111 goto error;
2112 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002113 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 goto error;
2115 }
2116
2117 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002119 PyObject *keytuple = PyList_AsTuple(names);
2120 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002121 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002122 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002125 else {
2126 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002127 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002128 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002129
2130error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002132 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002133}
2134
2135static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002136compiler_visit_defaults(struct compiler *c, arguments_ty args)
2137{
2138 VISIT_SEQ(c, expr, args->defaults);
2139 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2140 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141}
2142
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143static Py_ssize_t
2144compiler_default_arguments(struct compiler *c, arguments_ty args)
2145{
2146 Py_ssize_t funcflags = 0;
2147 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002148 if (!compiler_visit_defaults(c, args))
2149 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002150 funcflags |= 0x01;
2151 }
2152 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002153 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002155 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002156 return -1;
2157 }
2158 else if (res > 0) {
2159 funcflags |= 0x02;
2160 }
2161 }
2162 return funcflags;
2163}
2164
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165static int
Yury Selivanov75445082015-05-11 22:57:16 -04002166compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002169 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002170 arguments_ty args;
2171 expr_ty returns;
2172 identifier name;
2173 asdl_seq* decos;
2174 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002175 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002176 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002177 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002178 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179
Yury Selivanov75445082015-05-11 22:57:16 -04002180 if (is_async) {
2181 assert(s->kind == AsyncFunctionDef_kind);
2182
2183 args = s->v.AsyncFunctionDef.args;
2184 returns = s->v.AsyncFunctionDef.returns;
2185 decos = s->v.AsyncFunctionDef.decorator_list;
2186 name = s->v.AsyncFunctionDef.name;
2187 body = s->v.AsyncFunctionDef.body;
2188
2189 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2190 } else {
2191 assert(s->kind == FunctionDef_kind);
2192
2193 args = s->v.FunctionDef.args;
2194 returns = s->v.FunctionDef.returns;
2195 decos = s->v.FunctionDef.decorator_list;
2196 name = s->v.FunctionDef.name;
2197 body = s->v.FunctionDef.body;
2198
2199 scope_type = COMPILER_SCOPE_FUNCTION;
2200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (!compiler_decorators(c, decos))
2203 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002204
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002205 firstlineno = s->lineno;
2206 if (asdl_seq_LEN(decos)) {
2207 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2208 }
2209
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002210 funcflags = compiler_default_arguments(c, args);
2211 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002213 }
2214
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002215 annotations = compiler_visit_annotations(c, args, returns);
2216 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002217 return 0;
2218 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002219 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002220 funcflags |= 0x04;
2221 }
2222
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002223 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002224 return 0;
2225 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226
INADA Naokicb41b272017-02-23 00:31:59 +09002227 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002228 if (c->c_optimize < 2) {
2229 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002230 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002231 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 compiler_exit_scope(c);
2233 return 0;
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002237 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002239 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002241 qualname = c->u->u_qualname;
2242 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002244 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002245 Py_XDECREF(qualname);
2246 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002250 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002251 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 /* decorators */
2255 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2256 ADDOP_I(c, CALL_FUNCTION, 1);
2257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Yury Selivanov75445082015-05-11 22:57:16 -04002259 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260}
2261
2262static int
2263compiler_class(struct compiler *c, stmt_ty s)
2264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyCodeObject *co;
2266 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002267 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (!compiler_decorators(c, decos))
2271 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002272
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002273 firstlineno = s->lineno;
2274 if (asdl_seq_LEN(decos)) {
2275 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2276 }
2277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* ultimately generate code for:
2279 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2280 where:
2281 <func> is a function/closure created from the class body;
2282 it has a single argument (__locals__) where the dict
2283 (or MutableSequence) representing the locals is passed
2284 <name> is the class name
2285 <bases> is the positional arguments and *varargs argument
2286 <keywords> is the keyword arguments and **kwds argument
2287 This borrows from compiler_call.
2288 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002291 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002292 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 return 0;
2294 /* this block represents what we do in the new scope */
2295 {
2296 /* use the class name for name mangling */
2297 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002298 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 /* load (global) __name__ ... */
2300 str = PyUnicode_InternFromString("__name__");
2301 if (!str || !compiler_nameop(c, str, Load)) {
2302 Py_XDECREF(str);
2303 compiler_exit_scope(c);
2304 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 Py_DECREF(str);
2307 /* ... and store it as __module__ */
2308 str = PyUnicode_InternFromString("__module__");
2309 if (!str || !compiler_nameop(c, str, Store)) {
2310 Py_XDECREF(str);
2311 compiler_exit_scope(c);
2312 return 0;
2313 }
2314 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002315 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002316 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002317 str = PyUnicode_InternFromString("__qualname__");
2318 if (!str || !compiler_nameop(c, str, Store)) {
2319 Py_XDECREF(str);
2320 compiler_exit_scope(c);
2321 return 0;
2322 }
2323 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002325 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 compiler_exit_scope(c);
2327 return 0;
2328 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002329 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002330 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002331 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002332 str = PyUnicode_InternFromString("__class__");
2333 if (str == NULL) {
2334 compiler_exit_scope(c);
2335 return 0;
2336 }
2337 i = compiler_lookup_arg(c->u->u_cellvars, str);
2338 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002339 if (i < 0) {
2340 compiler_exit_scope(c);
2341 return 0;
2342 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002343 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002346 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002347 str = PyUnicode_InternFromString("__classcell__");
2348 if (!str || !compiler_nameop(c, str, Store)) {
2349 Py_XDECREF(str);
2350 compiler_exit_scope(c);
2351 return 0;
2352 }
2353 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002355 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002357 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002358 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002359 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002360 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 /* create the code object */
2362 co = assemble(c, 1);
2363 }
2364 /* leave the new scope */
2365 compiler_exit_scope(c);
2366 if (co == NULL)
2367 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* 2. load the 'build_class' function */
2370 ADDOP(c, LOAD_BUILD_CLASS);
2371
2372 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002373 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_DECREF(co);
2375
2376 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002377 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378
2379 /* 5. generate the rest of the code for the call */
2380 if (!compiler_call_helper(c, 2,
2381 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002382 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return 0;
2384
2385 /* 6. apply decorators */
2386 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2387 ADDOP_I(c, CALL_FUNCTION, 1);
2388 }
2389
2390 /* 7. store into <name> */
2391 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2392 return 0;
2393 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394}
2395
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002396/* Return 0 if the expression is a constant value except named singletons.
2397 Return 1 otherwise. */
2398static int
2399check_is_arg(expr_ty e)
2400{
2401 if (e->kind != Constant_kind) {
2402 return 1;
2403 }
2404 PyObject *value = e->v.Constant.value;
2405 return (value == Py_None
2406 || value == Py_False
2407 || value == Py_True
2408 || value == Py_Ellipsis);
2409}
2410
2411/* Check operands of identity chacks ("is" and "is not").
2412 Emit a warning if any operand is a constant except named singletons.
2413 Return 0 on error.
2414 */
2415static int
2416check_compare(struct compiler *c, expr_ty e)
2417{
2418 Py_ssize_t i, n;
2419 int left = check_is_arg(e->v.Compare.left);
2420 n = asdl_seq_LEN(e->v.Compare.ops);
2421 for (i = 0; i < n; i++) {
2422 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2423 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2424 if (op == Is || op == IsNot) {
2425 if (!right || !left) {
2426 const char *msg = (op == Is)
2427 ? "\"is\" with a literal. Did you mean \"==\"?"
2428 : "\"is not\" with a literal. Did you mean \"!=\"?";
2429 return compiler_warn(c, msg);
2430 }
2431 }
2432 left = right;
2433 }
2434 return 1;
2435}
2436
Mark Shannon9af0e472020-01-14 10:12:45 +00002437static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002438{
Mark Shannon9af0e472020-01-14 10:12:45 +00002439 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002440 switch (op) {
2441 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002442 cmp = Py_EQ;
2443 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002444 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002445 cmp = Py_NE;
2446 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002447 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002448 cmp = Py_LT;
2449 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002450 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002451 cmp = Py_LE;
2452 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002453 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002454 cmp = Py_GT;
2455 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002456 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002457 cmp = Py_GE;
2458 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002459 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002460 ADDOP_I(c, IS_OP, 0);
2461 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002462 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002463 ADDOP_I(c, IS_OP, 1);
2464 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002465 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002466 ADDOP_I(c, CONTAINS_OP, 0);
2467 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002468 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002469 ADDOP_I(c, CONTAINS_OP, 1);
2470 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002471 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002472 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 ADDOP_I(c, COMPARE_OP, cmp);
2475 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476}
2477
Mark Shannon9af0e472020-01-14 10:12:45 +00002478
2479
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002480static int
2481compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2482{
2483 switch (e->kind) {
2484 case UnaryOp_kind:
2485 if (e->v.UnaryOp.op == Not)
2486 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2487 /* fallback to general implementation */
2488 break;
2489 case BoolOp_kind: {
2490 asdl_seq *s = e->v.BoolOp.values;
2491 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2492 assert(n >= 0);
2493 int cond2 = e->v.BoolOp.op == Or;
2494 basicblock *next2 = next;
2495 if (!cond2 != !cond) {
2496 next2 = compiler_new_block(c);
2497 if (next2 == NULL)
2498 return 0;
2499 }
2500 for (i = 0; i < n; ++i) {
2501 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2502 return 0;
2503 }
2504 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2505 return 0;
2506 if (next2 != next)
2507 compiler_use_next_block(c, next2);
2508 return 1;
2509 }
2510 case IfExp_kind: {
2511 basicblock *end, *next2;
2512 end = compiler_new_block(c);
2513 if (end == NULL)
2514 return 0;
2515 next2 = compiler_new_block(c);
2516 if (next2 == NULL)
2517 return 0;
2518 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2519 return 0;
2520 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2521 return 0;
2522 ADDOP_JREL(c, JUMP_FORWARD, end);
2523 compiler_use_next_block(c, next2);
2524 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2525 return 0;
2526 compiler_use_next_block(c, end);
2527 return 1;
2528 }
2529 case Compare_kind: {
2530 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2531 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002532 if (!check_compare(c, e)) {
2533 return 0;
2534 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002535 basicblock *cleanup = compiler_new_block(c);
2536 if (cleanup == NULL)
2537 return 0;
2538 VISIT(c, expr, e->v.Compare.left);
2539 for (i = 0; i < n; i++) {
2540 VISIT(c, expr,
2541 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2542 ADDOP(c, DUP_TOP);
2543 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002544 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002545 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2546 NEXT_BLOCK(c);
2547 }
2548 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002549 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002550 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2551 basicblock *end = compiler_new_block(c);
2552 if (end == NULL)
2553 return 0;
2554 ADDOP_JREL(c, JUMP_FORWARD, end);
2555 compiler_use_next_block(c, cleanup);
2556 ADDOP(c, POP_TOP);
2557 if (!cond) {
2558 ADDOP_JREL(c, JUMP_FORWARD, next);
2559 }
2560 compiler_use_next_block(c, end);
2561 return 1;
2562 }
2563 /* fallback to general implementation */
2564 break;
2565 }
2566 default:
2567 /* fallback to general implementation */
2568 break;
2569 }
2570
2571 /* general implementation */
2572 VISIT(c, expr, e);
2573 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2574 return 1;
2575}
2576
2577static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002578compiler_ifexp(struct compiler *c, expr_ty e)
2579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 basicblock *end, *next;
2581
2582 assert(e->kind == IfExp_kind);
2583 end = compiler_new_block(c);
2584 if (end == NULL)
2585 return 0;
2586 next = compiler_new_block(c);
2587 if (next == NULL)
2588 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002589 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2590 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 VISIT(c, expr, e->v.IfExp.body);
2592 ADDOP_JREL(c, JUMP_FORWARD, end);
2593 compiler_use_next_block(c, next);
2594 VISIT(c, expr, e->v.IfExp.orelse);
2595 compiler_use_next_block(c, end);
2596 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002597}
2598
2599static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600compiler_lambda(struct compiler *c, expr_ty e)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002603 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002605 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 arguments_ty args = e->v.Lambda.args;
2607 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 if (!name) {
2610 name = PyUnicode_InternFromString("<lambda>");
2611 if (!name)
2612 return 0;
2613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002615 funcflags = compiler_default_arguments(c, args);
2616 if (funcflags == -1) {
2617 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002619
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002620 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002621 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 /* Make None the first constant, so the lambda can't have a
2625 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002626 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002630 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2632 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2633 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002634 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 }
2636 else {
2637 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002638 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002640 qualname = c->u->u_qualname;
2641 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002643 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002646 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002647 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 Py_DECREF(co);
2649
2650 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651}
2652
2653static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654compiler_if(struct compiler *c, stmt_ty s)
2655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 basicblock *end, *next;
2657 int constant;
2658 assert(s->kind == If_kind);
2659 end = compiler_new_block(c);
2660 if (end == NULL)
2661 return 0;
2662
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002663 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002664 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 * constant = 1: "if 1", "if 2", ...
2666 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002667 if (constant == 0) {
2668 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002670 END_DO_NOT_EMIT_BYTECODE
2671 if (s->v.If.orelse) {
2672 VISIT_SEQ(c, stmt, s->v.If.orelse);
2673 }
2674 } else if (constant == 1) {
2675 VISIT_SEQ(c, stmt, s->v.If.body);
2676 if (s->v.If.orelse) {
2677 BEGIN_DO_NOT_EMIT_BYTECODE
2678 VISIT_SEQ(c, stmt, s->v.If.orelse);
2679 END_DO_NOT_EMIT_BYTECODE
2680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002682 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 next = compiler_new_block(c);
2684 if (next == NULL)
2685 return 0;
2686 }
Mark Shannonfee55262019-11-21 09:11:43 +00002687 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002689 }
2690 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002691 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002694 if (asdl_seq_LEN(s->v.If.orelse)) {
2695 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 compiler_use_next_block(c, next);
2697 VISIT_SEQ(c, stmt, s->v.If.orelse);
2698 }
2699 }
2700 compiler_use_next_block(c, end);
2701 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702}
2703
2704static int
2705compiler_for(struct compiler *c, stmt_ty s)
2706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 start = compiler_new_block(c);
2710 cleanup = compiler_new_block(c);
2711 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002712 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002714 }
2715 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002717 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 VISIT(c, expr, s->v.For.iter);
2719 ADDOP(c, GET_ITER);
2720 compiler_use_next_block(c, start);
2721 ADDOP_JREL(c, FOR_ITER, cleanup);
2722 VISIT(c, expr, s->v.For.target);
2723 VISIT_SEQ(c, stmt, s->v.For.body);
2724 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2725 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002726
2727 compiler_pop_fblock(c, FOR_LOOP, start);
2728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 VISIT_SEQ(c, stmt, s->v.For.orelse);
2730 compiler_use_next_block(c, end);
2731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732}
2733
Yury Selivanov75445082015-05-11 22:57:16 -04002734
2735static int
2736compiler_async_for(struct compiler *c, stmt_ty s)
2737{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002738 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002739 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002740 c->u->u_ste->ste_coroutine = 1;
2741 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002742 return compiler_error(c, "'async for' outside async function");
2743 }
2744
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002745 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002746 except = compiler_new_block(c);
2747 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002748
Mark Shannonfee55262019-11-21 09:11:43 +00002749 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002750 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002751 }
Yury Selivanov75445082015-05-11 22:57:16 -04002752 VISIT(c, expr, s->v.AsyncFor.iter);
2753 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002754
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002755 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002756 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002757 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002758 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002759 /* SETUP_FINALLY to guard the __anext__ call */
2760 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002761 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002762 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002763 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002764 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002765
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 /* Success block for __anext__ */
2767 VISIT(c, expr, s->v.AsyncFor.target);
2768 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2769 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2770
2771 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002772
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002773 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002774 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002775 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002776
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002777 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002778 VISIT_SEQ(c, stmt, s->v.For.orelse);
2779
2780 compiler_use_next_block(c, end);
2781
2782 return 1;
2783}
2784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785static int
2786compiler_while(struct compiler *c, stmt_ty s)
2787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002789 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002792 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002793 // Push a dummy block so the VISIT_SEQ knows that we are
2794 // inside a while loop so it can correctly evaluate syntax
2795 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002796 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002797 return 0;
2798 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002799 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002800 // Remove the dummy block now that is not needed.
2801 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002802 END_DO_NOT_EMIT_BYTECODE
2803 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002805 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 return 1;
2807 }
2808 loop = compiler_new_block(c);
2809 end = compiler_new_block(c);
2810 if (constant == -1) {
2811 anchor = compiler_new_block(c);
2812 if (anchor == NULL)
2813 return 0;
2814 }
2815 if (loop == NULL || end == NULL)
2816 return 0;
2817 if (s->v.While.orelse) {
2818 orelse = compiler_new_block(c);
2819 if (orelse == NULL)
2820 return 0;
2821 }
2822 else
2823 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002826 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 return 0;
2828 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002829 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2830 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 }
2832 VISIT_SEQ(c, stmt, s->v.While.body);
2833 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* XXX should the two POP instructions be in a separate block
2836 if there is no else clause ?
2837 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002839 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002841 compiler_pop_fblock(c, WHILE_LOOP, loop);
2842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 if (orelse != NULL) /* what if orelse is just pass? */
2844 VISIT_SEQ(c, stmt, s->v.While.orelse);
2845 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848}
2849
2850static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002851compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002853 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002854 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855 if (c->u->u_ste->ste_type != FunctionBlock)
2856 return compiler_error(c, "'return' outside function");
2857 if (s->v.Return.value != NULL &&
2858 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2859 {
2860 return compiler_error(
2861 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002863 if (preserve_tos) {
2864 VISIT(c, expr, s->v.Return.value);
2865 }
Mark Shannonfee55262019-11-21 09:11:43 +00002866 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2867 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002868 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002869 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002870 }
2871 else if (!preserve_tos) {
2872 VISIT(c, expr, s->v.Return.value);
2873 }
2874 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877}
2878
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879static int
2880compiler_break(struct compiler *c)
2881{
Mark Shannonfee55262019-11-21 09:11:43 +00002882 struct fblockinfo *loop = NULL;
2883 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2884 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 }
Mark Shannonfee55262019-11-21 09:11:43 +00002886 if (loop == NULL) {
2887 return compiler_error(c, "'break' outside loop");
2888 }
2889 if (!compiler_unwind_fblock(c, loop, 0)) {
2890 return 0;
2891 }
2892 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2893 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002894}
2895
2896static int
2897compiler_continue(struct compiler *c)
2898{
Mark Shannonfee55262019-11-21 09:11:43 +00002899 struct fblockinfo *loop = NULL;
2900 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2901 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902 }
Mark Shannonfee55262019-11-21 09:11:43 +00002903 if (loop == NULL) {
2904 return compiler_error(c, "'continue' not properly in loop");
2905 }
2906 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2907 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002908}
2909
2910
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912
2913 SETUP_FINALLY L
2914 <code for body>
2915 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002916 <code for finalbody>
2917 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002918 L:
2919 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002920 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 The special instructions use the block stack. Each block
2923 stack entry contains the instruction that created it (here
2924 SETUP_FINALLY), the level of the value stack at the time the
2925 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 Pushes the current value stack level and the label
2929 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002931 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002934 when a SETUP_FINALLY entry is found, the raised and the caught
2935 exceptions are pushed onto the value stack (and the exception
2936 condition is cleared), and the interpreter jumps to the label
2937 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938*/
2939
2940static int
2941compiler_try_finally(struct compiler *c, stmt_ty s)
2942{
Mark Shannonfee55262019-11-21 09:11:43 +00002943 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 body = compiler_new_block(c);
2946 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002947 exit = compiler_new_block(c);
2948 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002951 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 ADDOP_JREL(c, SETUP_FINALLY, end);
2953 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002954 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002956 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2957 if (!compiler_try_except(c, s))
2958 return 0;
2959 }
2960 else {
2961 VISIT_SEQ(c, stmt, s->v.Try.body);
2962 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002964 compiler_pop_fblock(c, FINALLY_TRY, body);
2965 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2966 ADDOP_JREL(c, JUMP_FORWARD, exit);
2967 /* `finally` block */
2968 compiler_use_next_block(c, end);
2969 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2970 return 0;
2971 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2972 compiler_pop_fblock(c, FINALLY_END, end);
2973 ADDOP(c, RERAISE);
2974 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976}
2977
2978/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002979 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 (The contents of the value stack is shown in [], with the top
2981 at the right; 'tb' is trace-back info, 'val' the exception's
2982 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983
2984 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002985 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 [] <code for S>
2987 [] POP_BLOCK
2988 [] JUMP_FORWARD L0
2989
2990 [tb, val, exc] L1: DUP )
2991 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00002992 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 [tb, val, exc] POP
2994 [tb, val] <assign to V1> (or POP if no V1)
2995 [tb] POP
2996 [] <code for S1>
2997 JUMP_FORWARD L0
2998
2999 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000 .............................etc.......................
3001
Mark Shannonfee55262019-11-21 09:11:43 +00003002 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003
3004 [] L0: <next statement>
3005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006 Of course, parts are not generated if Vi or Ei is not present.
3007*/
3008static int
3009compiler_try_except(struct compiler *c, stmt_ty s)
3010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003012 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 body = compiler_new_block(c);
3015 except = compiler_new_block(c);
3016 orelse = compiler_new_block(c);
3017 end = compiler_new_block(c);
3018 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3019 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003020 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003022 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003024 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 ADDOP(c, POP_BLOCK);
3026 compiler_pop_fblock(c, EXCEPT, body);
3027 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003028 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 compiler_use_next_block(c, except);
3030 for (i = 0; i < n; i++) {
3031 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003032 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 if (!handler->v.ExceptHandler.type && i < n-1)
3034 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003035 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 except = compiler_new_block(c);
3037 if (except == NULL)
3038 return 0;
3039 if (handler->v.ExceptHandler.type) {
3040 ADDOP(c, DUP_TOP);
3041 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003042 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 }
3044 ADDOP(c, POP_TOP);
3045 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003046 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003047
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003048 cleanup_end = compiler_new_block(c);
3049 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003050 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003051 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003052 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003053
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003054 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3055 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003057 /*
3058 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003059 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003060 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003061 try:
3062 # body
3063 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003064 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003065 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003066 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003068 /* second try: */
3069 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3070 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003071 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 /* second # body */
3075 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003076 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003077 ADDOP(c, POP_BLOCK);
3078 ADDOP(c, POP_EXCEPT);
3079 /* name = None; del name */
3080 ADDOP_LOAD_CONST(c, Py_None);
3081 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3082 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3083 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084
Mark Shannonfee55262019-11-21 09:11:43 +00003085 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003088 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003089 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003090 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092
Mark Shannonfee55262019-11-21 09:11:43 +00003093 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 }
3095 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003096 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003098 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003099 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003100 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101
Guido van Rossumb940e112007-01-10 16:19:56 +00003102 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 ADDOP(c, POP_TOP);
3104 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003105 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003106 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003108 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003109 ADDOP(c, POP_EXCEPT);
3110 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 compiler_use_next_block(c, except);
3113 }
Mark Shannonfee55262019-11-21 09:11:43 +00003114 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003116 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 compiler_use_next_block(c, end);
3118 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119}
3120
3121static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003122compiler_try(struct compiler *c, stmt_ty s) {
3123 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3124 return compiler_try_finally(c, s);
3125 else
3126 return compiler_try_except(c, s);
3127}
3128
3129
3130static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131compiler_import_as(struct compiler *c, identifier name, identifier asname)
3132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* The IMPORT_NAME opcode was already generated. This function
3134 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003137 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003139 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3140 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003141 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003142 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003143 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003145 while (1) {
3146 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003148 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003149 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003150 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003151 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003153 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003154 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003155 if (dot == -1) {
3156 break;
3157 }
3158 ADDOP(c, ROT_TWO);
3159 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003161 if (!compiler_nameop(c, asname, Store)) {
3162 return 0;
3163 }
3164 ADDOP(c, POP_TOP);
3165 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 }
3167 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168}
3169
3170static int
3171compiler_import(struct compiler *c, stmt_ty s)
3172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* The Import node stores a module name like a.b.c as a single
3174 string. This is convenient for all cases except
3175 import a.b.c as d
3176 where we need to parse that string to extract the individual
3177 module names.
3178 XXX Perhaps change the representation to make this case simpler?
3179 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003180 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 for (i = 0; i < n; i++) {
3183 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3184 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003186 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3187 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 if (alias->asname) {
3191 r = compiler_import_as(c, alias->name, alias->asname);
3192 if (!r)
3193 return r;
3194 }
3195 else {
3196 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003197 Py_ssize_t dot = PyUnicode_FindChar(
3198 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003199 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003200 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003201 if (tmp == NULL)
3202 return 0;
3203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003205 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 Py_DECREF(tmp);
3207 }
3208 if (!r)
3209 return r;
3210 }
3211 }
3212 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213}
3214
3215static int
3216compiler_from_import(struct compiler *c, stmt_ty s)
3217{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003218 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003219 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 if (!empty_string) {
3223 empty_string = PyUnicode_FromString("");
3224 if (!empty_string)
3225 return 0;
3226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003228 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003229
3230 names = PyTuple_New(n);
3231 if (!names)
3232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 /* build up the names */
3235 for (i = 0; i < n; i++) {
3236 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3237 Py_INCREF(alias->name);
3238 PyTuple_SET_ITEM(names, i, alias->name);
3239 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003242 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 Py_DECREF(names);
3244 return compiler_error(c, "from __future__ imports must occur "
3245 "at the beginning of the file");
3246 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003247 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 if (s->v.ImportFrom.module) {
3250 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3251 }
3252 else {
3253 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3254 }
3255 for (i = 0; i < n; i++) {
3256 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3257 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003259 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 assert(n == 1);
3261 ADDOP(c, IMPORT_STAR);
3262 return 1;
3263 }
3264
3265 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3266 store_name = alias->name;
3267 if (alias->asname)
3268 store_name = alias->asname;
3269
3270 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 return 0;
3272 }
3273 }
3274 /* remove imported module */
3275 ADDOP(c, POP_TOP);
3276 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277}
3278
3279static int
3280compiler_assert(struct compiler *c, stmt_ty s)
3281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
Georg Brandl8334fd92010-12-04 10:26:46 +00003284 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003287 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3288 {
3289 if (!compiler_warn(c, "assertion is always true, "
3290 "perhaps remove parentheses?"))
3291 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003292 return 0;
3293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 end = compiler_new_block(c);
3296 if (end == NULL)
3297 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003298 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3299 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003300 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 if (s->v.Assert.msg) {
3302 VISIT(c, expr, s->v.Assert.msg);
3303 ADDOP_I(c, CALL_FUNCTION, 1);
3304 }
3305 ADDOP_I(c, RAISE_VARARGS, 1);
3306 compiler_use_next_block(c, end);
3307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308}
3309
3310static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003311compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3312{
3313 if (c->c_interactive && c->c_nestlevel <= 1) {
3314 VISIT(c, expr, value);
3315 ADDOP(c, PRINT_EXPR);
3316 return 1;
3317 }
3318
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003319 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003320 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003321 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003322 }
3323
3324 VISIT(c, expr, value);
3325 ADDOP(c, POP_TOP);
3326 return 1;
3327}
3328
3329static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330compiler_visit_stmt(struct compiler *c, stmt_ty s)
3331{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003332 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003335 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 switch (s->kind) {
3338 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003339 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 case ClassDef_kind:
3341 return compiler_class(c, s);
3342 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003343 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 case Delete_kind:
3345 VISIT_SEQ(c, expr, s->v.Delete.targets)
3346 break;
3347 case Assign_kind:
3348 n = asdl_seq_LEN(s->v.Assign.targets);
3349 VISIT(c, expr, s->v.Assign.value);
3350 for (i = 0; i < n; i++) {
3351 if (i < n - 1)
3352 ADDOP(c, DUP_TOP);
3353 VISIT(c, expr,
3354 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3355 }
3356 break;
3357 case AugAssign_kind:
3358 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003359 case AnnAssign_kind:
3360 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 case For_kind:
3362 return compiler_for(c, s);
3363 case While_kind:
3364 return compiler_while(c, s);
3365 case If_kind:
3366 return compiler_if(c, s);
3367 case Raise_kind:
3368 n = 0;
3369 if (s->v.Raise.exc) {
3370 VISIT(c, expr, s->v.Raise.exc);
3371 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003372 if (s->v.Raise.cause) {
3373 VISIT(c, expr, s->v.Raise.cause);
3374 n++;
3375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003377 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003379 case Try_kind:
3380 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 case Assert_kind:
3382 return compiler_assert(c, s);
3383 case Import_kind:
3384 return compiler_import(c, s);
3385 case ImportFrom_kind:
3386 return compiler_from_import(c, s);
3387 case Global_kind:
3388 case Nonlocal_kind:
3389 break;
3390 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003391 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Pass_kind:
3393 break;
3394 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003395 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 case Continue_kind:
3397 return compiler_continue(c);
3398 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003399 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003400 case AsyncFunctionDef_kind:
3401 return compiler_function(c, s, 1);
3402 case AsyncWith_kind:
3403 return compiler_async_with(c, s, 0);
3404 case AsyncFor_kind:
3405 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 }
Yury Selivanov75445082015-05-11 22:57:16 -04003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003409}
3410
3411static int
3412unaryop(unaryop_ty op)
3413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 switch (op) {
3415 case Invert:
3416 return UNARY_INVERT;
3417 case Not:
3418 return UNARY_NOT;
3419 case UAdd:
3420 return UNARY_POSITIVE;
3421 case USub:
3422 return UNARY_NEGATIVE;
3423 default:
3424 PyErr_Format(PyExc_SystemError,
3425 "unary op %d should not be possible", op);
3426 return 0;
3427 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428}
3429
3430static int
Andy Lester76d58772020-03-10 21:18:12 -05003431binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 switch (op) {
3434 case Add:
3435 return BINARY_ADD;
3436 case Sub:
3437 return BINARY_SUBTRACT;
3438 case Mult:
3439 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003440 case MatMult:
3441 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 case Div:
3443 return BINARY_TRUE_DIVIDE;
3444 case Mod:
3445 return BINARY_MODULO;
3446 case Pow:
3447 return BINARY_POWER;
3448 case LShift:
3449 return BINARY_LSHIFT;
3450 case RShift:
3451 return BINARY_RSHIFT;
3452 case BitOr:
3453 return BINARY_OR;
3454 case BitXor:
3455 return BINARY_XOR;
3456 case BitAnd:
3457 return BINARY_AND;
3458 case FloorDiv:
3459 return BINARY_FLOOR_DIVIDE;
3460 default:
3461 PyErr_Format(PyExc_SystemError,
3462 "binary op %d should not be possible", op);
3463 return 0;
3464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465}
3466
3467static int
Andy Lester76d58772020-03-10 21:18:12 -05003468inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 switch (op) {
3471 case Add:
3472 return INPLACE_ADD;
3473 case Sub:
3474 return INPLACE_SUBTRACT;
3475 case Mult:
3476 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003477 case MatMult:
3478 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 case Div:
3480 return INPLACE_TRUE_DIVIDE;
3481 case Mod:
3482 return INPLACE_MODULO;
3483 case Pow:
3484 return INPLACE_POWER;
3485 case LShift:
3486 return INPLACE_LSHIFT;
3487 case RShift:
3488 return INPLACE_RSHIFT;
3489 case BitOr:
3490 return INPLACE_OR;
3491 case BitXor:
3492 return INPLACE_XOR;
3493 case BitAnd:
3494 return INPLACE_AND;
3495 case FloorDiv:
3496 return INPLACE_FLOOR_DIVIDE;
3497 default:
3498 PyErr_Format(PyExc_SystemError,
3499 "inplace binary op %d should not be possible", op);
3500 return 0;
3501 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502}
3503
3504static int
3505compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3506{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003507 int op, scope;
3508 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 PyObject *dict = c->u->u_names;
3512 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003514 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3515 !_PyUnicode_EqualToASCIIString(name, "True") &&
3516 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003517
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003518 mangled = _Py_Mangle(c->u->u_private, name);
3519 if (!mangled)
3520 return 0;
3521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 op = 0;
3523 optype = OP_NAME;
3524 scope = PyST_GetScope(c->u->u_ste, mangled);
3525 switch (scope) {
3526 case FREE:
3527 dict = c->u->u_freevars;
3528 optype = OP_DEREF;
3529 break;
3530 case CELL:
3531 dict = c->u->u_cellvars;
3532 optype = OP_DEREF;
3533 break;
3534 case LOCAL:
3535 if (c->u->u_ste->ste_type == FunctionBlock)
3536 optype = OP_FAST;
3537 break;
3538 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003539 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 optype = OP_GLOBAL;
3541 break;
3542 case GLOBAL_EXPLICIT:
3543 optype = OP_GLOBAL;
3544 break;
3545 default:
3546 /* scope can be 0 */
3547 break;
3548 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003551 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 switch (optype) {
3554 case OP_DEREF:
3555 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003556 case Load:
3557 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3558 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003559 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003560 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 }
3562 break;
3563 case OP_FAST:
3564 switch (ctx) {
3565 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003566 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003569 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 return 1;
3571 case OP_GLOBAL:
3572 switch (ctx) {
3573 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003574 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 }
3577 break;
3578 case OP_NAME:
3579 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003580 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003581 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 }
3584 break;
3585 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003588 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 Py_DECREF(mangled);
3590 if (arg < 0)
3591 return 0;
3592 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593}
3594
3595static int
3596compiler_boolop(struct compiler *c, expr_ty e)
3597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003599 int jumpi;
3600 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 assert(e->kind == BoolOp_kind);
3604 if (e->v.BoolOp.op == And)
3605 jumpi = JUMP_IF_FALSE_OR_POP;
3606 else
3607 jumpi = JUMP_IF_TRUE_OR_POP;
3608 end = compiler_new_block(c);
3609 if (end == NULL)
3610 return 0;
3611 s = e->v.BoolOp.values;
3612 n = asdl_seq_LEN(s) - 1;
3613 assert(n >= 0);
3614 for (i = 0; i < n; ++i) {
3615 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3616 ADDOP_JABS(c, jumpi, end);
3617 }
3618 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3619 compiler_use_next_block(c, end);
3620 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621}
3622
3623static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003624starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3625 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003626{
3627 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003628 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003629 if (n > 2 && are_all_items_const(elts, 0, n)) {
3630 PyObject *folded = PyTuple_New(n);
3631 if (folded == NULL) {
3632 return 0;
3633 }
3634 PyObject *val;
3635 for (i = 0; i < n; i++) {
3636 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3637 Py_INCREF(val);
3638 PyTuple_SET_ITEM(folded, i, val);
3639 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003640 if (tuple) {
3641 ADDOP_LOAD_CONST_NEW(c, folded);
3642 } else {
3643 if (add == SET_ADD) {
3644 Py_SETREF(folded, PyFrozenSet_New(folded));
3645 if (folded == NULL) {
3646 return 0;
3647 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003648 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003649 ADDOP_I(c, build, pushed);
3650 ADDOP_LOAD_CONST_NEW(c, folded);
3651 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003652 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003653 return 1;
3654 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003655
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003656 for (i = 0; i < n; i++) {
3657 expr_ty elt = asdl_seq_GET(elts, i);
3658 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003659 seen_star = 1;
3660 }
3661 }
3662 if (seen_star) {
3663 seen_star = 0;
3664 for (i = 0; i < n; i++) {
3665 expr_ty elt = asdl_seq_GET(elts, i);
3666 if (elt->kind == Starred_kind) {
3667 if (seen_star == 0) {
3668 ADDOP_I(c, build, i+pushed);
3669 seen_star = 1;
3670 }
3671 VISIT(c, expr, elt->v.Starred.value);
3672 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003673 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003674 else {
3675 VISIT(c, expr, elt);
3676 if (seen_star) {
3677 ADDOP_I(c, add, 1);
3678 }
3679 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003680 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003681 assert(seen_star);
3682 if (tuple) {
3683 ADDOP(c, LIST_TO_TUPLE);
3684 }
3685 }
3686 else {
3687 for (i = 0; i < n; i++) {
3688 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003689 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003690 }
3691 if (tuple) {
3692 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3693 } else {
3694 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003695 }
3696 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003697 return 1;
3698}
3699
3700static int
3701assignment_helper(struct compiler *c, asdl_seq *elts)
3702{
3703 Py_ssize_t n = asdl_seq_LEN(elts);
3704 Py_ssize_t i;
3705 int seen_star = 0;
3706 for (i = 0; i < n; i++) {
3707 expr_ty elt = asdl_seq_GET(elts, i);
3708 if (elt->kind == Starred_kind && !seen_star) {
3709 if ((i >= (1 << 8)) ||
3710 (n-i-1 >= (INT_MAX >> 8)))
3711 return compiler_error(c,
3712 "too many expressions in "
3713 "star-unpacking assignment");
3714 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3715 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003716 }
3717 else if (elt->kind == Starred_kind) {
3718 return compiler_error(c,
3719 "two starred expressions in assignment");
3720 }
3721 }
3722 if (!seen_star) {
3723 ADDOP_I(c, UNPACK_SEQUENCE, n);
3724 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003725 for (i = 0; i < n; i++) {
3726 expr_ty elt = asdl_seq_GET(elts, i);
3727 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3728 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 return 1;
3730}
3731
3732static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733compiler_list(struct compiler *c, expr_ty e)
3734{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003736 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003740 return starunpack_helper(c, elts, 0, BUILD_LIST,
3741 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 else
3744 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746}
3747
3748static int
3749compiler_tuple(struct compiler *c, expr_ty e)
3750{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003751 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003752 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 return assignment_helper(c, elts);
3754 }
3755 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003756 return starunpack_helper(c, elts, 0, BUILD_LIST,
3757 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 }
3759 else
3760 VISIT_SEQ(c, expr, elts);
3761 return 1;
3762}
3763
3764static int
3765compiler_set(struct compiler *c, expr_ty e)
3766{
Mark Shannon13bc1392020-01-23 09:25:17 +00003767 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3768 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769}
3770
3771static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003772are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3773{
3774 Py_ssize_t i;
3775 for (i = begin; i < end; i++) {
3776 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003777 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003778 return 0;
3779 }
3780 return 1;
3781}
3782
3783static int
3784compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3785{
3786 Py_ssize_t i, n = end - begin;
3787 PyObject *keys, *key;
3788 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3789 for (i = begin; i < end; i++) {
3790 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3791 }
3792 keys = PyTuple_New(n);
3793 if (keys == NULL) {
3794 return 0;
3795 }
3796 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003797 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003798 Py_INCREF(key);
3799 PyTuple_SET_ITEM(keys, i - begin, key);
3800 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003801 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003802 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3803 }
3804 else {
3805 for (i = begin; i < end; i++) {
3806 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3807 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3808 }
3809 ADDOP_I(c, BUILD_MAP, n);
3810 }
3811 return 1;
3812}
3813
3814static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003815compiler_dict(struct compiler *c, expr_ty e)
3816{
Victor Stinner976bb402016-03-23 11:36:19 +01003817 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003818 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003819 int is_unpacking = 0;
3820 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003821 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003822 elements = 0;
3823 for (i = 0; i < n; i++) {
3824 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003825 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003826 if (elements) {
3827 if (!compiler_subdict(c, e, i - elements, i)) {
3828 return 0;
3829 }
3830 if (have_dict) {
3831 ADDOP_I(c, DICT_UPDATE, 1);
3832 }
3833 have_dict = 1;
3834 elements = 0;
3835 }
3836 if (have_dict == 0) {
3837 ADDOP_I(c, BUILD_MAP, 0);
3838 have_dict = 1;
3839 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003840 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003841 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003842 }
3843 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003844 if (elements == 0xFFFF) {
3845 if (!compiler_subdict(c, e, i - elements, i)) {
3846 return 0;
3847 }
3848 if (have_dict) {
3849 ADDOP_I(c, DICT_UPDATE, 1);
3850 }
3851 have_dict = 1;
3852 elements = 0;
3853 }
3854 else {
3855 elements++;
3856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 }
3858 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003859 if (elements) {
3860 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003861 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003862 }
3863 if (have_dict) {
3864 ADDOP_I(c, DICT_UPDATE, 1);
3865 }
3866 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003867 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003868 if (!have_dict) {
3869 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 }
3871 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872}
3873
3874static int
3875compiler_compare(struct compiler *c, expr_ty e)
3876{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003877 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003879 if (!check_compare(c, e)) {
3880 return 0;
3881 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003883 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3884 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3885 if (n == 0) {
3886 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003887 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003888 }
3889 else {
3890 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 if (cleanup == NULL)
3892 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003893 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 VISIT(c, expr,
3895 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003896 ADDOP(c, DUP_TOP);
3897 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003898 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003899 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3900 NEXT_BLOCK(c);
3901 }
3902 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003903 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 basicblock *end = compiler_new_block(c);
3905 if (end == NULL)
3906 return 0;
3907 ADDOP_JREL(c, JUMP_FORWARD, end);
3908 compiler_use_next_block(c, cleanup);
3909 ADDOP(c, ROT_TWO);
3910 ADDOP(c, POP_TOP);
3911 compiler_use_next_block(c, end);
3912 }
3913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914}
3915
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003916static PyTypeObject *
3917infer_type(expr_ty e)
3918{
3919 switch (e->kind) {
3920 case Tuple_kind:
3921 return &PyTuple_Type;
3922 case List_kind:
3923 case ListComp_kind:
3924 return &PyList_Type;
3925 case Dict_kind:
3926 case DictComp_kind:
3927 return &PyDict_Type;
3928 case Set_kind:
3929 case SetComp_kind:
3930 return &PySet_Type;
3931 case GeneratorExp_kind:
3932 return &PyGen_Type;
3933 case Lambda_kind:
3934 return &PyFunction_Type;
3935 case JoinedStr_kind:
3936 case FormattedValue_kind:
3937 return &PyUnicode_Type;
3938 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003939 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003940 default:
3941 return NULL;
3942 }
3943}
3944
3945static int
3946check_caller(struct compiler *c, expr_ty e)
3947{
3948 switch (e->kind) {
3949 case Constant_kind:
3950 case Tuple_kind:
3951 case List_kind:
3952 case ListComp_kind:
3953 case Dict_kind:
3954 case DictComp_kind:
3955 case Set_kind:
3956 case SetComp_kind:
3957 case GeneratorExp_kind:
3958 case JoinedStr_kind:
3959 case FormattedValue_kind:
3960 return compiler_warn(c, "'%.200s' object is not callable; "
3961 "perhaps you missed a comma?",
3962 infer_type(e)->tp_name);
3963 default:
3964 return 1;
3965 }
3966}
3967
3968static int
3969check_subscripter(struct compiler *c, expr_ty e)
3970{
3971 PyObject *v;
3972
3973 switch (e->kind) {
3974 case Constant_kind:
3975 v = e->v.Constant.value;
3976 if (!(v == Py_None || v == Py_Ellipsis ||
3977 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3978 PyAnySet_Check(v)))
3979 {
3980 return 1;
3981 }
3982 /* fall through */
3983 case Set_kind:
3984 case SetComp_kind:
3985 case GeneratorExp_kind:
3986 case Lambda_kind:
3987 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3988 "perhaps you missed a comma?",
3989 infer_type(e)->tp_name);
3990 default:
3991 return 1;
3992 }
3993}
3994
3995static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02003996check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003997{
3998 PyObject *v;
3999
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004000 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004001 if (index_type == NULL
4002 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4003 || index_type == &PySlice_Type) {
4004 return 1;
4005 }
4006
4007 switch (e->kind) {
4008 case Constant_kind:
4009 v = e->v.Constant.value;
4010 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4011 return 1;
4012 }
4013 /* fall through */
4014 case Tuple_kind:
4015 case List_kind:
4016 case ListComp_kind:
4017 case JoinedStr_kind:
4018 case FormattedValue_kind:
4019 return compiler_warn(c, "%.200s indices must be integers or slices, "
4020 "not %.200s; "
4021 "perhaps you missed a comma?",
4022 infer_type(e)->tp_name,
4023 index_type->tp_name);
4024 default:
4025 return 1;
4026 }
4027}
4028
Zackery Spytz97f5de02019-03-22 01:30:32 -06004029// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004031maybe_optimize_method_call(struct compiler *c, expr_ty e)
4032{
4033 Py_ssize_t argsl, i;
4034 expr_ty meth = e->v.Call.func;
4035 asdl_seq *args = e->v.Call.args;
4036
4037 /* Check that the call node is an attribute access, and that
4038 the call doesn't have keyword parameters. */
4039 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4040 asdl_seq_LEN(e->v.Call.keywords))
4041 return -1;
4042
4043 /* Check that there are no *varargs types of arguments. */
4044 argsl = asdl_seq_LEN(args);
4045 for (i = 0; i < argsl; i++) {
4046 expr_ty elt = asdl_seq_GET(args, i);
4047 if (elt->kind == Starred_kind) {
4048 return -1;
4049 }
4050 }
4051
4052 /* Alright, we can optimize the code. */
4053 VISIT(c, expr, meth->v.Attribute.value);
4054 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4055 VISIT_SEQ(c, expr, e->v.Call.args);
4056 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4057 return 1;
4058}
4059
4060static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004061compiler_call(struct compiler *c, expr_ty e)
4062{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004063 int ret = maybe_optimize_method_call(c, e);
4064 if (ret >= 0) {
4065 return ret;
4066 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004067 if (!check_caller(c, e->v.Call.func)) {
4068 return 0;
4069 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 VISIT(c, expr, e->v.Call.func);
4071 return compiler_call_helper(c, 0,
4072 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004073 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004074}
4075
Eric V. Smith235a6f02015-09-19 14:51:32 -04004076static int
4077compiler_joined_str(struct compiler *c, expr_ty e)
4078{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004079 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004080 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4081 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004082 return 1;
4083}
4084
Eric V. Smitha78c7952015-11-03 12:45:05 -05004085/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004086static int
4087compiler_formatted_value(struct compiler *c, expr_ty e)
4088{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004089 /* Our oparg encodes 2 pieces of information: the conversion
4090 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004091
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004092 Convert the conversion char to 3 bits:
4093 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004094 !s : 001 0x1 FVC_STR
4095 !r : 010 0x2 FVC_REPR
4096 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004097
Eric V. Smitha78c7952015-11-03 12:45:05 -05004098 next bit is whether or not we have a format spec:
4099 yes : 100 0x4
4100 no : 000 0x0
4101 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004102
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004103 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004104 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004105
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004106 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004107 VISIT(c, expr, e->v.FormattedValue.value);
4108
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004109 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004110 case 's': oparg = FVC_STR; break;
4111 case 'r': oparg = FVC_REPR; break;
4112 case 'a': oparg = FVC_ASCII; break;
4113 case -1: oparg = FVC_NONE; break;
4114 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004115 PyErr_Format(PyExc_SystemError,
4116 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004117 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004118 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004119 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004120 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004121 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004122 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004123 }
4124
Eric V. Smitha78c7952015-11-03 12:45:05 -05004125 /* And push our opcode and oparg */
4126 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004127
Eric V. Smith235a6f02015-09-19 14:51:32 -04004128 return 1;
4129}
4130
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004131static int
4132compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4133{
4134 Py_ssize_t i, n = end - begin;
4135 keyword_ty kw;
4136 PyObject *keys, *key;
4137 assert(n > 0);
4138 if (n > 1) {
4139 for (i = begin; i < end; i++) {
4140 kw = asdl_seq_GET(keywords, i);
4141 VISIT(c, expr, kw->value);
4142 }
4143 keys = PyTuple_New(n);
4144 if (keys == NULL) {
4145 return 0;
4146 }
4147 for (i = begin; i < end; i++) {
4148 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4149 Py_INCREF(key);
4150 PyTuple_SET_ITEM(keys, i - begin, key);
4151 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004152 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004153 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4154 }
4155 else {
4156 /* a for loop only executes once */
4157 for (i = begin; i < end; i++) {
4158 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004159 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004160 VISIT(c, expr, kw->value);
4161 }
4162 ADDOP_I(c, BUILD_MAP, n);
4163 }
4164 return 1;
4165}
4166
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004167/* shared code between compiler_call and compiler_class */
4168static int
4169compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004170 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004171 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004172 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004173{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004174 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004175
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004176 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004177 nkwelts = asdl_seq_LEN(keywords);
4178
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004179 for (i = 0; i < nelts; i++) {
4180 expr_ty elt = asdl_seq_GET(args, i);
4181 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004182 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004183 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004184 }
4185 for (i = 0; i < nkwelts; i++) {
4186 keyword_ty kw = asdl_seq_GET(keywords, i);
4187 if (kw->arg == NULL) {
4188 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004189 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004191
Mark Shannon13bc1392020-01-23 09:25:17 +00004192 /* No * or ** args, so can use faster calling sequence */
4193 for (i = 0; i < nelts; i++) {
4194 expr_ty elt = asdl_seq_GET(args, i);
4195 assert(elt->kind != Starred_kind);
4196 VISIT(c, expr, elt);
4197 }
4198 if (nkwelts) {
4199 PyObject *names;
4200 VISIT_SEQ(c, keyword, keywords);
4201 names = PyTuple_New(nkwelts);
4202 if (names == NULL) {
4203 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004204 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004205 for (i = 0; i < nkwelts; i++) {
4206 keyword_ty kw = asdl_seq_GET(keywords, i);
4207 Py_INCREF(kw->arg);
4208 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004209 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004210 ADDOP_LOAD_CONST_NEW(c, names);
4211 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4212 return 1;
4213 }
4214 else {
4215 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4216 return 1;
4217 }
4218
4219ex_call:
4220
4221 /* Do positional arguments. */
4222 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4223 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4224 }
4225 else if (starunpack_helper(c, args, n, BUILD_LIST,
4226 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4227 return 0;
4228 }
4229 /* Then keyword arguments */
4230 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004231 /* Has a new dict been pushed */
4232 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004233
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004234 nseen = 0; /* the number of keyword arguments on the stack following */
4235 for (i = 0; i < nkwelts; i++) {
4236 keyword_ty kw = asdl_seq_GET(keywords, i);
4237 if (kw->arg == NULL) {
4238 /* A keyword argument unpacking. */
4239 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004240 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004241 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004242 }
4243 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004244 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004245 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004246 if (!have_dict) {
4247 ADDOP_I(c, BUILD_MAP, 0);
4248 have_dict = 1;
4249 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004250 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004251 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004252 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004253 else {
4254 nseen++;
4255 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004256 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004257 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004258 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004259 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004260 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004261 }
4262 if (have_dict) {
4263 ADDOP_I(c, DICT_MERGE, 1);
4264 }
4265 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004266 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004267 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004269 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4270 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004271}
4272
Nick Coghlan650f0d02007-04-15 12:05:43 +00004273
4274/* List and set comprehensions and generator expressions work by creating a
4275 nested function to perform the actual iteration. This means that the
4276 iteration variables don't leak into the current scope.
4277 The defined function is called immediately following its definition, with the
4278 result of that call being the result of the expression.
4279 The LC/SC version returns the populated container, while the GE version is
4280 flagged in symtable.c as a generator, so it returns the generator object
4281 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004282
4283 Possible cleanups:
4284 - iterate over the generator sequence instead of using recursion
4285*/
4286
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004288static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289compiler_comprehension_generator(struct compiler *c,
4290 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004291 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004294 comprehension_ty gen;
4295 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4296 if (gen->is_async) {
4297 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004298 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004299 } else {
4300 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004301 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004302 }
4303}
4304
4305static int
4306compiler_sync_comprehension_generator(struct compiler *c,
4307 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004308 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004309 expr_ty elt, expr_ty val, int type)
4310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 /* generate code for the iterator, then each of the ifs,
4312 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 comprehension_ty gen;
4315 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004316 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 start = compiler_new_block(c);
4319 skip = compiler_new_block(c);
4320 if_cleanup = compiler_new_block(c);
4321 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4324 anchor == NULL)
4325 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 if (gen_index == 0) {
4330 /* Receive outermost iter as an implicit argument */
4331 c->u->u_argcount = 1;
4332 ADDOP_I(c, LOAD_FAST, 0);
4333 }
4334 else {
4335 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004336 /* Fast path for the temporary variable assignment idiom:
4337 for y in [f(x)]
4338 */
4339 asdl_seq *elts;
4340 switch (gen->iter->kind) {
4341 case List_kind:
4342 elts = gen->iter->v.List.elts;
4343 break;
4344 case Tuple_kind:
4345 elts = gen->iter->v.Tuple.elts;
4346 break;
4347 default:
4348 elts = NULL;
4349 }
4350 if (asdl_seq_LEN(elts) == 1) {
4351 expr_ty elt = asdl_seq_GET(elts, 0);
4352 if (elt->kind != Starred_kind) {
4353 VISIT(c, expr, elt);
4354 start = NULL;
4355 }
4356 }
4357 if (start) {
4358 VISIT(c, expr, gen->iter);
4359 ADDOP(c, GET_ITER);
4360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004362 if (start) {
4363 depth++;
4364 compiler_use_next_block(c, start);
4365 ADDOP_JREL(c, FOR_ITER, anchor);
4366 NEXT_BLOCK(c);
4367 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 /* XXX this needs to be cleaned up...a lot! */
4371 n = asdl_seq_LEN(gen->ifs);
4372 for (i = 0; i < n; i++) {
4373 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004374 if (!compiler_jump_if(c, e, if_cleanup, 0))
4375 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 NEXT_BLOCK(c);
4377 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (++gen_index < asdl_seq_LEN(generators))
4380 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004381 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 elt, val, type))
4383 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 /* only append after the last for generator */
4386 if (gen_index >= asdl_seq_LEN(generators)) {
4387 /* comprehension specific code */
4388 switch (type) {
4389 case COMP_GENEXP:
4390 VISIT(c, expr, elt);
4391 ADDOP(c, YIELD_VALUE);
4392 ADDOP(c, POP_TOP);
4393 break;
4394 case COMP_LISTCOMP:
4395 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004396 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 break;
4398 case COMP_SETCOMP:
4399 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004400 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 break;
4402 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004403 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004406 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004407 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 break;
4409 default:
4410 return 0;
4411 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 compiler_use_next_block(c, skip);
4414 }
4415 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004416 if (start) {
4417 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4418 compiler_use_next_block(c, anchor);
4419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420
4421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422}
4423
4424static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425compiler_async_comprehension_generator(struct compiler *c,
4426 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004427 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004428 expr_ty elt, expr_ty val, int type)
4429{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004431 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004432 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004433 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004434 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004435 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004436
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004437 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004438 return 0;
4439 }
4440
4441 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4442
4443 if (gen_index == 0) {
4444 /* Receive outermost iter as an implicit argument */
4445 c->u->u_argcount = 1;
4446 ADDOP_I(c, LOAD_FAST, 0);
4447 }
4448 else {
4449 /* Sub-iter - calculate on the fly */
4450 VISIT(c, expr, gen->iter);
4451 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004452 }
4453
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004454 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004455
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004456 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004457 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004458 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004459 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004460 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004461 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004462
4463 n = asdl_seq_LEN(gen->ifs);
4464 for (i = 0; i < n; i++) {
4465 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004466 if (!compiler_jump_if(c, e, if_cleanup, 0))
4467 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004468 NEXT_BLOCK(c);
4469 }
4470
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004471 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004472 if (++gen_index < asdl_seq_LEN(generators))
4473 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004475 elt, val, type))
4476 return 0;
4477
4478 /* only append after the last for generator */
4479 if (gen_index >= asdl_seq_LEN(generators)) {
4480 /* comprehension specific code */
4481 switch (type) {
4482 case COMP_GENEXP:
4483 VISIT(c, expr, elt);
4484 ADDOP(c, YIELD_VALUE);
4485 ADDOP(c, POP_TOP);
4486 break;
4487 case COMP_LISTCOMP:
4488 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004489 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 break;
4491 case COMP_SETCOMP:
4492 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004493 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494 break;
4495 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004496 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004498 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004499 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004500 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004501 break;
4502 default:
4503 return 0;
4504 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505 }
4506 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004507 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4508
4509 compiler_use_next_block(c, except);
4510 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004511
4512 return 1;
4513}
4514
4515static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004516compiler_comprehension(struct compiler *c, expr_ty e, int type,
4517 identifier name, asdl_seq *generators, expr_ty elt,
4518 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004522 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523 int is_async_function = c->u->u_ste->ste_coroutine;
4524 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004525
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004527
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004528 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4529 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 }
4533
4534 is_async_generator = c->u->u_ste->ste_coroutine;
4535
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004536 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 compiler_error(c, "asynchronous comprehension outside of "
4538 "an asynchronous function");
4539 goto error_in_scope;
4540 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 if (type != COMP_GENEXP) {
4543 int op;
4544 switch (type) {
4545 case COMP_LISTCOMP:
4546 op = BUILD_LIST;
4547 break;
4548 case COMP_SETCOMP:
4549 op = BUILD_SET;
4550 break;
4551 case COMP_DICTCOMP:
4552 op = BUILD_MAP;
4553 break;
4554 default:
4555 PyErr_Format(PyExc_SystemError,
4556 "unknown comprehension type %d", type);
4557 goto error_in_scope;
4558 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 ADDOP_I(c, op, 0);
4561 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004562
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004563 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 val, type))
4565 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (type != COMP_GENEXP) {
4568 ADDOP(c, RETURN_VALUE);
4569 }
4570
4571 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004572 qualname = c->u->u_qualname;
4573 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004575 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 goto error;
4577
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004578 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004580 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 Py_DECREF(co);
4582
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583 VISIT(c, expr, outermost->iter);
4584
4585 if (outermost->is_async) {
4586 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004587 } else {
4588 ADDOP(c, GET_ITER);
4589 }
4590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004592
4593 if (is_async_generator && type != COMP_GENEXP) {
4594 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004595 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004596 ADDOP(c, YIELD_FROM);
4597 }
4598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004600error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004602error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004603 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 Py_XDECREF(co);
4605 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004606}
4607
4608static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004609compiler_genexp(struct compiler *c, expr_ty e)
4610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 static identifier name;
4612 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004613 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 if (!name)
4615 return 0;
4616 }
4617 assert(e->kind == GeneratorExp_kind);
4618 return compiler_comprehension(c, e, COMP_GENEXP, name,
4619 e->v.GeneratorExp.generators,
4620 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004621}
4622
4623static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004624compiler_listcomp(struct compiler *c, expr_ty e)
4625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 static identifier name;
4627 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004628 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 if (!name)
4630 return 0;
4631 }
4632 assert(e->kind == ListComp_kind);
4633 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4634 e->v.ListComp.generators,
4635 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004636}
4637
4638static int
4639compiler_setcomp(struct compiler *c, expr_ty e)
4640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 static identifier name;
4642 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004643 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 if (!name)
4645 return 0;
4646 }
4647 assert(e->kind == SetComp_kind);
4648 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4649 e->v.SetComp.generators,
4650 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004651}
4652
4653
4654static int
4655compiler_dictcomp(struct compiler *c, expr_ty e)
4656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 static identifier name;
4658 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004659 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 if (!name)
4661 return 0;
4662 }
4663 assert(e->kind == DictComp_kind);
4664 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4665 e->v.DictComp.generators,
4666 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004667}
4668
4669
4670static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004671compiler_visit_keyword(struct compiler *c, keyword_ty k)
4672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 VISIT(c, expr, k->value);
4674 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004675}
4676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004678 whether they are true or false.
4679
4680 Return values: 1 for true, 0 for false, -1 for non-constant.
4681 */
4682
4683static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004684expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004685{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004686 if (e->kind == Constant_kind) {
4687 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004688 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004689 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004690}
4691
Mark Shannonfee55262019-11-21 09:11:43 +00004692static int
4693compiler_with_except_finish(struct compiler *c) {
4694 basicblock *exit;
4695 exit = compiler_new_block(c);
4696 if (exit == NULL)
4697 return 0;
4698 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4699 ADDOP(c, RERAISE);
4700 compiler_use_next_block(c, exit);
4701 ADDOP(c, POP_TOP);
4702 ADDOP(c, POP_TOP);
4703 ADDOP(c, POP_TOP);
4704 ADDOP(c, POP_EXCEPT);
4705 ADDOP(c, POP_TOP);
4706 return 1;
4707}
Yury Selivanov75445082015-05-11 22:57:16 -04004708
4709/*
4710 Implements the async with statement.
4711
4712 The semantics outlined in that PEP are as follows:
4713
4714 async with EXPR as VAR:
4715 BLOCK
4716
4717 It is implemented roughly as:
4718
4719 context = EXPR
4720 exit = context.__aexit__ # not calling it
4721 value = await context.__aenter__()
4722 try:
4723 VAR = value # if VAR present in the syntax
4724 BLOCK
4725 finally:
4726 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004727 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004728 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004729 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004730 if not (await exit(*exc)):
4731 raise
4732 */
4733static int
4734compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4735{
Mark Shannonfee55262019-11-21 09:11:43 +00004736 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004737 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4738
4739 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004740 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004741 c->u->u_ste->ste_coroutine = 1;
4742 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004743 return compiler_error(c, "'async with' outside async function");
4744 }
Yury Selivanov75445082015-05-11 22:57:16 -04004745
4746 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004747 final = compiler_new_block(c);
4748 exit = compiler_new_block(c);
4749 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004750 return 0;
4751
4752 /* Evaluate EXPR */
4753 VISIT(c, expr, item->context_expr);
4754
4755 ADDOP(c, BEFORE_ASYNC_WITH);
4756 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004757 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004758 ADDOP(c, YIELD_FROM);
4759
Mark Shannonfee55262019-11-21 09:11:43 +00004760 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004761
4762 /* SETUP_ASYNC_WITH pushes a finally block. */
4763 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004764 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004765 return 0;
4766 }
4767
4768 if (item->optional_vars) {
4769 VISIT(c, expr, item->optional_vars);
4770 }
4771 else {
4772 /* Discard result from context.__aenter__() */
4773 ADDOP(c, POP_TOP);
4774 }
4775
4776 pos++;
4777 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4778 /* BLOCK code */
4779 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4780 else if (!compiler_async_with(c, s, pos))
4781 return 0;
4782
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004783 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004784 ADDOP(c, POP_BLOCK);
4785 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004786
Mark Shannonfee55262019-11-21 09:11:43 +00004787 /* For successful outcome:
4788 * call __exit__(None, None, None)
4789 */
4790 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004791 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004792 ADDOP(c, GET_AWAITABLE);
4793 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4794 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004795
Mark Shannonfee55262019-11-21 09:11:43 +00004796 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004797
Mark Shannonfee55262019-11-21 09:11:43 +00004798 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4799
4800 /* For exceptional outcome: */
4801 compiler_use_next_block(c, final);
4802
4803 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004804 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004805 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004806 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004807 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004808
Mark Shannonfee55262019-11-21 09:11:43 +00004809compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004810 return 1;
4811}
4812
4813
Guido van Rossumc2e20742006-02-27 22:32:47 +00004814/*
4815 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004816 with EXPR as VAR:
4817 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004818 is implemented as:
4819 <code for EXPR>
4820 SETUP_WITH E
4821 <code to store to VAR> or POP_TOP
4822 <code for BLOCK>
4823 LOAD_CONST (None, None, None)
4824 CALL_FUNCTION_EX 0
4825 JUMP_FORWARD EXIT
4826 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4827 POP_JUMP_IF_TRUE T:
4828 RERAISE
4829 T: POP_TOP * 3 (remove exception from stack)
4830 POP_EXCEPT
4831 POP_TOP
4832 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004833 */
Mark Shannonfee55262019-11-21 09:11:43 +00004834
Guido van Rossumc2e20742006-02-27 22:32:47 +00004835static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004836compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004837{
Mark Shannonfee55262019-11-21 09:11:43 +00004838 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004839 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004840
4841 assert(s->kind == With_kind);
4842
Guido van Rossumc2e20742006-02-27 22:32:47 +00004843 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004844 final = compiler_new_block(c);
4845 exit = compiler_new_block(c);
4846 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004847 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004848
Thomas Wouters477c8d52006-05-27 19:21:47 +00004849 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004850 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004851 /* Will push bound __exit__ */
4852 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004853
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004854 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004855 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004856 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004857 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004858 }
4859
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004860 if (item->optional_vars) {
4861 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004862 }
4863 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004864 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004865 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004866 }
4867
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004868 pos++;
4869 if (pos == asdl_seq_LEN(s->v.With.items))
4870 /* BLOCK code */
4871 VISIT_SEQ(c, stmt, s->v.With.body)
4872 else if (!compiler_with(c, s, pos))
4873 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004874
Guido van Rossumc2e20742006-02-27 22:32:47 +00004875 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004876 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004877
Mark Shannonfee55262019-11-21 09:11:43 +00004878 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004879
Mark Shannonfee55262019-11-21 09:11:43 +00004880 /* For successful outcome:
4881 * call __exit__(None, None, None)
4882 */
4883 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004884 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004885 ADDOP(c, POP_TOP);
4886 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004887
Mark Shannonfee55262019-11-21 09:11:43 +00004888 /* For exceptional outcome: */
4889 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890
Mark Shannonfee55262019-11-21 09:11:43 +00004891 ADDOP(c, WITH_EXCEPT_START);
4892 compiler_with_except_finish(c);
4893
4894 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004895 return 1;
4896}
4897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004898static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004899compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004902 case NamedExpr_kind:
4903 VISIT(c, expr, e->v.NamedExpr.value);
4904 ADDOP(c, DUP_TOP);
4905 VISIT(c, expr, e->v.NamedExpr.target);
4906 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 case BoolOp_kind:
4908 return compiler_boolop(c, e);
4909 case BinOp_kind:
4910 VISIT(c, expr, e->v.BinOp.left);
4911 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004912 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 break;
4914 case UnaryOp_kind:
4915 VISIT(c, expr, e->v.UnaryOp.operand);
4916 ADDOP(c, unaryop(e->v.UnaryOp.op));
4917 break;
4918 case Lambda_kind:
4919 return compiler_lambda(c, e);
4920 case IfExp_kind:
4921 return compiler_ifexp(c, e);
4922 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004923 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004925 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 case GeneratorExp_kind:
4927 return compiler_genexp(c, e);
4928 case ListComp_kind:
4929 return compiler_listcomp(c, e);
4930 case SetComp_kind:
4931 return compiler_setcomp(c, e);
4932 case DictComp_kind:
4933 return compiler_dictcomp(c, e);
4934 case Yield_kind:
4935 if (c->u->u_ste->ste_type != FunctionBlock)
4936 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004937 if (e->v.Yield.value) {
4938 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 }
4940 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004941 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004942 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004943 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004945 case YieldFrom_kind:
4946 if (c->u->u_ste->ste_type != FunctionBlock)
4947 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004948
4949 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4950 return compiler_error(c, "'yield from' inside async function");
4951
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004952 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004953 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004954 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004955 ADDOP(c, YIELD_FROM);
4956 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004957 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00004958 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004959 if (c->u->u_ste->ste_type != FunctionBlock){
4960 return compiler_error(c, "'await' outside function");
4961 }
Yury Selivanov75445082015-05-11 22:57:16 -04004962
Victor Stinner331a6a52019-05-27 16:39:22 +02004963 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004964 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4965 return compiler_error(c, "'await' outside async function");
4966 }
4967 }
Yury Selivanov75445082015-05-11 22:57:16 -04004968
4969 VISIT(c, expr, e->v.Await.value);
4970 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004971 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004972 ADDOP(c, YIELD_FROM);
4973 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 case Compare_kind:
4975 return compiler_compare(c, e);
4976 case Call_kind:
4977 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004978 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004979 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004980 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004981 case JoinedStr_kind:
4982 return compiler_joined_str(c, e);
4983 case FormattedValue_kind:
4984 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 /* The following exprs can be assignment targets. */
4986 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02004987 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 case Load:
4990 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4991 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 case Store:
4993 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4994 break;
4995 case Del:
4996 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4997 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 }
4999 break;
5000 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005001 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005002 case Starred_kind:
5003 switch (e->v.Starred.ctx) {
5004 case Store:
5005 /* In all legitimate cases, the Starred node was already replaced
5006 * by compiler_list/compiler_tuple. XXX: is that okay? */
5007 return compiler_error(c,
5008 "starred assignment target must be in a list or tuple");
5009 default:
5010 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005011 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005013 break;
5014 case Slice_kind:
5015 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 case Name_kind:
5017 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5018 /* child nodes of List and Tuple will have expr_context set */
5019 case List_kind:
5020 return compiler_list(c, e);
5021 case Tuple_kind:
5022 return compiler_tuple(c, e);
5023 }
5024 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005025}
5026
5027static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005028compiler_visit_expr(struct compiler *c, expr_ty e)
5029{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005030 int old_lineno = c->u->u_lineno;
5031 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005032 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005033 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005034 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005035 c->u->u_col_offset = old_col_offset;
5036 return res;
5037}
5038
5039static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005040compiler_augassign(struct compiler *c, stmt_ty s)
5041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005043 expr_ty e = s->v.AugAssign.target;
5044
5045 int old_lineno = c->u->u_lineno;
5046 int old_col_offset = c->u->u_col_offset;
5047 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 switch (e->kind) {
5050 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005051 VISIT(c, expr, e->v.Attribute.value);
5052 ADDOP(c, DUP_TOP);
5053 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 break;
5055 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005056 VISIT(c, expr, e->v.Subscript.value);
5057 VISIT(c, expr, e->v.Subscript.slice);
5058 ADDOP(c, DUP_TOP_TWO);
5059 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 break;
5061 case Name_kind:
5062 if (!compiler_nameop(c, e->v.Name.id, Load))
5063 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005064 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 default:
5066 PyErr_Format(PyExc_SystemError,
5067 "invalid node type (%d) for augmented assignment",
5068 e->kind);
5069 return 0;
5070 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005071
5072 c->u->u_lineno = old_lineno;
5073 c->u->u_col_offset = old_col_offset;
5074
5075 VISIT(c, expr, s->v.AugAssign.value);
5076 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5077
5078 SET_LOC(c, e);
5079
5080 switch (e->kind) {
5081 case Attribute_kind:
5082 ADDOP(c, ROT_TWO);
5083 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5084 break;
5085 case Subscript_kind:
5086 ADDOP(c, ROT_THREE);
5087 ADDOP(c, STORE_SUBSCR);
5088 break;
5089 case Name_kind:
5090 return compiler_nameop(c, e->v.Name.id, Store);
5091 default:
5092 Py_UNREACHABLE();
5093 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095}
5096
5097static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005098check_ann_expr(struct compiler *c, expr_ty e)
5099{
5100 VISIT(c, expr, e);
5101 ADDOP(c, POP_TOP);
5102 return 1;
5103}
5104
5105static int
5106check_annotation(struct compiler *c, stmt_ty s)
5107{
5108 /* Annotations are only evaluated in a module or class. */
5109 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5110 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5111 return check_ann_expr(c, s->v.AnnAssign.annotation);
5112 }
5113 return 1;
5114}
5115
5116static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005117check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005118{
5119 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005120 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005121 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005122 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005123 return 0;
5124 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005125 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5126 return 0;
5127 }
5128 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5129 return 0;
5130 }
5131 return 1;
5132 case Tuple_kind: {
5133 /* extended slice */
5134 asdl_seq *elts = e->v.Tuple.elts;
5135 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005136 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005137 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005138 return 0;
5139 }
5140 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005141 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005142 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005143 default:
5144 return check_ann_expr(c, e);
5145 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005146}
5147
5148static int
5149compiler_annassign(struct compiler *c, stmt_ty s)
5150{
5151 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005152 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005153
5154 assert(s->kind == AnnAssign_kind);
5155
5156 /* We perform the actual assignment first. */
5157 if (s->v.AnnAssign.value) {
5158 VISIT(c, expr, s->v.AnnAssign.value);
5159 VISIT(c, expr, targ);
5160 }
5161 switch (targ->kind) {
5162 case Name_kind:
5163 /* If we have a simple name in a module or class, store annotation. */
5164 if (s->v.AnnAssign.simple &&
5165 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5166 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005167 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5168 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5169 }
5170 else {
5171 VISIT(c, expr, s->v.AnnAssign.annotation);
5172 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005173 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005174 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005175 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005176 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005177 }
5178 break;
5179 case Attribute_kind:
5180 if (!s->v.AnnAssign.value &&
5181 !check_ann_expr(c, targ->v.Attribute.value)) {
5182 return 0;
5183 }
5184 break;
5185 case Subscript_kind:
5186 if (!s->v.AnnAssign.value &&
5187 (!check_ann_expr(c, targ->v.Subscript.value) ||
5188 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5189 return 0;
5190 }
5191 break;
5192 default:
5193 PyErr_Format(PyExc_SystemError,
5194 "invalid node type (%d) for annotated assignment",
5195 targ->kind);
5196 return 0;
5197 }
5198 /* Annotation is evaluated last. */
5199 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5200 return 0;
5201 }
5202 return 1;
5203}
5204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005205/* Raises a SyntaxError and returns 0.
5206 If something goes wrong, a different exception may be raised.
5207*/
5208
5209static int
5210compiler_error(struct compiler *c, const char *errstr)
5211{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005212 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005214
Victor Stinner14e461d2013-08-26 22:28:21 +02005215 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 if (!loc) {
5217 Py_INCREF(Py_None);
5218 loc = Py_None;
5219 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005220 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005221 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 if (!u)
5223 goto exit;
5224 v = Py_BuildValue("(zO)", errstr, u);
5225 if (!v)
5226 goto exit;
5227 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005228 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 Py_DECREF(loc);
5230 Py_XDECREF(u);
5231 Py_XDECREF(v);
5232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005233}
5234
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005235/* Emits a SyntaxWarning and returns 1 on success.
5236 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5237 and returns 0.
5238*/
5239static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005240compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005241{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005242 va_list vargs;
5243#ifdef HAVE_STDARG_PROTOTYPES
5244 va_start(vargs, format);
5245#else
5246 va_start(vargs);
5247#endif
5248 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5249 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005250 if (msg == NULL) {
5251 return 0;
5252 }
5253 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5254 c->u->u_lineno, NULL, NULL) < 0)
5255 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005256 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005257 /* Replace the SyntaxWarning exception with a SyntaxError
5258 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005259 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005260 assert(PyUnicode_AsUTF8(msg) != NULL);
5261 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005262 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005263 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005264 return 0;
5265 }
5266 Py_DECREF(msg);
5267 return 1;
5268}
5269
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005270static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005271compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005272{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005273 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005275
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005276 if (ctx == Load) {
5277 if (!check_subscripter(c, e->v.Subscript.value)) {
5278 return 0;
5279 }
5280 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5281 return 0;
5282 }
5283 }
5284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005285 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 case Store: op = STORE_SUBSCR; break;
5288 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005289 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005290 assert(op);
5291 VISIT(c, expr, e->v.Subscript.value);
5292 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 ADDOP(c, op);
5294 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295}
5296
5297static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005298compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 int n = 2;
5301 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 /* only handles the cases where BUILD_SLICE is emitted */
5304 if (s->v.Slice.lower) {
5305 VISIT(c, expr, s->v.Slice.lower);
5306 }
5307 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005308 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 if (s->v.Slice.upper) {
5312 VISIT(c, expr, s->v.Slice.upper);
5313 }
5314 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005315 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 }
5317
5318 if (s->v.Slice.step) {
5319 n++;
5320 VISIT(c, expr, s->v.Slice.step);
5321 }
5322 ADDOP_I(c, BUILD_SLICE, n);
5323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324}
5325
Thomas Wouters89f507f2006-12-13 04:49:30 +00005326/* End of the compiler section, beginning of the assembler section */
5327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005328/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005329 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005330
5331 XXX must handle implicit jumps from one block to next
5332*/
5333
Thomas Wouters89f507f2006-12-13 04:49:30 +00005334struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 PyObject *a_bytecode; /* string containing bytecode */
5336 int a_offset; /* offset into bytecode */
5337 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005338 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 PyObject *a_lnotab; /* string containing lnotab */
5340 int a_lnotab_off; /* offset into lnotab */
5341 int a_lineno; /* last lineno of emitted instruction */
5342 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005343};
5344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005345static void
T. Wouters99b54d62019-09-12 07:05:33 -07005346dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347{
T. Wouters99b54d62019-09-12 07:05:33 -07005348 int i, j;
5349
5350 /* Get rid of recursion for normal control flow.
5351 Since the number of blocks is limited, unused space in a_postorder
5352 (from a_nblocks to end) can be used as a stack for still not ordered
5353 blocks. */
5354 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005355 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005356 assert(a->a_nblocks < j);
5357 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 }
T. Wouters99b54d62019-09-12 07:05:33 -07005359 while (j < end) {
5360 b = a->a_postorder[j++];
5361 for (i = 0; i < b->b_iused; i++) {
5362 struct instr *instr = &b->b_instr[i];
5363 if (instr->i_jrel || instr->i_jabs)
5364 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005365 }
T. Wouters99b54d62019-09-12 07:05:33 -07005366 assert(a->a_nblocks < j);
5367 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005369}
5370
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005371Py_LOCAL_INLINE(void)
5372stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005374 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005375 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005376 assert(b->b_startdepth < 0);
5377 b->b_startdepth = depth;
5378 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005379 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380}
5381
5382/* Find the flow path that needs the largest stack. We assume that
5383 * cycles in the flow graph have no net effect on the stack depth.
5384 */
5385static int
5386stackdepth(struct compiler *c)
5387{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005388 basicblock *b, *entryblock = NULL;
5389 basicblock **stack, **sp;
5390 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 b->b_startdepth = INT_MIN;
5393 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005394 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 }
5396 if (!entryblock)
5397 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005398 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5399 if (!stack) {
5400 PyErr_NoMemory();
5401 return -1;
5402 }
5403
5404 sp = stack;
5405 stackdepth_push(&sp, entryblock, 0);
5406 while (sp != stack) {
5407 b = *--sp;
5408 int depth = b->b_startdepth;
5409 assert(depth >= 0);
5410 basicblock *next = b->b_next;
5411 for (int i = 0; i < b->b_iused; i++) {
5412 struct instr *instr = &b->b_instr[i];
5413 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5414 if (effect == PY_INVALID_STACK_EFFECT) {
5415 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5416 Py_FatalError("PyCompile_OpcodeStackEffect()");
5417 }
5418 int new_depth = depth + effect;
5419 if (new_depth > maxdepth) {
5420 maxdepth = new_depth;
5421 }
5422 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5423 if (instr->i_jrel || instr->i_jabs) {
5424 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5425 assert(effect != PY_INVALID_STACK_EFFECT);
5426 int target_depth = depth + effect;
5427 if (target_depth > maxdepth) {
5428 maxdepth = target_depth;
5429 }
5430 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005431 stackdepth_push(&sp, instr->i_target, target_depth);
5432 }
5433 depth = new_depth;
5434 if (instr->i_opcode == JUMP_ABSOLUTE ||
5435 instr->i_opcode == JUMP_FORWARD ||
5436 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005437 instr->i_opcode == RAISE_VARARGS ||
5438 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 {
5440 /* remaining code is dead */
5441 next = NULL;
5442 break;
5443 }
5444 }
5445 if (next != NULL) {
5446 stackdepth_push(&sp, next, depth);
5447 }
5448 }
5449 PyObject_Free(stack);
5450 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451}
5452
5453static int
5454assemble_init(struct assembler *a, int nblocks, int firstlineno)
5455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 memset(a, 0, sizeof(struct assembler));
5457 a->a_lineno = firstlineno;
5458 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5459 if (!a->a_bytecode)
5460 return 0;
5461 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5462 if (!a->a_lnotab)
5463 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005464 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 PyErr_NoMemory();
5466 return 0;
5467 }
T. Wouters99b54d62019-09-12 07:05:33 -07005468 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005470 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 PyErr_NoMemory();
5472 return 0;
5473 }
5474 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005475}
5476
5477static void
5478assemble_free(struct assembler *a)
5479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 Py_XDECREF(a->a_bytecode);
5481 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005482 if (a->a_postorder)
5483 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005484}
5485
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005486static int
5487blocksize(basicblock *b)
5488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 int i;
5490 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005493 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005495}
5496
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005497/* Appends a pair to the end of the line number table, a_lnotab, representing
5498 the instruction's bytecode offset and line number. See
5499 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005500
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005501static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005502assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005504 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005505 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005506 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005509 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005511 }
5512
5513 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5514 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 if (d_bytecode > 255) {
5517 int j, nbytes, ncodes = d_bytecode / 255;
5518 nbytes = a->a_lnotab_off + 2 * ncodes;
5519 len = PyBytes_GET_SIZE(a->a_lnotab);
5520 if (nbytes >= len) {
5521 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5522 len = nbytes;
5523 else if (len <= INT_MAX / 2)
5524 len *= 2;
5525 else {
5526 PyErr_NoMemory();
5527 return 0;
5528 }
5529 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5530 return 0;
5531 }
5532 lnotab = (unsigned char *)
5533 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5534 for (j = 0; j < ncodes; j++) {
5535 *lnotab++ = 255;
5536 *lnotab++ = 0;
5537 }
5538 d_bytecode -= ncodes * 255;
5539 a->a_lnotab_off += ncodes * 2;
5540 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005541 assert(0 <= d_bytecode && d_bytecode <= 255);
5542
5543 if (d_lineno < -128 || 127 < d_lineno) {
5544 int j, nbytes, ncodes, k;
5545 if (d_lineno < 0) {
5546 k = -128;
5547 /* use division on positive numbers */
5548 ncodes = (-d_lineno) / 128;
5549 }
5550 else {
5551 k = 127;
5552 ncodes = d_lineno / 127;
5553 }
5554 d_lineno -= ncodes * k;
5555 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 nbytes = a->a_lnotab_off + 2 * ncodes;
5557 len = PyBytes_GET_SIZE(a->a_lnotab);
5558 if (nbytes >= len) {
5559 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5560 len = nbytes;
5561 else if (len <= INT_MAX / 2)
5562 len *= 2;
5563 else {
5564 PyErr_NoMemory();
5565 return 0;
5566 }
5567 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5568 return 0;
5569 }
5570 lnotab = (unsigned char *)
5571 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5572 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005573 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005574 d_bytecode = 0;
5575 for (j = 1; j < ncodes; j++) {
5576 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005577 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 a->a_lnotab_off += ncodes * 2;
5580 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005581 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 len = PyBytes_GET_SIZE(a->a_lnotab);
5584 if (a->a_lnotab_off + 2 >= len) {
5585 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5586 return 0;
5587 }
5588 lnotab = (unsigned char *)
5589 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005591 a->a_lnotab_off += 2;
5592 if (d_bytecode) {
5593 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005594 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 }
5596 else { /* First line of a block; def stmt, etc. */
5597 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005598 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005599 }
5600 a->a_lineno = i->i_lineno;
5601 a->a_lineno_off = a->a_offset;
5602 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005603}
5604
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005605/* assemble_emit()
5606 Extend the bytecode with a new instruction.
5607 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005608*/
5609
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005610static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005611assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005612{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005613 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005615 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005616
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005617 arg = i->i_oparg;
5618 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 if (i->i_lineno && !assemble_lnotab(a, i))
5620 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005621 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 if (len > PY_SSIZE_T_MAX / 2)
5623 return 0;
5624 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5625 return 0;
5626 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005627 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005629 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005631}
5632
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005633static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005634assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005637 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 /* Compute the size of each block and fixup jump args.
5641 Replace block pointer with position in bytecode. */
5642 do {
5643 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005644 for (i = a->a_nblocks - 1; i >= 0; i--) {
5645 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 bsize = blocksize(b);
5647 b->b_offset = totsize;
5648 totsize += bsize;
5649 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005650 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5652 bsize = b->b_offset;
5653 for (i = 0; i < b->b_iused; i++) {
5654 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005655 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 /* Relative jumps are computed relative to
5657 the instruction pointer after fetching
5658 the jump instruction.
5659 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005660 bsize += isize;
5661 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005663 if (instr->i_jrel) {
5664 instr->i_oparg -= bsize;
5665 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005666 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005667 if (instrsize(instr->i_oparg) != isize) {
5668 extended_arg_recompile = 1;
5669 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 }
5672 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 /* XXX: This is an awful hack that could hurt performance, but
5675 on the bright side it should work until we come up
5676 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 The issue is that in the first loop blocksize() is called
5679 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005680 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 So we loop until we stop seeing new EXTENDED_ARGs.
5684 The only EXTENDED_ARGs that could be popping up are
5685 ones in jump instructions. So this should converge
5686 fairly quickly.
5687 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005688 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005689}
5690
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005691static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005692dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005695 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 tuple = PyTuple_New(size);
5698 if (tuple == NULL)
5699 return NULL;
5700 while (PyDict_Next(dict, &pos, &k, &v)) {
5701 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005702 Py_INCREF(k);
5703 assert((i - offset) < size);
5704 assert((i - offset) >= 0);
5705 PyTuple_SET_ITEM(tuple, i - offset, k);
5706 }
5707 return tuple;
5708}
5709
5710static PyObject *
5711consts_dict_keys_inorder(PyObject *dict)
5712{
5713 PyObject *consts, *k, *v;
5714 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5715
5716 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5717 if (consts == NULL)
5718 return NULL;
5719 while (PyDict_Next(dict, &pos, &k, &v)) {
5720 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005721 /* The keys of the dictionary can be tuples wrapping a contant.
5722 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5723 * the object we want is always second. */
5724 if (PyTuple_CheckExact(k)) {
5725 k = PyTuple_GET_ITEM(k, 1);
5726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005728 assert(i < size);
5729 assert(i >= 0);
5730 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005732 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005733}
5734
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005735static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005736compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005739 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005741 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 if (ste->ste_nested)
5743 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005744 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005746 if (!ste->ste_generator && ste->ste_coroutine)
5747 flags |= CO_COROUTINE;
5748 if (ste->ste_generator && ste->ste_coroutine)
5749 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 if (ste->ste_varargs)
5751 flags |= CO_VARARGS;
5752 if (ste->ste_varkeywords)
5753 flags |= CO_VARKEYWORDS;
5754 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 /* (Only) inherit compilerflags in PyCF_MASK */
5757 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005758
Pablo Galindo90235812020-03-15 04:29:22 +00005759 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005760 ste->ste_coroutine &&
5761 !ste->ste_generator) {
5762 flags |= CO_COROUTINE;
5763 }
5764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005766}
5767
INADA Naokic2e16072018-11-26 21:23:22 +09005768// Merge *tuple* with constant cache.
5769// Unlike merge_consts_recursive(), this function doesn't work recursively.
5770static int
5771merge_const_tuple(struct compiler *c, PyObject **tuple)
5772{
5773 assert(PyTuple_CheckExact(*tuple));
5774
5775 PyObject *key = _PyCode_ConstantKey(*tuple);
5776 if (key == NULL) {
5777 return 0;
5778 }
5779
5780 // t is borrowed reference
5781 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5782 Py_DECREF(key);
5783 if (t == NULL) {
5784 return 0;
5785 }
5786 if (t == key) { // tuple is new constant.
5787 return 1;
5788 }
5789
5790 PyObject *u = PyTuple_GET_ITEM(t, 1);
5791 Py_INCREF(u);
5792 Py_DECREF(*tuple);
5793 *tuple = u;
5794 return 1;
5795}
5796
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005797static PyCodeObject *
5798makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 PyObject *tmp;
5801 PyCodeObject *co = NULL;
5802 PyObject *consts = NULL;
5803 PyObject *names = NULL;
5804 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 PyObject *name = NULL;
5806 PyObject *freevars = NULL;
5807 PyObject *cellvars = NULL;
5808 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005809 Py_ssize_t nlocals;
5810 int nlocals_int;
5811 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005812 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005813
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005814 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 names = dict_keys_inorder(c->u->u_names, 0);
5816 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5817 if (!consts || !names || !varnames)
5818 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5821 if (!cellvars)
5822 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005823 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 if (!freevars)
5825 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005826
INADA Naokic2e16072018-11-26 21:23:22 +09005827 if (!merge_const_tuple(c, &names) ||
5828 !merge_const_tuple(c, &varnames) ||
5829 !merge_const_tuple(c, &cellvars) ||
5830 !merge_const_tuple(c, &freevars))
5831 {
5832 goto error;
5833 }
5834
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005835 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005836 assert(nlocals < INT_MAX);
5837 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 flags = compute_code_flags(c);
5840 if (flags < 0)
5841 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5844 if (!bytecode)
5845 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5848 if (!tmp)
5849 goto error;
5850 Py_DECREF(consts);
5851 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005852 if (!merge_const_tuple(c, &consts)) {
5853 goto error;
5854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005856 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005857 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005858 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005859 maxdepth = stackdepth(c);
5860 if (maxdepth < 0) {
5861 goto error;
5862 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005863 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005864 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005865 maxdepth, flags, bytecode, consts, names,
5866 varnames, freevars, cellvars, c->c_filename,
5867 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005868 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005869 Py_XDECREF(consts);
5870 Py_XDECREF(names);
5871 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 Py_XDECREF(name);
5873 Py_XDECREF(freevars);
5874 Py_XDECREF(cellvars);
5875 Py_XDECREF(bytecode);
5876 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005877}
5878
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005879
5880/* For debugging purposes only */
5881#if 0
5882static void
5883dump_instr(const struct instr *i)
5884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 const char *jrel = i->i_jrel ? "jrel " : "";
5886 const char *jabs = i->i_jabs ? "jabs " : "";
5887 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005890 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5894 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005895}
5896
5897static void
5898dump_basicblock(const basicblock *b)
5899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 const char *seen = b->b_seen ? "seen " : "";
5901 const char *b_return = b->b_return ? "return " : "";
5902 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5903 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5904 if (b->b_instr) {
5905 int i;
5906 for (i = 0; i < b->b_iused; i++) {
5907 fprintf(stderr, " [%02d] ", i);
5908 dump_instr(b->b_instr + i);
5909 }
5910 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005911}
5912#endif
5913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005914static PyCodeObject *
5915assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 basicblock *b, *entryblock;
5918 struct assembler a;
5919 int i, j, nblocks;
5920 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 /* Make sure every block that falls off the end returns None.
5923 XXX NEXT_BLOCK() isn't quite right, because if the last
5924 block ends with a jump or return b_next shouldn't set.
5925 */
5926 if (!c->u->u_curblock->b_return) {
5927 NEXT_BLOCK(c);
5928 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005929 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 ADDOP(c, RETURN_VALUE);
5931 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 nblocks = 0;
5934 entryblock = NULL;
5935 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5936 nblocks++;
5937 entryblock = b;
5938 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 /* Set firstlineno if it wasn't explicitly set. */
5941 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005942 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5944 else
5945 c->u->u_firstlineno = 1;
5946 }
5947 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5948 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07005949 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 /* Can't modify the bytecode after computing jump offsets. */
5952 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005953
T. Wouters99b54d62019-09-12 07:05:33 -07005954 /* Emit code in reverse postorder from dfs. */
5955 for (i = a.a_nblocks - 1; i >= 0; i--) {
5956 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 for (j = 0; j < b->b_iused; j++)
5958 if (!assemble_emit(&a, &b->b_instr[j]))
5959 goto error;
5960 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5963 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005964 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005968 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 assemble_free(&a);
5970 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005971}
Georg Brandl8334fd92010-12-04 10:26:46 +00005972
5973#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005974PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005975PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5976 PyArena *arena)
5977{
5978 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5979}