blob: 8fe82f91559e09fb703c522ddd34f46c006f274d [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Thomas Wouters89f507f2006-12-13 04:49:30 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Ammar Askare92d3932020-01-15 11:48:40 -050026#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000029#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000030#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030031#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000033#define DEFAULT_BLOCK_SIZE 16
34#define DEFAULT_BLOCKS 8
35#define DEFAULT_CODE_SIZE 128
36#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000037
Nick Coghlan650f0d02007-04-15 12:05:43 +000038#define COMP_GENEXP 0
39#define COMP_LISTCOMP 1
40#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000041#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000042
Pablo Galindo90235812020-03-15 04:29:22 +000043#define IS_TOP_LEVEL_AWAIT(c) ( \
44 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
45 && (c->u->u_ste->ste_type == ModuleBlock))
46
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000047struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 unsigned i_jabs : 1;
49 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 /* Each basicblock in a compilation unit is linked via b_list in the
58 reverse order that the block are allocated. b_list points to the next
59 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 struct basicblock_ *b_list;
61 /* number of instructions used */
62 int b_iused;
63 /* length of instruction array (b_instr) */
64 int b_ialloc;
65 /* pointer to an array of instructions, initially NULL */
66 struct instr *b_instr;
67 /* If b_next is non-NULL, it is a pointer to the next
68 block reached by normal control flow. */
69 struct basicblock_ *b_next;
70 /* b_seen is used to perform a DFS of basicblocks. */
71 unsigned b_seen : 1;
72 /* b_return is true if a RETURN_VALUE opcode is inserted. */
73 unsigned b_return : 1;
74 /* depth of stack upon entry of block, computed by stackdepth() */
75 int b_startdepth;
76 /* instruction offset for block, computed by assemble_jump_offsets() */
77 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078} basicblock;
79
80/* fblockinfo tracks the current frame block.
81
Jeremy Hyltone9357b22006-03-01 15:47:05 +000082A frame block is used to handle loops, try/except, and try/finally.
83It's called a frame block to distinguish it from a basic block in the
84compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085*/
86
Mark Shannonfee55262019-11-21 09:11:43 +000087enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
88 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089
90struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 enum fblocktype fb_type;
92 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020093 /* (optional) type-specific exit or cleanup block */
94 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +000095 /* (optional) additional information required for unwinding */
96 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000097};
98
Antoine Pitrou86a36b52011-11-25 18:56:07 +010099enum {
100 COMPILER_SCOPE_MODULE,
101 COMPILER_SCOPE_CLASS,
102 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400103 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400104 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100105 COMPILER_SCOPE_COMPREHENSION,
106};
107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108/* The following items change on entry and exit of code blocks.
109 They must be saved and restored when returning to a block.
110*/
111struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400115 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100116 int u_scope_type;
117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 /* The following fields are dicts that map objects to
119 the index of them in co_XXX. The index is used as
120 the argument for opcodes that refer to those collections.
121 */
122 PyObject *u_consts; /* all constants */
123 PyObject *u_names; /* all names */
124 PyObject *u_varnames; /* local variables */
125 PyObject *u_cellvars; /* cell variables */
126 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129
Victor Stinnerf8e32212013-11-19 23:56:34 +0100130 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100131 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100132 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 /* Pointer to the most recently allocated block. By following b_list
134 members, you can reach all early allocated blocks. */
135 basicblock *u_blocks;
136 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_nfblocks;
139 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 int u_firstlineno; /* the first lineno of the block */
142 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000143 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144};
145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000148The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000150managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000151
152Note that we don't track recursion levels during compilation - the
153task of detecting and rejecting excessive levels of nesting is
154handled by the symbol analysis pass.
155
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156*/
157
158struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200159 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 struct symtable *c_st;
161 PyFutureFeatures *c_future; /* pointer to module's __future__ */
162 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163
Georg Brandl8334fd92010-12-04 10:26:46 +0000164 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 int c_interactive; /* true if in interactive mode */
166 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100167 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
168 if this value is different from zero.
169 This can be used to temporarily visit
170 nodes without emitting bytecode to
171 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172
INADA Naokic2e16072018-11-26 21:23:22 +0900173 PyObject *c_const_cache; /* Python dict holding all constants,
174 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 struct compiler_unit *u; /* compiler state for current block */
176 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
177 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178};
179
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100180static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000181static void compiler_free(struct compiler *);
182static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500183static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000184static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100185static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200188static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
190
191static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
192static int compiler_visit_stmt(struct compiler *, stmt_ty);
193static int compiler_visit_keyword(struct compiler *, keyword_ty);
194static int compiler_visit_expr(struct compiler *, expr_ty);
195static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700196static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200197static int compiler_subscript(struct compiler *, expr_ty);
198static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199
Andy Lester76d58772020-03-10 21:18:12 -0500200static int inplace_binop(operator_ty);
Brandt Bucher6dd9b642019-11-25 22:16:53 -0800201static int are_all_items_const(asdl_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200202static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500204static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400205static int compiler_async_with(struct compiler *, stmt_ty, int);
206static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100207static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400209 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500210static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400211static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000212
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700213static int compiler_sync_comprehension_generator(
214 struct compiler *c,
215 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200216 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700217 expr_ty elt, expr_ty val, int type);
218
219static int compiler_async_comprehension_generator(
220 struct compiler *c,
221 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200222 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700223 expr_ty elt, expr_ty val, int type);
224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000226static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400228#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000231_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* Name mangling: __private becomes _classname__private.
234 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200235 PyObject *result;
236 size_t nlen, plen, ipriv;
237 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200239 PyUnicode_READ_CHAR(ident, 0) != '_' ||
240 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_INCREF(ident);
242 return ident;
243 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200244 nlen = PyUnicode_GET_LENGTH(ident);
245 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 The only time a name with a dot can occur is when
249 we are compiling an import statement that has a
250 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 TODO(jhylton): Decide whether we want to support
253 mangling of the module name, e.g. __M.X.
254 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200255 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
256 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
257 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 Py_INCREF(ident);
259 return ident; /* Don't mangle __whatever__ */
260 }
261 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200262 ipriv = 0;
263 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
264 ipriv++;
265 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 Py_INCREF(ident);
267 return ident; /* Don't mangle if class is just underscores */
268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200269 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000270
Antoine Pitrou55bff892013-04-06 21:21:04 +0200271 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
272 PyErr_SetString(PyExc_OverflowError,
273 "private identifier too large to be mangled");
274 return NULL;
275 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200277 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
278 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
279 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
280
281 result = PyUnicode_New(1 + nlen + plen, maxchar);
282 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
285 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200286 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
287 Py_DECREF(result);
288 return NULL;
289 }
290 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
291 Py_DECREF(result);
292 return NULL;
293 }
Victor Stinner8f825062012-04-27 13:55:39 +0200294 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200295 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000296}
297
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298static int
299compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000302
INADA Naokic2e16072018-11-26 21:23:22 +0900303 c->c_const_cache = PyDict_New();
304 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900306 }
307
308 c->c_stack = PyList_New(0);
309 if (!c->c_stack) {
310 Py_CLEAR(c->c_const_cache);
311 return 0;
312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315}
316
317PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200318PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
319 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 struct compiler c;
322 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200323 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (!__doc__) {
327 __doc__ = PyUnicode_InternFromString("__doc__");
328 if (!__doc__)
329 return NULL;
330 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000331 if (!__annotations__) {
332 __annotations__ = PyUnicode_InternFromString("__annotations__");
333 if (!__annotations__)
334 return NULL;
335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (!compiler_init(&c))
337 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200338 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 c.c_filename = filename;
340 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200341 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (c.c_future == NULL)
343 goto finally;
344 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 flags = &local_flags;
346 }
347 merged = c.c_future->ff_features | flags->cf_flags;
348 c.c_future->ff_features = merged;
349 flags->cf_flags = merged;
350 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200351 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100353 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Pablo Galindod112c602020-03-18 23:02:09 +0000355 _PyASTOptimizeState state;
356 state.optimize = c.c_optimize;
357 state.ff_features = merged;
358
359 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900360 goto finally;
361 }
362
Victor Stinner14e461d2013-08-26 22:28:21 +0200363 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (c.c_st == NULL) {
365 if (!PyErr_Occurred())
366 PyErr_SetString(PyExc_SystemError, "no symtable");
367 goto finally;
368 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371
Thomas Wouters1175c432006-02-27 22:49:54 +0000372 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 compiler_free(&c);
374 assert(co || PyErr_Occurred());
375 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376}
377
378PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200379PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
380 int optimize, PyArena *arena)
381{
382 PyObject *filename;
383 PyCodeObject *co;
384 filename = PyUnicode_DecodeFSDefault(filename_str);
385 if (filename == NULL)
386 return NULL;
387 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
388 Py_DECREF(filename);
389 return co;
390
391}
392
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (c->c_st)
397 PySymtable_Free(c->c_st);
398 if (c->c_future)
399 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200400 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900401 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000403}
404
Guido van Rossum79f25d91997-04-29 20:08:16 +0000405static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_ssize_t i, n;
409 PyObject *v, *k;
410 PyObject *dict = PyDict_New();
411 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 n = PyList_Size(list);
414 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100415 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (!v) {
417 Py_DECREF(dict);
418 return NULL;
419 }
420 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300421 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 Py_DECREF(v);
423 Py_DECREF(dict);
424 return NULL;
425 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 Py_DECREF(v);
427 }
428 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429}
430
431/* Return new dict containing names from src that match scope(s).
432
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435values are integers, starting at offset and increasing by one for
436each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437*/
438
439static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100440dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700442 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500444 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(offset >= 0);
447 if (dest == NULL)
448 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Meador Inge2ca63152012-07-18 14:20:11 -0500450 /* Sort the keys so that we have a deterministic order on the indexes
451 saved in the returned dictionary. These indexes are used as indexes
452 into the free and cell var storage. Therefore if they aren't
453 deterministic, then the generated bytecode is not deterministic.
454 */
455 sorted_keys = PyDict_Keys(src);
456 if (sorted_keys == NULL)
457 return NULL;
458 if (PyList_Sort(sorted_keys) != 0) {
459 Py_DECREF(sorted_keys);
460 return NULL;
461 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500462 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500463
464 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* XXX this should probably be a macro in symtable.h */
466 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500467 k = PyList_GET_ITEM(sorted_keys, key_i);
468 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 assert(PyLong_Check(v));
470 vi = PyLong_AS_LONG(v);
471 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300474 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500476 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_DECREF(dest);
478 return NULL;
479 }
480 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300481 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500482 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_DECREF(item);
484 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
486 }
487 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
489 }
Meador Inge2ca63152012-07-18 14:20:11 -0500490 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000492}
493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494static void
495compiler_unit_check(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *block;
498 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700499 assert((uintptr_t)block != 0xcbcbcbcbU);
500 assert((uintptr_t)block != 0xfbfbfbfbU);
501 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (block->b_instr != NULL) {
503 assert(block->b_ialloc > 0);
504 assert(block->b_iused > 0);
505 assert(block->b_ialloc >= block->b_iused);
506 }
507 else {
508 assert (block->b_iused == 0);
509 assert (block->b_ialloc == 0);
510 }
511 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000512}
513
514static void
515compiler_unit_free(struct compiler_unit *u)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 compiler_unit_check(u);
520 b = u->u_blocks;
521 while (b != NULL) {
522 if (b->b_instr)
523 PyObject_Free((void *)b->b_instr);
524 next = b->b_list;
525 PyObject_Free((void *)b);
526 b = next;
527 }
528 Py_CLEAR(u->u_ste);
529 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400530 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 Py_CLEAR(u->u_consts);
532 Py_CLEAR(u->u_names);
533 Py_CLEAR(u->u_varnames);
534 Py_CLEAR(u->u_freevars);
535 Py_CLEAR(u->u_cellvars);
536 Py_CLEAR(u->u_private);
537 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538}
539
540static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100541compiler_enter_scope(struct compiler *c, identifier name,
542 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100545 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546
Andy Lester7668a8b2020-03-24 23:26:44 -0500547 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 struct compiler_unit));
549 if (!u) {
550 PyErr_NoMemory();
551 return 0;
552 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100553 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100555 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 u->u_kwonlyargcount = 0;
557 u->u_ste = PySymtable_Lookup(c->c_st, key);
558 if (!u->u_ste) {
559 compiler_unit_free(u);
560 return 0;
561 }
562 Py_INCREF(name);
563 u->u_name = name;
564 u->u_varnames = list2dict(u->u_ste->ste_varnames);
565 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
566 if (!u->u_varnames || !u->u_cellvars) {
567 compiler_unit_free(u);
568 return 0;
569 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500570 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000571 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500572 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300573 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 int res;
575 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200576 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500577 name = _PyUnicode_FromId(&PyId___class__);
578 if (!name) {
579 compiler_unit_free(u);
580 return 0;
581 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300582 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500583 if (res < 0) {
584 compiler_unit_free(u);
585 return 0;
586 }
587 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200590 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (!u->u_freevars) {
592 compiler_unit_free(u);
593 return 0;
594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 u->u_blocks = NULL;
597 u->u_nfblocks = 0;
598 u->u_firstlineno = lineno;
599 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000600 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 u->u_consts = PyDict_New();
602 if (!u->u_consts) {
603 compiler_unit_free(u);
604 return 0;
605 }
606 u->u_names = PyDict_New();
607 if (!u->u_names) {
608 compiler_unit_free(u);
609 return 0;
610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Push the old compiler_unit on the stack. */
615 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400616 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
618 Py_XDECREF(capsule);
619 compiler_unit_free(u);
620 return 0;
621 }
622 Py_DECREF(capsule);
623 u->u_private = c->u->u_private;
624 Py_XINCREF(u->u_private);
625 }
626 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100629
630 block = compiler_new_block(c);
631 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100633 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400635 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
636 if (!compiler_set_qualname(c))
637 return 0;
638 }
639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641}
642
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000643static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644compiler_exit_scope(struct compiler *c)
645{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100646 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 c->c_nestlevel--;
650 compiler_unit_free(c->u);
651 /* Restore c->u to the parent unit. */
652 n = PyList_GET_SIZE(c->c_stack) - 1;
653 if (n >= 0) {
654 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400655 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 assert(c->u);
657 /* we are deleting from a list so this really shouldn't fail */
658 if (PySequence_DelItem(c->c_stack, n) < 0)
659 Py_FatalError("compiler_exit_scope()");
660 compiler_unit_check(c->u);
661 }
662 else
663 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665}
666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667static int
668compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100670 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 _Py_static_string(dot_locals, ".<locals>");
672 Py_ssize_t stack_size;
673 struct compiler_unit *u = c->u;
674 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400678 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 if (stack_size > 1) {
680 int scope, force_global = 0;
681 struct compiler_unit *parent;
682 PyObject *mangled, *capsule;
683
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400684 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400685 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 assert(parent);
687
Yury Selivanov75445082015-05-11 22:57:16 -0400688 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
690 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 assert(u->u_name);
692 mangled = _Py_Mangle(parent->u_private, u->u_name);
693 if (!mangled)
694 return 0;
695 scope = PyST_GetScope(parent->u_ste, mangled);
696 Py_DECREF(mangled);
697 assert(scope != GLOBAL_IMPLICIT);
698 if (scope == GLOBAL_EXPLICIT)
699 force_global = 1;
700 }
701
702 if (!force_global) {
703 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400704 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
706 dot_locals_str = _PyUnicode_FromId(&dot_locals);
707 if (dot_locals_str == NULL)
708 return 0;
709 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
710 if (base == NULL)
711 return 0;
712 }
713 else {
714 Py_INCREF(parent->u_qualname);
715 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400716 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100717 }
718 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400719
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 if (base != NULL) {
721 dot_str = _PyUnicode_FromId(&dot);
722 if (dot_str == NULL) {
723 Py_DECREF(base);
724 return 0;
725 }
726 name = PyUnicode_Concat(base, dot_str);
727 Py_DECREF(base);
728 if (name == NULL)
729 return 0;
730 PyUnicode_Append(&name, u->u_name);
731 if (name == NULL)
732 return 0;
733 }
734 else {
735 Py_INCREF(u->u_name);
736 name = u->u_name;
737 }
738 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400740 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741}
742
Eric V. Smith235a6f02015-09-19 14:51:32 -0400743
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744/* Allocate a new block and return a pointer to it.
745 Returns NULL on error.
746*/
747
748static basicblock *
749compiler_new_block(struct compiler *c)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 basicblock *b;
752 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500755 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (b == NULL) {
757 PyErr_NoMemory();
758 return NULL;
759 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* Extend the singly linked list of blocks with new block. */
761 b->b_list = u->u_blocks;
762 u->u_blocks = b;
763 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000764}
765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767compiler_next_block(struct compiler *c)
768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 basicblock *block = compiler_new_block(c);
770 if (block == NULL)
771 return NULL;
772 c->u->u_curblock->b_next = block;
773 c->u->u_curblock = block;
774 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000775}
776
777static basicblock *
778compiler_use_next_block(struct compiler *c, basicblock *block)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 assert(block != NULL);
781 c->u->u_curblock->b_next = block;
782 c->u->u_curblock = block;
783 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784}
785
786/* Returns the offset of the next instruction in the current block's
787 b_instr array. Resizes the b_instr as necessary.
788 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000789*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790
791static int
Andy Lester76d58772020-03-10 21:18:12 -0500792compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 assert(b != NULL);
795 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500796 b->b_instr = (struct instr *)PyObject_Calloc(
797 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (b->b_instr == NULL) {
799 PyErr_NoMemory();
800 return -1;
801 }
802 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 }
804 else if (b->b_iused == b->b_ialloc) {
805 struct instr *tmp;
806 size_t oldsize, newsize;
807 oldsize = b->b_ialloc * sizeof(struct instr);
808 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000809
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700810 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyErr_NoMemory();
812 return -1;
813 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (newsize == 0) {
816 PyErr_NoMemory();
817 return -1;
818 }
819 b->b_ialloc <<= 1;
820 tmp = (struct instr *)PyObject_Realloc(
821 (void *)b->b_instr, newsize);
822 if (tmp == NULL) {
823 PyErr_NoMemory();
824 return -1;
825 }
826 b->b_instr = tmp;
827 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
828 }
829 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830}
831
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200832/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000833
Christian Heimes2202f872008-02-06 14:31:34 +0000834 The line number is reset in the following cases:
835 - when entering a new scope
836 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200837 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200838 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000840
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200841#define SET_LOC(c, x) \
842 (c)->u->u_lineno = (x)->lineno; \
843 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200845/* Return the stack effect of opcode with argument oparg.
846
847 Some opcodes have different stack effect when jump to the target and
848 when not jump. The 'jump' parameter specifies the case:
849
850 * 0 -- when not jump
851 * 1 -- when jump
852 * -1 -- maximal
853 */
854/* XXX Make the stack effect of WITH_CLEANUP_START and
855 WITH_CLEANUP_FINISH deterministic. */
856static int
857stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300860 case NOP:
861 case EXTENDED_ARG:
862 return 0;
863
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200864 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 case POP_TOP:
866 return -1;
867 case ROT_TWO:
868 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200869 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return 0;
871 case DUP_TOP:
872 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000873 case DUP_TOP_TWO:
874 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200876 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case UNARY_POSITIVE:
878 case UNARY_NEGATIVE:
879 case UNARY_NOT:
880 case UNARY_INVERT:
881 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 case SET_ADD:
884 case LIST_APPEND:
885 return -1;
886 case MAP_ADD:
887 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000888
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200889 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 case BINARY_POWER:
891 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400892 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 case BINARY_MODULO:
894 case BINARY_ADD:
895 case BINARY_SUBTRACT:
896 case BINARY_SUBSCR:
897 case BINARY_FLOOR_DIVIDE:
898 case BINARY_TRUE_DIVIDE:
899 return -1;
900 case INPLACE_FLOOR_DIVIDE:
901 case INPLACE_TRUE_DIVIDE:
902 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 case INPLACE_ADD:
905 case INPLACE_SUBTRACT:
906 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400907 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 case INPLACE_MODULO:
909 return -1;
910 case STORE_SUBSCR:
911 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case DELETE_SUBSCR:
913 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case BINARY_LSHIFT:
916 case BINARY_RSHIFT:
917 case BINARY_AND:
918 case BINARY_XOR:
919 case BINARY_OR:
920 return -1;
921 case INPLACE_POWER:
922 return -1;
923 case GET_ITER:
924 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case PRINT_EXPR:
927 return -1;
928 case LOAD_BUILD_CLASS:
929 return 1;
930 case INPLACE_LSHIFT:
931 case INPLACE_RSHIFT:
932 case INPLACE_AND:
933 case INPLACE_XOR:
934 case INPLACE_OR:
935 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200938 /* 1 in the normal flow.
939 * Restore the stack position and push 6 values before jumping to
940 * the handler if an exception be raised. */
941 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case RETURN_VALUE:
943 return -1;
944 case IMPORT_STAR:
945 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700946 case SETUP_ANNOTATIONS:
947 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 case YIELD_VALUE:
949 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500950 case YIELD_FROM:
951 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case POP_BLOCK:
953 return 0;
954 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200955 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case STORE_NAME:
958 return -1;
959 case DELETE_NAME:
960 return 0;
961 case UNPACK_SEQUENCE:
962 return oparg-1;
963 case UNPACK_EX:
964 return (oparg&0xFF) + (oparg>>8);
965 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200966 /* -1 at end of iterator, 1 if continue iterating. */
967 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case STORE_ATTR:
970 return -2;
971 case DELETE_ATTR:
972 return -1;
973 case STORE_GLOBAL:
974 return -1;
975 case DELETE_GLOBAL:
976 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case LOAD_CONST:
978 return 1;
979 case LOAD_NAME:
980 return 1;
981 case BUILD_TUPLE:
982 case BUILD_LIST:
983 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300984 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return 1-oparg;
986 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700987 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300988 case BUILD_CONST_KEY_MAP:
989 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 case LOAD_ATTR:
991 return 0;
992 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +0000993 case IS_OP:
994 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +0000996 case JUMP_IF_NOT_EXC_MATCH:
997 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case IMPORT_NAME:
999 return -1;
1000 case IMPORT_FROM:
1001 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001002
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001003 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case JUMP_ABSOLUTE:
1006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001008 case JUMP_IF_TRUE_OR_POP:
1009 case JUMP_IF_FALSE_OR_POP:
1010 return jump ? 0 : -1;
1011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 case POP_JUMP_IF_FALSE:
1013 case POP_JUMP_IF_TRUE:
1014 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case LOAD_GLOBAL:
1017 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001018
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001019 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001021 /* 0 in the normal flow.
1022 * Restore the stack position and push 6 values before jumping to
1023 * the handler if an exception be raised. */
1024 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001025 case RERAISE:
1026 return -3;
1027
1028 case WITH_EXCEPT_START:
1029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case LOAD_FAST:
1032 return 1;
1033 case STORE_FAST:
1034 return -1;
1035 case DELETE_FAST:
1036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case RAISE_VARARGS:
1039 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001040
1041 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001043 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001044 case CALL_METHOD:
1045 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001047 return -oparg-1;
1048 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001049 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001050 case MAKE_FUNCTION:
1051 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1052 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 case BUILD_SLICE:
1054 if (oparg == 3)
1055 return -2;
1056 else
1057 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_CLOSURE:
1061 return 1;
1062 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001063 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 return 1;
1065 case STORE_DEREF:
1066 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001067 case DELETE_DEREF:
1068 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001069
1070 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001071 case GET_AWAITABLE:
1072 return 0;
1073 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001074 /* 0 in the normal flow.
1075 * Restore the stack position to the position before the result
1076 * of __aenter__ and push 6 values before jumping to the handler
1077 * if an exception be raised. */
1078 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001079 case BEFORE_ASYNC_WITH:
1080 return 1;
1081 case GET_AITER:
1082 return 0;
1083 case GET_ANEXT:
1084 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001085 case GET_YIELD_FROM_ITER:
1086 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001087 case END_ASYNC_FOR:
1088 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001089 case FORMAT_VALUE:
1090 /* If there's a fmt_spec on the stack, we go from 2->1,
1091 else 1->1. */
1092 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001093 case LOAD_METHOD:
1094 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001095 case LOAD_ASSERTION_ERROR:
1096 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001097 case LIST_TO_TUPLE:
1098 return 0;
1099 case LIST_EXTEND:
1100 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001101 case DICT_MERGE:
1102 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001103 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001105 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
Larry Hastings3a907972013-11-23 14:49:22 -08001107 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108}
1109
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001110int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001111PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1112{
1113 return stack_effect(opcode, oparg, jump);
1114}
1115
1116int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001117PyCompile_OpcodeStackEffect(int opcode, int oparg)
1118{
1119 return stack_effect(opcode, oparg, -1);
1120}
1121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122/* Add an opcode with no argument.
1123 Returns 0 on failure, 1 on success.
1124*/
1125
1126static int
1127compiler_addop(struct compiler *c, int opcode)
1128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 basicblock *b;
1130 struct instr *i;
1131 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001132 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001133 if (c->c_do_not_emit_bytecode) {
1134 return 1;
1135 }
Andy Lester76d58772020-03-10 21:18:12 -05001136 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (off < 0)
1138 return 0;
1139 b = c->u->u_curblock;
1140 i = &b->b_instr[off];
1141 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001142 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (opcode == RETURN_VALUE)
1144 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001145 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
Victor Stinnerf8e32212013-11-19 23:56:34 +01001149static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001150compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001152 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001155 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001157 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001159 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001160 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001161 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return -1;
1164 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001165 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 Py_DECREF(v);
1167 return -1;
1168 }
1169 Py_DECREF(v);
1170 }
1171 else
1172 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001173 return arg;
1174}
1175
INADA Naokic2e16072018-11-26 21:23:22 +09001176// Merge const *o* recursively and return constant key object.
1177static PyObject*
1178merge_consts_recursive(struct compiler *c, PyObject *o)
1179{
1180 // None and Ellipsis are singleton, and key is the singleton.
1181 // No need to merge object and key.
1182 if (o == Py_None || o == Py_Ellipsis) {
1183 Py_INCREF(o);
1184 return o;
1185 }
1186
1187 PyObject *key = _PyCode_ConstantKey(o);
1188 if (key == NULL) {
1189 return NULL;
1190 }
1191
1192 // t is borrowed reference
1193 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1194 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001195 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001196 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001197 Py_DECREF(key);
1198 return t;
1199 }
1200
INADA Naokif7e4d362018-11-29 00:58:46 +09001201 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001202 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001203 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001204 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001205 Py_ssize_t len = PyTuple_GET_SIZE(o);
1206 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001207 PyObject *item = PyTuple_GET_ITEM(o, i);
1208 PyObject *u = merge_consts_recursive(c, item);
1209 if (u == NULL) {
1210 Py_DECREF(key);
1211 return NULL;
1212 }
1213
1214 // See _PyCode_ConstantKey()
1215 PyObject *v; // borrowed
1216 if (PyTuple_CheckExact(u)) {
1217 v = PyTuple_GET_ITEM(u, 1);
1218 }
1219 else {
1220 v = u;
1221 }
1222 if (v != item) {
1223 Py_INCREF(v);
1224 PyTuple_SET_ITEM(o, i, v);
1225 Py_DECREF(item);
1226 }
1227
1228 Py_DECREF(u);
1229 }
1230 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001231 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001232 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001233 // constant keys.
1234 // See _PyCode_ConstantKey() for detail.
1235 assert(PyTuple_CheckExact(key));
1236 assert(PyTuple_GET_SIZE(key) == 2);
1237
1238 Py_ssize_t len = PySet_GET_SIZE(o);
1239 if (len == 0) { // empty frozenset should not be re-created.
1240 return key;
1241 }
1242 PyObject *tuple = PyTuple_New(len);
1243 if (tuple == NULL) {
1244 Py_DECREF(key);
1245 return NULL;
1246 }
1247 Py_ssize_t i = 0, pos = 0;
1248 PyObject *item;
1249 Py_hash_t hash;
1250 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1251 PyObject *k = merge_consts_recursive(c, item);
1252 if (k == NULL) {
1253 Py_DECREF(tuple);
1254 Py_DECREF(key);
1255 return NULL;
1256 }
1257 PyObject *u;
1258 if (PyTuple_CheckExact(k)) {
1259 u = PyTuple_GET_ITEM(k, 1);
1260 Py_INCREF(u);
1261 Py_DECREF(k);
1262 }
1263 else {
1264 u = k;
1265 }
1266 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1267 i++;
1268 }
1269
1270 // Instead of rewriting o, we create new frozenset and embed in the
1271 // key tuple. Caller should get merged frozenset from the key tuple.
1272 PyObject *new = PyFrozenSet_New(tuple);
1273 Py_DECREF(tuple);
1274 if (new == NULL) {
1275 Py_DECREF(key);
1276 return NULL;
1277 }
1278 assert(PyTuple_GET_ITEM(key, 1) == o);
1279 Py_DECREF(o);
1280 PyTuple_SET_ITEM(key, 1, new);
1281 }
INADA Naokic2e16072018-11-26 21:23:22 +09001282
1283 return key;
1284}
1285
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001286static Py_ssize_t
1287compiler_add_const(struct compiler *c, PyObject *o)
1288{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001289 if (c->c_do_not_emit_bytecode) {
1290 return 0;
1291 }
1292
INADA Naokic2e16072018-11-26 21:23:22 +09001293 PyObject *key = merge_consts_recursive(c, o);
1294 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001295 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001296 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001297
Andy Lester76d58772020-03-10 21:18:12 -05001298 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001299 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301}
1302
1303static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001304compiler_addop_load_const(struct compiler *c, PyObject *o)
1305{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001306 if (c->c_do_not_emit_bytecode) {
1307 return 1;
1308 }
1309
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310 Py_ssize_t arg = compiler_add_const(c, o);
1311 if (arg < 0)
1312 return 0;
1313 return compiler_addop_i(c, LOAD_CONST, arg);
1314}
1315
1316static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001320 if (c->c_do_not_emit_bytecode) {
1321 return 1;
1322 }
1323
Andy Lester76d58772020-03-10 21:18:12 -05001324 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001326 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327 return compiler_addop_i(c, opcode, arg);
1328}
1329
1330static int
1331compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001334 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001335
1336 if (c->c_do_not_emit_bytecode) {
1337 return 1;
1338 }
1339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1341 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001342 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001343 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 Py_DECREF(mangled);
1345 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return compiler_addop_i(c, opcode, arg);
1348}
1349
1350/* Add an opcode with an integer argument.
1351 Returns 0 on failure, 1 on success.
1352*/
1353
1354static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001355compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 struct instr *i;
1358 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001359
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001360 if (c->c_do_not_emit_bytecode) {
1361 return 1;
1362 }
1363
Victor Stinner2ad474b2016-03-01 23:34:47 +01001364 /* oparg value is unsigned, but a signed C int is usually used to store
1365 it in the C code (like Python/ceval.c).
1366
1367 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1368
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001369 The argument of a concrete bytecode instruction is limited to 8-bit.
1370 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1371 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001372 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001373
Andy Lester76d58772020-03-10 21:18:12 -05001374 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (off < 0)
1376 return 0;
1377 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001378 i->i_opcode = opcode;
1379 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001380 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382}
1383
1384static int
1385compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 struct instr *i;
1388 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001390 if (c->c_do_not_emit_bytecode) {
1391 return 1;
1392 }
1393
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001394 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001396 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 if (off < 0)
1398 return 0;
1399 i = &c->u->u_curblock->b_instr[off];
1400 i->i_opcode = opcode;
1401 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (absolute)
1403 i->i_jabs = 1;
1404 else
1405 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001406 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408}
1409
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001410/* NEXT_BLOCK() creates an implicit jump from the current block
1411 to the new block.
1412
1413 The returns inside this macro make it impossible to decref objects
1414 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (compiler_next_block((C)) == NULL) \
1418 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001419}
1420
1421#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (!compiler_addop((C), (OP))) \
1423 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424}
1425
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001426#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (!compiler_addop((C), (OP))) { \
1428 compiler_exit_scope(c); \
1429 return 0; \
1430 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001431}
1432
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001433#define ADDOP_LOAD_CONST(C, O) { \
1434 if (!compiler_addop_load_const((C), (O))) \
1435 return 0; \
1436}
1437
1438/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1439#define ADDOP_LOAD_CONST_NEW(C, O) { \
1440 PyObject *__new_const = (O); \
1441 if (__new_const == NULL) { \
1442 return 0; \
1443 } \
1444 if (!compiler_addop_load_const((C), __new_const)) { \
1445 Py_DECREF(__new_const); \
1446 return 0; \
1447 } \
1448 Py_DECREF(__new_const); \
1449}
1450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1453 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454}
1455
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001456/* Same as ADDOP_O, but steals a reference. */
1457#define ADDOP_N(C, OP, O, TYPE) { \
1458 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1459 Py_DECREF((O)); \
1460 return 0; \
1461 } \
1462 Py_DECREF((O)); \
1463}
1464
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1467 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468}
1469
1470#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 if (!compiler_addop_i((C), (OP), (O))) \
1472 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473}
1474
1475#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (!compiler_addop_j((C), (OP), (O), 1)) \
1477 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478}
1479
1480#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_addop_j((C), (OP), (O), 0)) \
1482 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483}
1484
Mark Shannon9af0e472020-01-14 10:12:45 +00001485
1486#define ADDOP_COMPARE(C, CMP) { \
1487 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1488 return 0; \
1489}
1490
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001491/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1492 the ASDL name to synthesize the name of the C type and the visit function.
1493*/
1494
1495#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_visit_ ## TYPE((C), (V))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001500#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!compiler_visit_ ## TYPE((C), (V))) { \
1502 compiler_exit_scope(c); \
1503 return 0; \
1504 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001505}
1506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001507#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (!compiler_visit_slice((C), (V), (CTX))) \
1509 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510}
1511
1512#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 int _i; \
1514 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1515 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1516 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1517 if (!compiler_visit_ ## TYPE((C), elt)) \
1518 return 0; \
1519 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001522#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 int _i; \
1524 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1525 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1526 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1527 if (!compiler_visit_ ## TYPE((C), elt)) { \
1528 compiler_exit_scope(c); \
1529 return 0; \
1530 } \
1531 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001532}
1533
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001534/* These macros allows to check only for errors and not emmit bytecode
1535 * while visiting nodes.
1536*/
1537
1538#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1539 c->c_do_not_emit_bytecode++;
1540
1541#define END_DO_NOT_EMIT_BYTECODE \
1542 c->c_do_not_emit_bytecode--; \
1543}
1544
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001545/* Search if variable annotations are present statically in a block. */
1546
1547static int
1548find_ann(asdl_seq *stmts)
1549{
1550 int i, j, res = 0;
1551 stmt_ty st;
1552
1553 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1554 st = (stmt_ty)asdl_seq_GET(stmts, i);
1555 switch (st->kind) {
1556 case AnnAssign_kind:
1557 return 1;
1558 case For_kind:
1559 res = find_ann(st->v.For.body) ||
1560 find_ann(st->v.For.orelse);
1561 break;
1562 case AsyncFor_kind:
1563 res = find_ann(st->v.AsyncFor.body) ||
1564 find_ann(st->v.AsyncFor.orelse);
1565 break;
1566 case While_kind:
1567 res = find_ann(st->v.While.body) ||
1568 find_ann(st->v.While.orelse);
1569 break;
1570 case If_kind:
1571 res = find_ann(st->v.If.body) ||
1572 find_ann(st->v.If.orelse);
1573 break;
1574 case With_kind:
1575 res = find_ann(st->v.With.body);
1576 break;
1577 case AsyncWith_kind:
1578 res = find_ann(st->v.AsyncWith.body);
1579 break;
1580 case Try_kind:
1581 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1582 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1583 st->v.Try.handlers, j);
1584 if (find_ann(handler->v.ExceptHandler.body)) {
1585 return 1;
1586 }
1587 }
1588 res = find_ann(st->v.Try.body) ||
1589 find_ann(st->v.Try.finalbody) ||
1590 find_ann(st->v.Try.orelse);
1591 break;
1592 default:
1593 res = 0;
1594 }
1595 if (res) {
1596 break;
1597 }
1598 }
1599 return res;
1600}
1601
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001602/*
1603 * Frame block handling functions
1604 */
1605
1606static int
1607compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001608 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001609{
1610 struct fblockinfo *f;
1611 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1612 PyErr_SetString(PyExc_SyntaxError,
1613 "too many statically nested blocks");
1614 return 0;
1615 }
1616 f = &c->u->u_fblock[c->u->u_nfblocks++];
1617 f->fb_type = t;
1618 f->fb_block = b;
1619 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001620 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001621 return 1;
1622}
1623
1624static void
1625compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1626{
1627 struct compiler_unit *u = c->u;
1628 assert(u->u_nfblocks > 0);
1629 u->u_nfblocks--;
1630 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1631 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1632}
1633
Mark Shannonfee55262019-11-21 09:11:43 +00001634static int
1635compiler_call_exit_with_nones(struct compiler *c) {
1636 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1637 ADDOP(c, DUP_TOP);
1638 ADDOP(c, DUP_TOP);
1639 ADDOP_I(c, CALL_FUNCTION, 3);
1640 return 1;
1641}
1642
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001643/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001644 * popping the blocks will be restored afterwards, unless another
1645 * return, break or continue is found. In which case, the TOS will
1646 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001647 */
1648static int
1649compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1650 int preserve_tos)
1651{
1652 switch (info->fb_type) {
1653 case WHILE_LOOP:
1654 return 1;
1655
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001656 case FOR_LOOP:
1657 /* Pop the iterator */
1658 if (preserve_tos) {
1659 ADDOP(c, ROT_TWO);
1660 }
1661 ADDOP(c, POP_TOP);
1662 return 1;
1663
1664 case EXCEPT:
1665 ADDOP(c, POP_BLOCK);
1666 return 1;
1667
1668 case FINALLY_TRY:
1669 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001670 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001671 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1672 return 0;
1673 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001674 }
Mark Shannon88dce262019-12-30 09:53:36 +00001675 /* Emit the finally block, restoring the line number when done */
1676 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001677 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001678 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001679 if (preserve_tos) {
1680 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001681 }
1682 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001683
Mark Shannonfee55262019-11-21 09:11:43 +00001684 case FINALLY_END:
1685 if (preserve_tos) {
1686 ADDOP(c, ROT_FOUR);
1687 }
1688 ADDOP(c, POP_TOP);
1689 ADDOP(c, POP_TOP);
1690 ADDOP(c, POP_TOP);
1691 if (preserve_tos) {
1692 ADDOP(c, ROT_FOUR);
1693 }
1694 ADDOP(c, POP_EXCEPT);
1695 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001696
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001697 case WITH:
1698 case ASYNC_WITH:
1699 ADDOP(c, POP_BLOCK);
1700 if (preserve_tos) {
1701 ADDOP(c, ROT_TWO);
1702 }
Mark Shannonfee55262019-11-21 09:11:43 +00001703 if(!compiler_call_exit_with_nones(c)) {
1704 return 0;
1705 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001706 if (info->fb_type == ASYNC_WITH) {
1707 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001708 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001709 ADDOP(c, YIELD_FROM);
1710 }
Mark Shannonfee55262019-11-21 09:11:43 +00001711 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001712 return 1;
1713
1714 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001715 if (info->fb_datum) {
1716 ADDOP(c, POP_BLOCK);
1717 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001718 if (preserve_tos) {
1719 ADDOP(c, ROT_FOUR);
1720 }
Mark Shannonfee55262019-11-21 09:11:43 +00001721 ADDOP(c, POP_EXCEPT);
1722 if (info->fb_datum) {
1723 ADDOP_LOAD_CONST(c, Py_None);
1724 compiler_nameop(c, info->fb_datum, Store);
1725 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001726 }
Mark Shannonfee55262019-11-21 09:11:43 +00001727 return 1;
1728
1729 case POP_VALUE:
1730 if (preserve_tos) {
1731 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001732 }
Mark Shannonfee55262019-11-21 09:11:43 +00001733 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001734 return 1;
1735 }
1736 Py_UNREACHABLE();
1737}
1738
Mark Shannonfee55262019-11-21 09:11:43 +00001739/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1740static int
1741compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1742 if (c->u->u_nfblocks == 0) {
1743 return 1;
1744 }
1745 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1746 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1747 *loop = top;
1748 return 1;
1749 }
1750 struct fblockinfo copy = *top;
1751 c->u->u_nfblocks--;
1752 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1753 return 0;
1754 }
1755 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1756 return 0;
1757 }
1758 c->u->u_fblock[c->u->u_nfblocks] = copy;
1759 c->u->u_nfblocks++;
1760 return 1;
1761}
1762
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001763/* Compile a sequence of statements, checking for a docstring
1764 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765
1766static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001767compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001769 int i = 0;
1770 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001771 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001772
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001773 /* Set current line number to the line number of first statement.
1774 This way line number for SETUP_ANNOTATIONS will always
1775 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301776 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001777 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001778 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001779 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001780 }
1781 /* Every annotated class and module should have __annotations__. */
1782 if (find_ann(stmts)) {
1783 ADDOP(c, SETUP_ANNOTATIONS);
1784 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001785 if (!asdl_seq_LEN(stmts))
1786 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001787 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001788 if (c->c_optimize < 2) {
1789 docstring = _PyAST_GetDocString(stmts);
1790 if (docstring) {
1791 i = 1;
1792 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1793 assert(st->kind == Expr_kind);
1794 VISIT(c, expr, st->v.Expr.value);
1795 if (!compiler_nameop(c, __doc__, Store))
1796 return 0;
1797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001799 for (; i < asdl_seq_LEN(stmts); i++)
1800 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802}
1803
1804static PyCodeObject *
1805compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 PyCodeObject *co;
1808 int addNone = 1;
1809 static PyObject *module;
1810 if (!module) {
1811 module = PyUnicode_InternFromString("<module>");
1812 if (!module)
1813 return NULL;
1814 }
1815 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001816 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return NULL;
1818 switch (mod->kind) {
1819 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001820 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 compiler_exit_scope(c);
1822 return 0;
1823 }
1824 break;
1825 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001826 if (find_ann(mod->v.Interactive.body)) {
1827 ADDOP(c, SETUP_ANNOTATIONS);
1828 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 c->c_interactive = 1;
1830 VISIT_SEQ_IN_SCOPE(c, stmt,
1831 mod->v.Interactive.body);
1832 break;
1833 case Expression_kind:
1834 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1835 addNone = 0;
1836 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 default:
1838 PyErr_Format(PyExc_SystemError,
1839 "module kind %d should not be possible",
1840 mod->kind);
1841 return 0;
1842 }
1843 co = assemble(c, addNone);
1844 compiler_exit_scope(c);
1845 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001846}
1847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848/* The test for LOCAL must come before the test for FREE in order to
1849 handle classes where name is both local and free. The local var is
1850 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001851*/
1852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853static int
1854get_ref_type(struct compiler *c, PyObject *name)
1855{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001856 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001857 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001858 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001859 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001860 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001862 _Py_FatalErrorFormat(__func__,
1863 "unknown scope for %.100s in %.100s(%s)\n"
1864 "symbols: %s\nlocals: %s\nglobals: %s",
1865 PyUnicode_AsUTF8(name),
1866 PyUnicode_AsUTF8(c->u->u_name),
1867 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1868 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1869 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1870 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874}
1875
1876static int
1877compiler_lookup_arg(PyObject *dict, PyObject *name)
1878{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001879 PyObject *v;
1880 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001882 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001883 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884}
1885
1886static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001887compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001889 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001890 if (qualname == NULL)
1891 qualname = co->co_name;
1892
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001893 if (free) {
1894 for (i = 0; i < free; ++i) {
1895 /* Bypass com_addop_varname because it will generate
1896 LOAD_DEREF but LOAD_CLOSURE is needed.
1897 */
1898 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1899 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001900
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001901 /* Special case: If a class contains a method with a
1902 free variable that has the same name as a method,
1903 the name will be considered free *and* local in the
1904 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001905 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906 */
1907 reftype = get_ref_type(c, name);
1908 if (reftype == CELL)
1909 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1910 else /* (reftype == FREE) */
1911 arg = compiler_lookup_arg(c->u->u_freevars, name);
1912 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001913 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001914 "lookup %s in %s %d %d\n"
1915 "freevars of %s: %s\n",
1916 PyUnicode_AsUTF8(PyObject_Repr(name)),
1917 PyUnicode_AsUTF8(c->u->u_name),
1918 reftype, arg,
1919 PyUnicode_AsUTF8(co->co_name),
1920 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921 }
1922 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 flags |= 0x08;
1925 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001927 ADDOP_LOAD_CONST(c, (PyObject*)co);
1928 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001929 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931}
1932
1933static int
1934compiler_decorators(struct compiler *c, asdl_seq* decos)
1935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (!decos)
1939 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1942 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1943 }
1944 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945}
1946
1947static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001948compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001950{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001951 /* Push a dict of keyword-only default values.
1952
1953 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1954 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 int i;
1956 PyObject *keys = NULL;
1957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1959 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1960 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1961 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001962 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001963 if (!mangled) {
1964 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001966 if (keys == NULL) {
1967 keys = PyList_New(1);
1968 if (keys == NULL) {
1969 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001970 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001971 }
1972 PyList_SET_ITEM(keys, 0, mangled);
1973 }
1974 else {
1975 int res = PyList_Append(keys, mangled);
1976 Py_DECREF(mangled);
1977 if (res == -1) {
1978 goto error;
1979 }
1980 }
1981 if (!compiler_visit_expr(c, default_)) {
1982 goto error;
1983 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
1985 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 if (keys != NULL) {
1987 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1988 PyObject *keys_tuple = PyList_AsTuple(keys);
1989 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001990 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001991 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001992 assert(default_count > 0);
1993 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 }
1995 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001996 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001997 }
1998
1999error:
2000 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002001 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002002}
2003
2004static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002005compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2006{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002007 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002008 return 1;
2009}
2010
2011static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002012compiler_visit_argannotation(struct compiler *c, identifier id,
2013 expr_ty annotation, PyObject *names)
2014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002016 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002017 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2018 VISIT(c, annexpr, annotation)
2019 }
2020 else {
2021 VISIT(c, expr, annotation);
2022 }
Victor Stinner065efc32014-02-18 22:07:56 +01002023 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002024 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002025 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002026 if (PyList_Append(names, mangled) < 0) {
2027 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002028 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002029 }
2030 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002032 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002033}
2034
2035static int
2036compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2037 PyObject *names)
2038{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002039 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 for (i = 0; i < asdl_seq_LEN(args); i++) {
2041 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002042 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 c,
2044 arg->arg,
2045 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002046 names))
2047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002050}
2051
2052static int
2053compiler_visit_annotations(struct compiler *c, arguments_ty args,
2054 expr_ty returns)
2055{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002056 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002057 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002058
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002059 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 */
2061 static identifier return_str;
2062 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002063 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 names = PyList_New(0);
2065 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002066 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002067
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002068 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002070 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2071 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002072 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002074 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002076 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002078 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002080 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (!return_str) {
2084 return_str = PyUnicode_InternFromString("return");
2085 if (!return_str)
2086 goto error;
2087 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 goto error;
2090 }
2091
2092 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002094 PyObject *keytuple = PyList_AsTuple(names);
2095 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002096 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002097 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002098 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002100 else {
2101 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002102 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002103 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002104
2105error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002107 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002108}
2109
2110static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002111compiler_visit_defaults(struct compiler *c, arguments_ty args)
2112{
2113 VISIT_SEQ(c, expr, args->defaults);
2114 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2115 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116}
2117
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118static Py_ssize_t
2119compiler_default_arguments(struct compiler *c, arguments_ty args)
2120{
2121 Py_ssize_t funcflags = 0;
2122 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002123 if (!compiler_visit_defaults(c, args))
2124 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002125 funcflags |= 0x01;
2126 }
2127 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002128 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002129 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002130 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002131 return -1;
2132 }
2133 else if (res > 0) {
2134 funcflags |= 0x02;
2135 }
2136 }
2137 return funcflags;
2138}
2139
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002141forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2142{
2143
2144 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2145 compiler_error(c, "cannot assign to __debug__");
2146 return 1;
2147 }
2148 return 0;
2149}
2150
2151static int
2152compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2153{
2154 if (arg != NULL) {
2155 if (forbidden_name(c, arg->arg, Store))
2156 return 0;
2157 }
2158 return 1;
2159}
2160
2161static int
2162compiler_check_debug_args_seq(struct compiler *c, asdl_seq *args)
2163{
2164 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002165 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002166 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2167 return 0;
2168 }
2169 }
2170 return 1;
2171}
2172
2173static int
2174compiler_check_debug_args(struct compiler *c, arguments_ty args)
2175{
2176 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2177 return 0;
2178 if (!compiler_check_debug_args_seq(c, args->args))
2179 return 0;
2180 if (!compiler_check_debug_one_arg(c, args->vararg))
2181 return 0;
2182 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2183 return 0;
2184 if (!compiler_check_debug_one_arg(c, args->kwarg))
2185 return 0;
2186 return 1;
2187}
2188
2189static int
Yury Selivanov75445082015-05-11 22:57:16 -04002190compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002193 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002194 arguments_ty args;
2195 expr_ty returns;
2196 identifier name;
2197 asdl_seq* decos;
2198 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002199 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002200 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002201 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002202 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203
Yury Selivanov75445082015-05-11 22:57:16 -04002204 if (is_async) {
2205 assert(s->kind == AsyncFunctionDef_kind);
2206
2207 args = s->v.AsyncFunctionDef.args;
2208 returns = s->v.AsyncFunctionDef.returns;
2209 decos = s->v.AsyncFunctionDef.decorator_list;
2210 name = s->v.AsyncFunctionDef.name;
2211 body = s->v.AsyncFunctionDef.body;
2212
2213 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2214 } else {
2215 assert(s->kind == FunctionDef_kind);
2216
2217 args = s->v.FunctionDef.args;
2218 returns = s->v.FunctionDef.returns;
2219 decos = s->v.FunctionDef.decorator_list;
2220 name = s->v.FunctionDef.name;
2221 body = s->v.FunctionDef.body;
2222
2223 scope_type = COMPILER_SCOPE_FUNCTION;
2224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002226 if (!compiler_check_debug_args(c, args))
2227 return 0;
2228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 if (!compiler_decorators(c, decos))
2230 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002231
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002232 firstlineno = s->lineno;
2233 if (asdl_seq_LEN(decos)) {
2234 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2235 }
2236
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002237 funcflags = compiler_default_arguments(c, args);
2238 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002240 }
2241
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002242 annotations = compiler_visit_annotations(c, args, returns);
2243 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002244 return 0;
2245 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002246 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002247 funcflags |= 0x04;
2248 }
2249
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002250 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002251 return 0;
2252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
INADA Naokicb41b272017-02-23 00:31:59 +09002254 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002255 if (c->c_optimize < 2) {
2256 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002257 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002258 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 compiler_exit_scope(c);
2260 return 0;
2261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002264 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002266 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002268 qualname = c->u->u_qualname;
2269 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002271 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002272 Py_XDECREF(qualname);
2273 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002277 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002278 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 /* decorators */
2282 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2283 ADDOP_I(c, CALL_FUNCTION, 1);
2284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285
Yury Selivanov75445082015-05-11 22:57:16 -04002286 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287}
2288
2289static int
2290compiler_class(struct compiler *c, stmt_ty s)
2291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 PyCodeObject *co;
2293 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002294 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 if (!compiler_decorators(c, decos))
2298 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002299
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002300 firstlineno = s->lineno;
2301 if (asdl_seq_LEN(decos)) {
2302 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2303 }
2304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* ultimately generate code for:
2306 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2307 where:
2308 <func> is a function/closure created from the class body;
2309 it has a single argument (__locals__) where the dict
2310 (or MutableSequence) representing the locals is passed
2311 <name> is the class name
2312 <bases> is the positional arguments and *varargs argument
2313 <keywords> is the keyword arguments and **kwds argument
2314 This borrows from compiler_call.
2315 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002318 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002319 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 return 0;
2321 /* this block represents what we do in the new scope */
2322 {
2323 /* use the class name for name mangling */
2324 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002325 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* load (global) __name__ ... */
2327 str = PyUnicode_InternFromString("__name__");
2328 if (!str || !compiler_nameop(c, str, Load)) {
2329 Py_XDECREF(str);
2330 compiler_exit_scope(c);
2331 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 Py_DECREF(str);
2334 /* ... and store it as __module__ */
2335 str = PyUnicode_InternFromString("__module__");
2336 if (!str || !compiler_nameop(c, str, Store)) {
2337 Py_XDECREF(str);
2338 compiler_exit_scope(c);
2339 return 0;
2340 }
2341 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002342 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002343 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002344 str = PyUnicode_InternFromString("__qualname__");
2345 if (!str || !compiler_nameop(c, str, Store)) {
2346 Py_XDECREF(str);
2347 compiler_exit_scope(c);
2348 return 0;
2349 }
2350 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002352 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 compiler_exit_scope(c);
2354 return 0;
2355 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002357 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002358 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002359 str = PyUnicode_InternFromString("__class__");
2360 if (str == NULL) {
2361 compiler_exit_scope(c);
2362 return 0;
2363 }
2364 i = compiler_lookup_arg(c->u->u_cellvars, str);
2365 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002366 if (i < 0) {
2367 compiler_exit_scope(c);
2368 return 0;
2369 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002370 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002373 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002374 str = PyUnicode_InternFromString("__classcell__");
2375 if (!str || !compiler_nameop(c, str, Store)) {
2376 Py_XDECREF(str);
2377 compiler_exit_scope(c);
2378 return 0;
2379 }
2380 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002382 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002383 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002384 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002385 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002386 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002387 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* create the code object */
2389 co = assemble(c, 1);
2390 }
2391 /* leave the new scope */
2392 compiler_exit_scope(c);
2393 if (co == NULL)
2394 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* 2. load the 'build_class' function */
2397 ADDOP(c, LOAD_BUILD_CLASS);
2398
2399 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002400 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 Py_DECREF(co);
2402
2403 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002404 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405
2406 /* 5. generate the rest of the code for the call */
2407 if (!compiler_call_helper(c, 2,
2408 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002409 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 return 0;
2411
2412 /* 6. apply decorators */
2413 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2414 ADDOP_I(c, CALL_FUNCTION, 1);
2415 }
2416
2417 /* 7. store into <name> */
2418 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2419 return 0;
2420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421}
2422
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002423/* Return 0 if the expression is a constant value except named singletons.
2424 Return 1 otherwise. */
2425static int
2426check_is_arg(expr_ty e)
2427{
2428 if (e->kind != Constant_kind) {
2429 return 1;
2430 }
2431 PyObject *value = e->v.Constant.value;
2432 return (value == Py_None
2433 || value == Py_False
2434 || value == Py_True
2435 || value == Py_Ellipsis);
2436}
2437
2438/* Check operands of identity chacks ("is" and "is not").
2439 Emit a warning if any operand is a constant except named singletons.
2440 Return 0 on error.
2441 */
2442static int
2443check_compare(struct compiler *c, expr_ty e)
2444{
2445 Py_ssize_t i, n;
2446 int left = check_is_arg(e->v.Compare.left);
2447 n = asdl_seq_LEN(e->v.Compare.ops);
2448 for (i = 0; i < n; i++) {
2449 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2450 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2451 if (op == Is || op == IsNot) {
2452 if (!right || !left) {
2453 const char *msg = (op == Is)
2454 ? "\"is\" with a literal. Did you mean \"==\"?"
2455 : "\"is not\" with a literal. Did you mean \"!=\"?";
2456 return compiler_warn(c, msg);
2457 }
2458 }
2459 left = right;
2460 }
2461 return 1;
2462}
2463
Mark Shannon9af0e472020-01-14 10:12:45 +00002464static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002465{
Mark Shannon9af0e472020-01-14 10:12:45 +00002466 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 switch (op) {
2468 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002469 cmp = Py_EQ;
2470 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002471 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002472 cmp = Py_NE;
2473 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002474 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002475 cmp = Py_LT;
2476 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002478 cmp = Py_LE;
2479 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002480 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 cmp = Py_GT;
2482 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002484 cmp = Py_GE;
2485 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002486 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002487 ADDOP_I(c, IS_OP, 0);
2488 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002490 ADDOP_I(c, IS_OP, 1);
2491 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002492 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002493 ADDOP_I(c, CONTAINS_OP, 0);
2494 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002495 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002496 ADDOP_I(c, CONTAINS_OP, 1);
2497 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002498 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002499 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002500 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002501 ADDOP_I(c, COMPARE_OP, cmp);
2502 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503}
2504
Mark Shannon9af0e472020-01-14 10:12:45 +00002505
2506
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002507static int
2508compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2509{
2510 switch (e->kind) {
2511 case UnaryOp_kind:
2512 if (e->v.UnaryOp.op == Not)
2513 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2514 /* fallback to general implementation */
2515 break;
2516 case BoolOp_kind: {
2517 asdl_seq *s = e->v.BoolOp.values;
2518 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2519 assert(n >= 0);
2520 int cond2 = e->v.BoolOp.op == Or;
2521 basicblock *next2 = next;
2522 if (!cond2 != !cond) {
2523 next2 = compiler_new_block(c);
2524 if (next2 == NULL)
2525 return 0;
2526 }
2527 for (i = 0; i < n; ++i) {
2528 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2529 return 0;
2530 }
2531 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2532 return 0;
2533 if (next2 != next)
2534 compiler_use_next_block(c, next2);
2535 return 1;
2536 }
2537 case IfExp_kind: {
2538 basicblock *end, *next2;
2539 end = compiler_new_block(c);
2540 if (end == NULL)
2541 return 0;
2542 next2 = compiler_new_block(c);
2543 if (next2 == NULL)
2544 return 0;
2545 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2546 return 0;
2547 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2548 return 0;
2549 ADDOP_JREL(c, JUMP_FORWARD, end);
2550 compiler_use_next_block(c, next2);
2551 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2552 return 0;
2553 compiler_use_next_block(c, end);
2554 return 1;
2555 }
2556 case Compare_kind: {
2557 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2558 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002559 if (!check_compare(c, e)) {
2560 return 0;
2561 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002562 basicblock *cleanup = compiler_new_block(c);
2563 if (cleanup == NULL)
2564 return 0;
2565 VISIT(c, expr, e->v.Compare.left);
2566 for (i = 0; i < n; i++) {
2567 VISIT(c, expr,
2568 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2569 ADDOP(c, DUP_TOP);
2570 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002571 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002572 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2573 NEXT_BLOCK(c);
2574 }
2575 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002576 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002577 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2578 basicblock *end = compiler_new_block(c);
2579 if (end == NULL)
2580 return 0;
2581 ADDOP_JREL(c, JUMP_FORWARD, end);
2582 compiler_use_next_block(c, cleanup);
2583 ADDOP(c, POP_TOP);
2584 if (!cond) {
2585 ADDOP_JREL(c, JUMP_FORWARD, next);
2586 }
2587 compiler_use_next_block(c, end);
2588 return 1;
2589 }
2590 /* fallback to general implementation */
2591 break;
2592 }
2593 default:
2594 /* fallback to general implementation */
2595 break;
2596 }
2597
2598 /* general implementation */
2599 VISIT(c, expr, e);
2600 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2601 return 1;
2602}
2603
2604static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002605compiler_ifexp(struct compiler *c, expr_ty e)
2606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 basicblock *end, *next;
2608
2609 assert(e->kind == IfExp_kind);
2610 end = compiler_new_block(c);
2611 if (end == NULL)
2612 return 0;
2613 next = compiler_new_block(c);
2614 if (next == NULL)
2615 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002616 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2617 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 VISIT(c, expr, e->v.IfExp.body);
2619 ADDOP_JREL(c, JUMP_FORWARD, end);
2620 compiler_use_next_block(c, next);
2621 VISIT(c, expr, e->v.IfExp.orelse);
2622 compiler_use_next_block(c, end);
2623 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002624}
2625
2626static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627compiler_lambda(struct compiler *c, expr_ty e)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002630 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002632 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 arguments_ty args = e->v.Lambda.args;
2634 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002636 if (!compiler_check_debug_args(c, args))
2637 return 0;
2638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 if (!name) {
2640 name = PyUnicode_InternFromString("<lambda>");
2641 if (!name)
2642 return 0;
2643 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002645 funcflags = compiler_default_arguments(c, args);
2646 if (funcflags == -1) {
2647 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002649
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002650 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002651 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 /* Make None the first constant, so the lambda can't have a
2655 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002656 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002660 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2662 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2663 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002664 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
2666 else {
2667 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002668 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002670 qualname = c->u->u_qualname;
2671 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002673 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002676 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002677 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 Py_DECREF(co);
2679
2680 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681}
2682
2683static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684compiler_if(struct compiler *c, stmt_ty s)
2685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 basicblock *end, *next;
2687 int constant;
2688 assert(s->kind == If_kind);
2689 end = compiler_new_block(c);
2690 if (end == NULL)
2691 return 0;
2692
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002693 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002694 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 * constant = 1: "if 1", "if 2", ...
2696 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002697 if (constant == 0) {
2698 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002700 END_DO_NOT_EMIT_BYTECODE
2701 if (s->v.If.orelse) {
2702 VISIT_SEQ(c, stmt, s->v.If.orelse);
2703 }
2704 } else if (constant == 1) {
2705 VISIT_SEQ(c, stmt, s->v.If.body);
2706 if (s->v.If.orelse) {
2707 BEGIN_DO_NOT_EMIT_BYTECODE
2708 VISIT_SEQ(c, stmt, s->v.If.orelse);
2709 END_DO_NOT_EMIT_BYTECODE
2710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002712 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 next = compiler_new_block(c);
2714 if (next == NULL)
2715 return 0;
2716 }
Mark Shannonfee55262019-11-21 09:11:43 +00002717 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002719 }
2720 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002721 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002724 if (asdl_seq_LEN(s->v.If.orelse)) {
2725 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 compiler_use_next_block(c, next);
2727 VISIT_SEQ(c, stmt, s->v.If.orelse);
2728 }
2729 }
2730 compiler_use_next_block(c, end);
2731 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732}
2733
2734static int
2735compiler_for(struct compiler *c, stmt_ty s)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 start = compiler_new_block(c);
2740 cleanup = compiler_new_block(c);
2741 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002742 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002744 }
2745 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 VISIT(c, expr, s->v.For.iter);
2749 ADDOP(c, GET_ITER);
2750 compiler_use_next_block(c, start);
2751 ADDOP_JREL(c, FOR_ITER, cleanup);
2752 VISIT(c, expr, s->v.For.target);
2753 VISIT_SEQ(c, stmt, s->v.For.body);
2754 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2755 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002756
2757 compiler_pop_fblock(c, FOR_LOOP, start);
2758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 VISIT_SEQ(c, stmt, s->v.For.orelse);
2760 compiler_use_next_block(c, end);
2761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762}
2763
Yury Selivanov75445082015-05-11 22:57:16 -04002764
2765static int
2766compiler_async_for(struct compiler *c, stmt_ty s)
2767{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002768 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002769 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002770 c->u->u_ste->ste_coroutine = 1;
2771 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002772 return compiler_error(c, "'async for' outside async function");
2773 }
2774
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002775 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002776 except = compiler_new_block(c);
2777 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002778
Mark Shannonfee55262019-11-21 09:11:43 +00002779 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002780 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002781 }
Yury Selivanov75445082015-05-11 22:57:16 -04002782 VISIT(c, expr, s->v.AsyncFor.iter);
2783 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002784
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002785 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002786 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002787 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002788 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 /* SETUP_FINALLY to guard the __anext__ call */
2790 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002791 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002792 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002793 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002794 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002795
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002796 /* Success block for __anext__ */
2797 VISIT(c, expr, s->v.AsyncFor.target);
2798 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2799 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2800
2801 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002802
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002804 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002805 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002806
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002808 VISIT_SEQ(c, stmt, s->v.For.orelse);
2809
2810 compiler_use_next_block(c, end);
2811
2812 return 1;
2813}
2814
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815static int
2816compiler_while(struct compiler *c, stmt_ty s)
2817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002819 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002822 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002823 // Push a dummy block so the VISIT_SEQ knows that we are
2824 // inside a while loop so it can correctly evaluate syntax
2825 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002826 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002827 return 0;
2828 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002829 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002830 // Remove the dummy block now that is not needed.
2831 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002832 END_DO_NOT_EMIT_BYTECODE
2833 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002835 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 1;
2837 }
2838 loop = compiler_new_block(c);
2839 end = compiler_new_block(c);
2840 if (constant == -1) {
2841 anchor = compiler_new_block(c);
2842 if (anchor == NULL)
2843 return 0;
2844 }
2845 if (loop == NULL || end == NULL)
2846 return 0;
2847 if (s->v.While.orelse) {
2848 orelse = compiler_new_block(c);
2849 if (orelse == NULL)
2850 return 0;
2851 }
2852 else
2853 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002856 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return 0;
2858 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002859 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2860 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 }
2862 VISIT_SEQ(c, stmt, s->v.While.body);
2863 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 /* XXX should the two POP instructions be in a separate block
2866 if there is no else clause ?
2867 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002869 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002871 compiler_pop_fblock(c, WHILE_LOOP, loop);
2872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 if (orelse != NULL) /* what if orelse is just pass? */
2874 VISIT_SEQ(c, stmt, s->v.While.orelse);
2875 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878}
2879
2880static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002884 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 if (c->u->u_ste->ste_type != FunctionBlock)
2886 return compiler_error(c, "'return' outside function");
2887 if (s->v.Return.value != NULL &&
2888 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2889 {
2890 return compiler_error(
2891 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002893 if (preserve_tos) {
2894 VISIT(c, expr, s->v.Return.value);
2895 }
Mark Shannonfee55262019-11-21 09:11:43 +00002896 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2897 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002898 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002899 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002900 }
2901 else if (!preserve_tos) {
2902 VISIT(c, expr, s->v.Return.value);
2903 }
2904 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907}
2908
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002909static int
2910compiler_break(struct compiler *c)
2911{
Mark Shannonfee55262019-11-21 09:11:43 +00002912 struct fblockinfo *loop = NULL;
2913 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2914 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002915 }
Mark Shannonfee55262019-11-21 09:11:43 +00002916 if (loop == NULL) {
2917 return compiler_error(c, "'break' outside loop");
2918 }
2919 if (!compiler_unwind_fblock(c, loop, 0)) {
2920 return 0;
2921 }
2922 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2923 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002924}
2925
2926static int
2927compiler_continue(struct compiler *c)
2928{
Mark Shannonfee55262019-11-21 09:11:43 +00002929 struct fblockinfo *loop = NULL;
2930 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2931 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002932 }
Mark Shannonfee55262019-11-21 09:11:43 +00002933 if (loop == NULL) {
2934 return compiler_error(c, "'continue' not properly in loop");
2935 }
2936 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2937 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002938}
2939
2940
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942
2943 SETUP_FINALLY L
2944 <code for body>
2945 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002946 <code for finalbody>
2947 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002948 L:
2949 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002950 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 The special instructions use the block stack. Each block
2953 stack entry contains the instruction that created it (here
2954 SETUP_FINALLY), the level of the value stack at the time the
2955 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 Pushes the current value stack level and the label
2959 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002961 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002964 when a SETUP_FINALLY entry is found, the raised and the caught
2965 exceptions are pushed onto the value stack (and the exception
2966 condition is cleared), and the interpreter jumps to the label
2967 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968*/
2969
2970static int
2971compiler_try_finally(struct compiler *c, stmt_ty s)
2972{
Mark Shannonfee55262019-11-21 09:11:43 +00002973 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 body = compiler_new_block(c);
2976 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002977 exit = compiler_new_block(c);
2978 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002981 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 ADDOP_JREL(c, SETUP_FINALLY, end);
2983 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002984 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002986 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2987 if (!compiler_try_except(c, s))
2988 return 0;
2989 }
2990 else {
2991 VISIT_SEQ(c, stmt, s->v.Try.body);
2992 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002994 compiler_pop_fblock(c, FINALLY_TRY, body);
2995 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2996 ADDOP_JREL(c, JUMP_FORWARD, exit);
2997 /* `finally` block */
2998 compiler_use_next_block(c, end);
2999 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3000 return 0;
3001 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3002 compiler_pop_fblock(c, FINALLY_END, end);
3003 ADDOP(c, RERAISE);
3004 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006}
3007
3008/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003009 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 (The contents of the value stack is shown in [], with the top
3011 at the right; 'tb' is trace-back info, 'val' the exception's
3012 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013
3014 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003015 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 [] <code for S>
3017 [] POP_BLOCK
3018 [] JUMP_FORWARD L0
3019
3020 [tb, val, exc] L1: DUP )
3021 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003022 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 [tb, val, exc] POP
3024 [tb, val] <assign to V1> (or POP if no V1)
3025 [tb] POP
3026 [] <code for S1>
3027 JUMP_FORWARD L0
3028
3029 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 .............................etc.......................
3031
Mark Shannonfee55262019-11-21 09:11:43 +00003032 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033
3034 [] L0: <next statement>
3035
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 Of course, parts are not generated if Vi or Ei is not present.
3037*/
3038static int
3039compiler_try_except(struct compiler *c, stmt_ty s)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003042 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 body = compiler_new_block(c);
3045 except = compiler_new_block(c);
3046 orelse = compiler_new_block(c);
3047 end = compiler_new_block(c);
3048 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3049 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003050 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003052 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003054 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 ADDOP(c, POP_BLOCK);
3056 compiler_pop_fblock(c, EXCEPT, body);
3057 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003058 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 compiler_use_next_block(c, except);
3060 for (i = 0; i < n; i++) {
3061 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003062 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 if (!handler->v.ExceptHandler.type && i < n-1)
3064 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003065 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 except = compiler_new_block(c);
3067 if (except == NULL)
3068 return 0;
3069 if (handler->v.ExceptHandler.type) {
3070 ADDOP(c, DUP_TOP);
3071 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003072 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 }
3074 ADDOP(c, POP_TOP);
3075 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003077
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003078 cleanup_end = compiler_new_block(c);
3079 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003080 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003082 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003083
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3085 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 /*
3088 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003089 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003090 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003091 try:
3092 # body
3093 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003094 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003095 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003096 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003098 /* second try: */
3099 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3100 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003101 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003104 /* second # body */
3105 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003106 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003107 ADDOP(c, POP_BLOCK);
3108 ADDOP(c, POP_EXCEPT);
3109 /* name = None; del name */
3110 ADDOP_LOAD_CONST(c, Py_None);
3111 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3112 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3113 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Mark Shannonfee55262019-11-21 09:11:43 +00003115 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003116 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003118 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003119 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003120 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122
Mark Shannonfee55262019-11-21 09:11:43 +00003123 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 }
3125 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003126 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003128 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003129 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003130 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131
Guido van Rossumb940e112007-01-10 16:19:56 +00003132 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003133 ADDOP(c, POP_TOP);
3134 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003135 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003136 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003138 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003139 ADDOP(c, POP_EXCEPT);
3140 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 compiler_use_next_block(c, except);
3143 }
Mark Shannonfee55262019-11-21 09:11:43 +00003144 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003146 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 compiler_use_next_block(c, end);
3148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149}
3150
3151static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003152compiler_try(struct compiler *c, stmt_ty s) {
3153 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3154 return compiler_try_finally(c, s);
3155 else
3156 return compiler_try_except(c, s);
3157}
3158
3159
3160static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161compiler_import_as(struct compiler *c, identifier name, identifier asname)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* The IMPORT_NAME opcode was already generated. This function
3164 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003167 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003169 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3170 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003172 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003175 while (1) {
3176 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003178 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003179 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003180 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003181 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003183 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003184 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003185 if (dot == -1) {
3186 break;
3187 }
3188 ADDOP(c, ROT_TWO);
3189 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003191 if (!compiler_nameop(c, asname, Store)) {
3192 return 0;
3193 }
3194 ADDOP(c, POP_TOP);
3195 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 }
3197 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198}
3199
3200static int
3201compiler_import(struct compiler *c, stmt_ty s)
3202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* The Import node stores a module name like a.b.c as a single
3204 string. This is convenient for all cases except
3205 import a.b.c as d
3206 where we need to parse that string to extract the individual
3207 module names.
3208 XXX Perhaps change the representation to make this case simpler?
3209 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003210 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 for (i = 0; i < n; i++) {
3213 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3214 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003215
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003216 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3217 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 if (alias->asname) {
3221 r = compiler_import_as(c, alias->name, alias->asname);
3222 if (!r)
3223 return r;
3224 }
3225 else {
3226 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003227 Py_ssize_t dot = PyUnicode_FindChar(
3228 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003229 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003230 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003231 if (tmp == NULL)
3232 return 0;
3233 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003235 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 Py_DECREF(tmp);
3237 }
3238 if (!r)
3239 return r;
3240 }
3241 }
3242 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003243}
3244
3245static int
3246compiler_from_import(struct compiler *c, stmt_ty s)
3247{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003248 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003249 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (!empty_string) {
3253 empty_string = PyUnicode_FromString("");
3254 if (!empty_string)
3255 return 0;
3256 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003258 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003259
3260 names = PyTuple_New(n);
3261 if (!names)
3262 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 /* build up the names */
3265 for (i = 0; i < n; i++) {
3266 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3267 Py_INCREF(alias->name);
3268 PyTuple_SET_ITEM(names, i, alias->name);
3269 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003272 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 Py_DECREF(names);
3274 return compiler_error(c, "from __future__ imports must occur "
3275 "at the beginning of the file");
3276 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003277 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 if (s->v.ImportFrom.module) {
3280 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3281 }
3282 else {
3283 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3284 }
3285 for (i = 0; i < n; i++) {
3286 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3287 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003289 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 assert(n == 1);
3291 ADDOP(c, IMPORT_STAR);
3292 return 1;
3293 }
3294
3295 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3296 store_name = alias->name;
3297 if (alias->asname)
3298 store_name = alias->asname;
3299
3300 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 return 0;
3302 }
3303 }
3304 /* remove imported module */
3305 ADDOP(c, POP_TOP);
3306 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307}
3308
3309static int
3310compiler_assert(struct compiler *c, stmt_ty s)
3311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
Georg Brandl8334fd92010-12-04 10:26:46 +00003314 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003317 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3318 {
3319 if (!compiler_warn(c, "assertion is always true, "
3320 "perhaps remove parentheses?"))
3321 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003322 return 0;
3323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 end = compiler_new_block(c);
3326 if (end == NULL)
3327 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003328 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3329 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003330 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 if (s->v.Assert.msg) {
3332 VISIT(c, expr, s->v.Assert.msg);
3333 ADDOP_I(c, CALL_FUNCTION, 1);
3334 }
3335 ADDOP_I(c, RAISE_VARARGS, 1);
3336 compiler_use_next_block(c, end);
3337 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338}
3339
3340static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003341compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3342{
3343 if (c->c_interactive && c->c_nestlevel <= 1) {
3344 VISIT(c, expr, value);
3345 ADDOP(c, PRINT_EXPR);
3346 return 1;
3347 }
3348
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003349 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003350 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003351 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003352 }
3353
3354 VISIT(c, expr, value);
3355 ADDOP(c, POP_TOP);
3356 return 1;
3357}
3358
3359static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360compiler_visit_stmt(struct compiler *c, stmt_ty s)
3361{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003362 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003365 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 switch (s->kind) {
3368 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003369 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 case ClassDef_kind:
3371 return compiler_class(c, s);
3372 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003373 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 case Delete_kind:
3375 VISIT_SEQ(c, expr, s->v.Delete.targets)
3376 break;
3377 case Assign_kind:
3378 n = asdl_seq_LEN(s->v.Assign.targets);
3379 VISIT(c, expr, s->v.Assign.value);
3380 for (i = 0; i < n; i++) {
3381 if (i < n - 1)
3382 ADDOP(c, DUP_TOP);
3383 VISIT(c, expr,
3384 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3385 }
3386 break;
3387 case AugAssign_kind:
3388 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003389 case AnnAssign_kind:
3390 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 case For_kind:
3392 return compiler_for(c, s);
3393 case While_kind:
3394 return compiler_while(c, s);
3395 case If_kind:
3396 return compiler_if(c, s);
3397 case Raise_kind:
3398 n = 0;
3399 if (s->v.Raise.exc) {
3400 VISIT(c, expr, s->v.Raise.exc);
3401 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003402 if (s->v.Raise.cause) {
3403 VISIT(c, expr, s->v.Raise.cause);
3404 n++;
3405 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003407 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003409 case Try_kind:
3410 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 case Assert_kind:
3412 return compiler_assert(c, s);
3413 case Import_kind:
3414 return compiler_import(c, s);
3415 case ImportFrom_kind:
3416 return compiler_from_import(c, s);
3417 case Global_kind:
3418 case Nonlocal_kind:
3419 break;
3420 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003421 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 case Pass_kind:
3423 break;
3424 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003425 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 case Continue_kind:
3427 return compiler_continue(c);
3428 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003429 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003430 case AsyncFunctionDef_kind:
3431 return compiler_function(c, s, 1);
3432 case AsyncWith_kind:
3433 return compiler_async_with(c, s, 0);
3434 case AsyncFor_kind:
3435 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 }
Yury Selivanov75445082015-05-11 22:57:16 -04003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439}
3440
3441static int
3442unaryop(unaryop_ty op)
3443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 switch (op) {
3445 case Invert:
3446 return UNARY_INVERT;
3447 case Not:
3448 return UNARY_NOT;
3449 case UAdd:
3450 return UNARY_POSITIVE;
3451 case USub:
3452 return UNARY_NEGATIVE;
3453 default:
3454 PyErr_Format(PyExc_SystemError,
3455 "unary op %d should not be possible", op);
3456 return 0;
3457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458}
3459
3460static int
Andy Lester76d58772020-03-10 21:18:12 -05003461binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 switch (op) {
3464 case Add:
3465 return BINARY_ADD;
3466 case Sub:
3467 return BINARY_SUBTRACT;
3468 case Mult:
3469 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003470 case MatMult:
3471 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 case Div:
3473 return BINARY_TRUE_DIVIDE;
3474 case Mod:
3475 return BINARY_MODULO;
3476 case Pow:
3477 return BINARY_POWER;
3478 case LShift:
3479 return BINARY_LSHIFT;
3480 case RShift:
3481 return BINARY_RSHIFT;
3482 case BitOr:
3483 return BINARY_OR;
3484 case BitXor:
3485 return BINARY_XOR;
3486 case BitAnd:
3487 return BINARY_AND;
3488 case FloorDiv:
3489 return BINARY_FLOOR_DIVIDE;
3490 default:
3491 PyErr_Format(PyExc_SystemError,
3492 "binary op %d should not be possible", op);
3493 return 0;
3494 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495}
3496
3497static int
Andy Lester76d58772020-03-10 21:18:12 -05003498inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 switch (op) {
3501 case Add:
3502 return INPLACE_ADD;
3503 case Sub:
3504 return INPLACE_SUBTRACT;
3505 case Mult:
3506 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003507 case MatMult:
3508 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 case Div:
3510 return INPLACE_TRUE_DIVIDE;
3511 case Mod:
3512 return INPLACE_MODULO;
3513 case Pow:
3514 return INPLACE_POWER;
3515 case LShift:
3516 return INPLACE_LSHIFT;
3517 case RShift:
3518 return INPLACE_RSHIFT;
3519 case BitOr:
3520 return INPLACE_OR;
3521 case BitXor:
3522 return INPLACE_XOR;
3523 case BitAnd:
3524 return INPLACE_AND;
3525 case FloorDiv:
3526 return INPLACE_FLOOR_DIVIDE;
3527 default:
3528 PyErr_Format(PyExc_SystemError,
3529 "inplace binary op %d should not be possible", op);
3530 return 0;
3531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532}
3533
3534static int
3535compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3536{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003537 int op, scope;
3538 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyObject *dict = c->u->u_names;
3542 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003544 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3545 !_PyUnicode_EqualToASCIIString(name, "True") &&
3546 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003547
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003548 if (forbidden_name(c, name, ctx))
3549 return 0;
3550
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003551 mangled = _Py_Mangle(c->u->u_private, name);
3552 if (!mangled)
3553 return 0;
3554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 op = 0;
3556 optype = OP_NAME;
3557 scope = PyST_GetScope(c->u->u_ste, mangled);
3558 switch (scope) {
3559 case FREE:
3560 dict = c->u->u_freevars;
3561 optype = OP_DEREF;
3562 break;
3563 case CELL:
3564 dict = c->u->u_cellvars;
3565 optype = OP_DEREF;
3566 break;
3567 case LOCAL:
3568 if (c->u->u_ste->ste_type == FunctionBlock)
3569 optype = OP_FAST;
3570 break;
3571 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003572 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 optype = OP_GLOBAL;
3574 break;
3575 case GLOBAL_EXPLICIT:
3576 optype = OP_GLOBAL;
3577 break;
3578 default:
3579 /* scope can be 0 */
3580 break;
3581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003584 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 switch (optype) {
3587 case OP_DEREF:
3588 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003589 case Load:
3590 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3591 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003592 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003593 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 }
3595 break;
3596 case OP_FAST:
3597 switch (ctx) {
3598 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003599 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003602 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 return 1;
3604 case OP_GLOBAL:
3605 switch (ctx) {
3606 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003607 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 }
3610 break;
3611 case OP_NAME:
3612 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003613 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003614 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 }
3617 break;
3618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003621 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 Py_DECREF(mangled);
3623 if (arg < 0)
3624 return 0;
3625 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626}
3627
3628static int
3629compiler_boolop(struct compiler *c, expr_ty e)
3630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003632 int jumpi;
3633 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 assert(e->kind == BoolOp_kind);
3637 if (e->v.BoolOp.op == And)
3638 jumpi = JUMP_IF_FALSE_OR_POP;
3639 else
3640 jumpi = JUMP_IF_TRUE_OR_POP;
3641 end = compiler_new_block(c);
3642 if (end == NULL)
3643 return 0;
3644 s = e->v.BoolOp.values;
3645 n = asdl_seq_LEN(s) - 1;
3646 assert(n >= 0);
3647 for (i = 0; i < n; ++i) {
3648 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3649 ADDOP_JABS(c, jumpi, end);
3650 }
3651 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3652 compiler_use_next_block(c, end);
3653 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654}
3655
3656static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003657starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3658 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003659{
3660 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003661 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003662 if (n > 2 && are_all_items_const(elts, 0, n)) {
3663 PyObject *folded = PyTuple_New(n);
3664 if (folded == NULL) {
3665 return 0;
3666 }
3667 PyObject *val;
3668 for (i = 0; i < n; i++) {
3669 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3670 Py_INCREF(val);
3671 PyTuple_SET_ITEM(folded, i, val);
3672 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003673 if (tuple) {
3674 ADDOP_LOAD_CONST_NEW(c, folded);
3675 } else {
3676 if (add == SET_ADD) {
3677 Py_SETREF(folded, PyFrozenSet_New(folded));
3678 if (folded == NULL) {
3679 return 0;
3680 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003681 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003682 ADDOP_I(c, build, pushed);
3683 ADDOP_LOAD_CONST_NEW(c, folded);
3684 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003686 return 1;
3687 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003688
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003689 for (i = 0; i < n; i++) {
3690 expr_ty elt = asdl_seq_GET(elts, i);
3691 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003692 seen_star = 1;
3693 }
3694 }
3695 if (seen_star) {
3696 seen_star = 0;
3697 for (i = 0; i < n; i++) {
3698 expr_ty elt = asdl_seq_GET(elts, i);
3699 if (elt->kind == Starred_kind) {
3700 if (seen_star == 0) {
3701 ADDOP_I(c, build, i+pushed);
3702 seen_star = 1;
3703 }
3704 VISIT(c, expr, elt->v.Starred.value);
3705 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003706 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003707 else {
3708 VISIT(c, expr, elt);
3709 if (seen_star) {
3710 ADDOP_I(c, add, 1);
3711 }
3712 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003713 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003714 assert(seen_star);
3715 if (tuple) {
3716 ADDOP(c, LIST_TO_TUPLE);
3717 }
3718 }
3719 else {
3720 for (i = 0; i < n; i++) {
3721 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003722 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003723 }
3724 if (tuple) {
3725 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3726 } else {
3727 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003728 }
3729 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003730 return 1;
3731}
3732
3733static int
3734assignment_helper(struct compiler *c, asdl_seq *elts)
3735{
3736 Py_ssize_t n = asdl_seq_LEN(elts);
3737 Py_ssize_t i;
3738 int seen_star = 0;
3739 for (i = 0; i < n; i++) {
3740 expr_ty elt = asdl_seq_GET(elts, i);
3741 if (elt->kind == Starred_kind && !seen_star) {
3742 if ((i >= (1 << 8)) ||
3743 (n-i-1 >= (INT_MAX >> 8)))
3744 return compiler_error(c,
3745 "too many expressions in "
3746 "star-unpacking assignment");
3747 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3748 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 }
3750 else if (elt->kind == Starred_kind) {
3751 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003752 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 }
3754 }
3755 if (!seen_star) {
3756 ADDOP_I(c, UNPACK_SEQUENCE, n);
3757 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003758 for (i = 0; i < n; i++) {
3759 expr_ty elt = asdl_seq_GET(elts, i);
3760 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3761 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 return 1;
3763}
3764
3765static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766compiler_list(struct compiler *c, expr_ty e)
3767{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003768 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003769 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003770 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003772 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003773 return starunpack_helper(c, elts, 0, BUILD_LIST,
3774 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003776 else
3777 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779}
3780
3781static int
3782compiler_tuple(struct compiler *c, expr_ty e)
3783{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003784 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003785 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003786 return assignment_helper(c, elts);
3787 }
3788 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003789 return starunpack_helper(c, elts, 0, BUILD_LIST,
3790 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 }
3792 else
3793 VISIT_SEQ(c, expr, elts);
3794 return 1;
3795}
3796
3797static int
3798compiler_set(struct compiler *c, expr_ty e)
3799{
Mark Shannon13bc1392020-01-23 09:25:17 +00003800 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3801 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003802}
3803
3804static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003805are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3806{
3807 Py_ssize_t i;
3808 for (i = begin; i < end; i++) {
3809 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003810 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003811 return 0;
3812 }
3813 return 1;
3814}
3815
3816static int
3817compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3818{
3819 Py_ssize_t i, n = end - begin;
3820 PyObject *keys, *key;
3821 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3822 for (i = begin; i < end; i++) {
3823 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3824 }
3825 keys = PyTuple_New(n);
3826 if (keys == NULL) {
3827 return 0;
3828 }
3829 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003830 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003831 Py_INCREF(key);
3832 PyTuple_SET_ITEM(keys, i - begin, key);
3833 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003834 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003835 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3836 }
3837 else {
3838 for (i = begin; i < end; i++) {
3839 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3840 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3841 }
3842 ADDOP_I(c, BUILD_MAP, n);
3843 }
3844 return 1;
3845}
3846
3847static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003848compiler_dict(struct compiler *c, expr_ty e)
3849{
Victor Stinner976bb402016-03-23 11:36:19 +01003850 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003851 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003852 int is_unpacking = 0;
3853 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003854 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003855 elements = 0;
3856 for (i = 0; i < n; i++) {
3857 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003858 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003859 if (elements) {
3860 if (!compiler_subdict(c, e, i - elements, i)) {
3861 return 0;
3862 }
3863 if (have_dict) {
3864 ADDOP_I(c, DICT_UPDATE, 1);
3865 }
3866 have_dict = 1;
3867 elements = 0;
3868 }
3869 if (have_dict == 0) {
3870 ADDOP_I(c, BUILD_MAP, 0);
3871 have_dict = 1;
3872 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003874 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003875 }
3876 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003877 if (elements == 0xFFFF) {
3878 if (!compiler_subdict(c, e, i - elements, i)) {
3879 return 0;
3880 }
3881 if (have_dict) {
3882 ADDOP_I(c, DICT_UPDATE, 1);
3883 }
3884 have_dict = 1;
3885 elements = 0;
3886 }
3887 else {
3888 elements++;
3889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 }
3891 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003892 if (elements) {
3893 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003894 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003895 }
3896 if (have_dict) {
3897 ADDOP_I(c, DICT_UPDATE, 1);
3898 }
3899 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003900 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003901 if (!have_dict) {
3902 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 }
3904 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905}
3906
3907static int
3908compiler_compare(struct compiler *c, expr_ty e)
3909{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003910 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003912 if (!check_compare(c, e)) {
3913 return 0;
3914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003916 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3917 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3918 if (n == 0) {
3919 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003920 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003921 }
3922 else {
3923 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 if (cleanup == NULL)
3925 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003926 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 VISIT(c, expr,
3928 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003929 ADDOP(c, DUP_TOP);
3930 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003931 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003932 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3933 NEXT_BLOCK(c);
3934 }
3935 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003936 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 basicblock *end = compiler_new_block(c);
3938 if (end == NULL)
3939 return 0;
3940 ADDOP_JREL(c, JUMP_FORWARD, end);
3941 compiler_use_next_block(c, cleanup);
3942 ADDOP(c, ROT_TWO);
3943 ADDOP(c, POP_TOP);
3944 compiler_use_next_block(c, end);
3945 }
3946 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003947}
3948
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003949static PyTypeObject *
3950infer_type(expr_ty e)
3951{
3952 switch (e->kind) {
3953 case Tuple_kind:
3954 return &PyTuple_Type;
3955 case List_kind:
3956 case ListComp_kind:
3957 return &PyList_Type;
3958 case Dict_kind:
3959 case DictComp_kind:
3960 return &PyDict_Type;
3961 case Set_kind:
3962 case SetComp_kind:
3963 return &PySet_Type;
3964 case GeneratorExp_kind:
3965 return &PyGen_Type;
3966 case Lambda_kind:
3967 return &PyFunction_Type;
3968 case JoinedStr_kind:
3969 case FormattedValue_kind:
3970 return &PyUnicode_Type;
3971 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003972 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003973 default:
3974 return NULL;
3975 }
3976}
3977
3978static int
3979check_caller(struct compiler *c, expr_ty e)
3980{
3981 switch (e->kind) {
3982 case Constant_kind:
3983 case Tuple_kind:
3984 case List_kind:
3985 case ListComp_kind:
3986 case Dict_kind:
3987 case DictComp_kind:
3988 case Set_kind:
3989 case SetComp_kind:
3990 case GeneratorExp_kind:
3991 case JoinedStr_kind:
3992 case FormattedValue_kind:
3993 return compiler_warn(c, "'%.200s' object is not callable; "
3994 "perhaps you missed a comma?",
3995 infer_type(e)->tp_name);
3996 default:
3997 return 1;
3998 }
3999}
4000
4001static int
4002check_subscripter(struct compiler *c, expr_ty e)
4003{
4004 PyObject *v;
4005
4006 switch (e->kind) {
4007 case Constant_kind:
4008 v = e->v.Constant.value;
4009 if (!(v == Py_None || v == Py_Ellipsis ||
4010 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4011 PyAnySet_Check(v)))
4012 {
4013 return 1;
4014 }
4015 /* fall through */
4016 case Set_kind:
4017 case SetComp_kind:
4018 case GeneratorExp_kind:
4019 case Lambda_kind:
4020 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4021 "perhaps you missed a comma?",
4022 infer_type(e)->tp_name);
4023 default:
4024 return 1;
4025 }
4026}
4027
4028static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004029check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004030{
4031 PyObject *v;
4032
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004033 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004034 if (index_type == NULL
4035 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4036 || index_type == &PySlice_Type) {
4037 return 1;
4038 }
4039
4040 switch (e->kind) {
4041 case Constant_kind:
4042 v = e->v.Constant.value;
4043 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4044 return 1;
4045 }
4046 /* fall through */
4047 case Tuple_kind:
4048 case List_kind:
4049 case ListComp_kind:
4050 case JoinedStr_kind:
4051 case FormattedValue_kind:
4052 return compiler_warn(c, "%.200s indices must be integers or slices, "
4053 "not %.200s; "
4054 "perhaps you missed a comma?",
4055 infer_type(e)->tp_name,
4056 index_type->tp_name);
4057 default:
4058 return 1;
4059 }
4060}
4061
Zackery Spytz97f5de02019-03-22 01:30:32 -06004062// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004064maybe_optimize_method_call(struct compiler *c, expr_ty e)
4065{
4066 Py_ssize_t argsl, i;
4067 expr_ty meth = e->v.Call.func;
4068 asdl_seq *args = e->v.Call.args;
4069
4070 /* Check that the call node is an attribute access, and that
4071 the call doesn't have keyword parameters. */
4072 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4073 asdl_seq_LEN(e->v.Call.keywords))
4074 return -1;
4075
4076 /* Check that there are no *varargs types of arguments. */
4077 argsl = asdl_seq_LEN(args);
4078 for (i = 0; i < argsl; i++) {
4079 expr_ty elt = asdl_seq_GET(args, i);
4080 if (elt->kind == Starred_kind) {
4081 return -1;
4082 }
4083 }
4084
4085 /* Alright, we can optimize the code. */
4086 VISIT(c, expr, meth->v.Attribute.value);
4087 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4088 VISIT_SEQ(c, expr, e->v.Call.args);
4089 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4090 return 1;
4091}
4092
4093static int
Zackery Spytz08050e92020-04-06 00:47:47 -06004094validate_keywords(struct compiler *c, asdl_seq *keywords)
4095{
4096 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4097 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004098 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4099 if (key->arg == NULL) {
4100 continue;
4101 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004102 if (forbidden_name(c, key->arg, Store)) {
4103 return -1;
4104 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004105 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004106 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4107 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4108 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4109 if (msg == NULL) {
4110 return -1;
4111 }
4112 c->u->u_col_offset = other->col_offset;
4113 compiler_error(c, PyUnicode_AsUTF8(msg));
4114 Py_DECREF(msg);
4115 return -1;
4116 }
4117 }
4118 }
4119 return 0;
4120}
4121
4122static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123compiler_call(struct compiler *c, expr_ty e)
4124{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004125 int ret = maybe_optimize_method_call(c, e);
4126 if (ret >= 0) {
4127 return ret;
4128 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004129 if (!check_caller(c, e->v.Call.func)) {
4130 return 0;
4131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 VISIT(c, expr, e->v.Call.func);
4133 return compiler_call_helper(c, 0,
4134 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004135 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004136}
4137
Eric V. Smith235a6f02015-09-19 14:51:32 -04004138static int
4139compiler_joined_str(struct compiler *c, expr_ty e)
4140{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004141 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004142 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4143 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004144 return 1;
4145}
4146
Eric V. Smitha78c7952015-11-03 12:45:05 -05004147/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004148static int
4149compiler_formatted_value(struct compiler *c, expr_ty e)
4150{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004151 /* Our oparg encodes 2 pieces of information: the conversion
4152 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004154 Convert the conversion char to 3 bits:
4155 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004156 !s : 001 0x1 FVC_STR
4157 !r : 010 0x2 FVC_REPR
4158 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004159
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 next bit is whether or not we have a format spec:
4161 yes : 100 0x4
4162 no : 000 0x0
4163 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004164
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004165 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004166 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004167
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004168 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004169 VISIT(c, expr, e->v.FormattedValue.value);
4170
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004171 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004172 case 's': oparg = FVC_STR; break;
4173 case 'r': oparg = FVC_REPR; break;
4174 case 'a': oparg = FVC_ASCII; break;
4175 case -1: oparg = FVC_NONE; break;
4176 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004177 PyErr_Format(PyExc_SystemError,
4178 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004179 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004180 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004181 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004182 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004183 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004184 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004185 }
4186
Eric V. Smitha78c7952015-11-03 12:45:05 -05004187 /* And push our opcode and oparg */
4188 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004189
Eric V. Smith235a6f02015-09-19 14:51:32 -04004190 return 1;
4191}
4192
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004193static int
4194compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4195{
4196 Py_ssize_t i, n = end - begin;
4197 keyword_ty kw;
4198 PyObject *keys, *key;
4199 assert(n > 0);
4200 if (n > 1) {
4201 for (i = begin; i < end; i++) {
4202 kw = asdl_seq_GET(keywords, i);
4203 VISIT(c, expr, kw->value);
4204 }
4205 keys = PyTuple_New(n);
4206 if (keys == NULL) {
4207 return 0;
4208 }
4209 for (i = begin; i < end; i++) {
4210 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4211 Py_INCREF(key);
4212 PyTuple_SET_ITEM(keys, i - begin, key);
4213 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004214 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004215 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4216 }
4217 else {
4218 /* a for loop only executes once */
4219 for (i = begin; i < end; i++) {
4220 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004221 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004222 VISIT(c, expr, kw->value);
4223 }
4224 ADDOP_I(c, BUILD_MAP, n);
4225 }
4226 return 1;
4227}
4228
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004229/* shared code between compiler_call and compiler_class */
4230static int
4231compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004232 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004233 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004234 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004235{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004236 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004237
Pablo Galindo254ec782020-04-03 20:37:13 +01004238 if (validate_keywords(c, keywords) == -1) {
4239 return 0;
4240 }
4241
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004242 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004243 nkwelts = asdl_seq_LEN(keywords);
4244
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004245 for (i = 0; i < nelts; i++) {
4246 expr_ty elt = asdl_seq_GET(args, i);
4247 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004248 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004249 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004250 }
4251 for (i = 0; i < nkwelts; i++) {
4252 keyword_ty kw = asdl_seq_GET(keywords, i);
4253 if (kw->arg == NULL) {
4254 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004257
Mark Shannon13bc1392020-01-23 09:25:17 +00004258 /* No * or ** args, so can use faster calling sequence */
4259 for (i = 0; i < nelts; i++) {
4260 expr_ty elt = asdl_seq_GET(args, i);
4261 assert(elt->kind != Starred_kind);
4262 VISIT(c, expr, elt);
4263 }
4264 if (nkwelts) {
4265 PyObject *names;
4266 VISIT_SEQ(c, keyword, keywords);
4267 names = PyTuple_New(nkwelts);
4268 if (names == NULL) {
4269 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004270 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004271 for (i = 0; i < nkwelts; i++) {
4272 keyword_ty kw = asdl_seq_GET(keywords, i);
4273 Py_INCREF(kw->arg);
4274 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004275 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004276 ADDOP_LOAD_CONST_NEW(c, names);
4277 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4278 return 1;
4279 }
4280 else {
4281 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4282 return 1;
4283 }
4284
4285ex_call:
4286
4287 /* Do positional arguments. */
4288 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4289 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4290 }
4291 else if (starunpack_helper(c, args, n, BUILD_LIST,
4292 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4293 return 0;
4294 }
4295 /* Then keyword arguments */
4296 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004297 /* Has a new dict been pushed */
4298 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004299
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004300 nseen = 0; /* the number of keyword arguments on the stack following */
4301 for (i = 0; i < nkwelts; i++) {
4302 keyword_ty kw = asdl_seq_GET(keywords, i);
4303 if (kw->arg == NULL) {
4304 /* A keyword argument unpacking. */
4305 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004307 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004308 }
Mark Shannondb64f122020-06-01 10:42:42 +01004309 if (have_dict) {
4310 ADDOP_I(c, DICT_MERGE, 1);
4311 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004312 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004313 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004314 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 if (!have_dict) {
4316 ADDOP_I(c, BUILD_MAP, 0);
4317 have_dict = 1;
4318 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004319 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004320 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004321 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004322 else {
4323 nseen++;
4324 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004325 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004326 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004327 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004328 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004329 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004330 }
4331 if (have_dict) {
4332 ADDOP_I(c, DICT_MERGE, 1);
4333 }
4334 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004335 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004336 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004338 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340}
4341
Nick Coghlan650f0d02007-04-15 12:05:43 +00004342
4343/* List and set comprehensions and generator expressions work by creating a
4344 nested function to perform the actual iteration. This means that the
4345 iteration variables don't leak into the current scope.
4346 The defined function is called immediately following its definition, with the
4347 result of that call being the result of the expression.
4348 The LC/SC version returns the populated container, while the GE version is
4349 flagged in symtable.c as a generator, so it returns the generator object
4350 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004351
4352 Possible cleanups:
4353 - iterate over the generator sequence instead of using recursion
4354*/
4355
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004356
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004357static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358compiler_comprehension_generator(struct compiler *c,
4359 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004360 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004362{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004363 comprehension_ty gen;
4364 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4365 if (gen->is_async) {
4366 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004367 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 } else {
4369 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004370 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004371 }
4372}
4373
4374static int
4375compiler_sync_comprehension_generator(struct compiler *c,
4376 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004377 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004378 expr_ty elt, expr_ty val, int type)
4379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 /* generate code for the iterator, then each of the ifs,
4381 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 comprehension_ty gen;
4384 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004385 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 start = compiler_new_block(c);
4388 skip = compiler_new_block(c);
4389 if_cleanup = compiler_new_block(c);
4390 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4393 anchor == NULL)
4394 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 if (gen_index == 0) {
4399 /* Receive outermost iter as an implicit argument */
4400 c->u->u_argcount = 1;
4401 ADDOP_I(c, LOAD_FAST, 0);
4402 }
4403 else {
4404 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004405 /* Fast path for the temporary variable assignment idiom:
4406 for y in [f(x)]
4407 */
4408 asdl_seq *elts;
4409 switch (gen->iter->kind) {
4410 case List_kind:
4411 elts = gen->iter->v.List.elts;
4412 break;
4413 case Tuple_kind:
4414 elts = gen->iter->v.Tuple.elts;
4415 break;
4416 default:
4417 elts = NULL;
4418 }
4419 if (asdl_seq_LEN(elts) == 1) {
4420 expr_ty elt = asdl_seq_GET(elts, 0);
4421 if (elt->kind != Starred_kind) {
4422 VISIT(c, expr, elt);
4423 start = NULL;
4424 }
4425 }
4426 if (start) {
4427 VISIT(c, expr, gen->iter);
4428 ADDOP(c, GET_ITER);
4429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004431 if (start) {
4432 depth++;
4433 compiler_use_next_block(c, start);
4434 ADDOP_JREL(c, FOR_ITER, anchor);
4435 NEXT_BLOCK(c);
4436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 /* XXX this needs to be cleaned up...a lot! */
4440 n = asdl_seq_LEN(gen->ifs);
4441 for (i = 0; i < n; i++) {
4442 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004443 if (!compiler_jump_if(c, e, if_cleanup, 0))
4444 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 NEXT_BLOCK(c);
4446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 if (++gen_index < asdl_seq_LEN(generators))
4449 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004450 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 elt, val, type))
4452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 /* only append after the last for generator */
4455 if (gen_index >= asdl_seq_LEN(generators)) {
4456 /* comprehension specific code */
4457 switch (type) {
4458 case COMP_GENEXP:
4459 VISIT(c, expr, elt);
4460 ADDOP(c, YIELD_VALUE);
4461 ADDOP(c, POP_TOP);
4462 break;
4463 case COMP_LISTCOMP:
4464 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004465 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 break;
4467 case COMP_SETCOMP:
4468 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004469 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 break;
4471 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004472 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004475 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004476 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 break;
4478 default:
4479 return 0;
4480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 compiler_use_next_block(c, skip);
4483 }
4484 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004485 if (start) {
4486 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4487 compiler_use_next_block(c, anchor);
4488 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489
4490 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004491}
4492
4493static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494compiler_async_comprehension_generator(struct compiler *c,
4495 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004496 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497 expr_ty elt, expr_ty val, int type)
4498{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004499 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004500 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004501 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004502 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004504 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004505
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004506 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507 return 0;
4508 }
4509
4510 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4511
4512 if (gen_index == 0) {
4513 /* Receive outermost iter as an implicit argument */
4514 c->u->u_argcount = 1;
4515 ADDOP_I(c, LOAD_FAST, 0);
4516 }
4517 else {
4518 /* Sub-iter - calculate on the fly */
4519 VISIT(c, expr, gen->iter);
4520 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521 }
4522
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004523 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004525 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004527 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004530 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531
4532 n = asdl_seq_LEN(gen->ifs);
4533 for (i = 0; i < n; i++) {
4534 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004535 if (!compiler_jump_if(c, e, if_cleanup, 0))
4536 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 NEXT_BLOCK(c);
4538 }
4539
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004540 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004541 if (++gen_index < asdl_seq_LEN(generators))
4542 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004543 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004544 elt, val, type))
4545 return 0;
4546
4547 /* only append after the last for generator */
4548 if (gen_index >= asdl_seq_LEN(generators)) {
4549 /* comprehension specific code */
4550 switch (type) {
4551 case COMP_GENEXP:
4552 VISIT(c, expr, elt);
4553 ADDOP(c, YIELD_VALUE);
4554 ADDOP(c, POP_TOP);
4555 break;
4556 case COMP_LISTCOMP:
4557 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004558 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559 break;
4560 case COMP_SETCOMP:
4561 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004562 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004563 break;
4564 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004565 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004566 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004567 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004568 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004569 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004570 break;
4571 default:
4572 return 0;
4573 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 }
4575 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004576 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4577
4578 compiler_use_next_block(c, except);
4579 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004580
4581 return 1;
4582}
4583
4584static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004585compiler_comprehension(struct compiler *c, expr_ty e, int type,
4586 identifier name, asdl_seq *generators, expr_ty elt,
4587 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004591 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004592 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004593
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004594 if (IS_TOP_LEVEL_AWAIT(c)) {
4595 c->u->u_ste->ste_coroutine = 1;
4596 }
4597 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004598
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004599 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004600 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4601 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004602 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004604 }
4605
4606 is_async_generator = c->u->u_ste->ste_coroutine;
4607
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004608 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004609 compiler_error(c, "asynchronous comprehension outside of "
4610 "an asynchronous function");
4611 goto error_in_scope;
4612 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 if (type != COMP_GENEXP) {
4615 int op;
4616 switch (type) {
4617 case COMP_LISTCOMP:
4618 op = BUILD_LIST;
4619 break;
4620 case COMP_SETCOMP:
4621 op = BUILD_SET;
4622 break;
4623 case COMP_DICTCOMP:
4624 op = BUILD_MAP;
4625 break;
4626 default:
4627 PyErr_Format(PyExc_SystemError,
4628 "unknown comprehension type %d", type);
4629 goto error_in_scope;
4630 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 ADDOP_I(c, op, 0);
4633 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004634
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004635 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 val, type))
4637 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 if (type != COMP_GENEXP) {
4640 ADDOP(c, RETURN_VALUE);
4641 }
4642
4643 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004644 qualname = c->u->u_qualname;
4645 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004647 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 goto error;
4649
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004650 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004652 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 Py_DECREF(co);
4654
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004655 VISIT(c, expr, outermost->iter);
4656
4657 if (outermost->is_async) {
4658 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004659 } else {
4660 ADDOP(c, GET_ITER);
4661 }
4662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004664
4665 if (is_async_generator && type != COMP_GENEXP) {
4666 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004667 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004668 ADDOP(c, YIELD_FROM);
4669 }
4670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004672error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004674error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004675 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 Py_XDECREF(co);
4677 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004678}
4679
4680static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004681compiler_genexp(struct compiler *c, expr_ty e)
4682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 static identifier name;
4684 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004685 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 if (!name)
4687 return 0;
4688 }
4689 assert(e->kind == GeneratorExp_kind);
4690 return compiler_comprehension(c, e, COMP_GENEXP, name,
4691 e->v.GeneratorExp.generators,
4692 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004693}
4694
4695static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004696compiler_listcomp(struct compiler *c, expr_ty e)
4697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 static identifier name;
4699 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004700 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 if (!name)
4702 return 0;
4703 }
4704 assert(e->kind == ListComp_kind);
4705 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4706 e->v.ListComp.generators,
4707 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004708}
4709
4710static int
4711compiler_setcomp(struct compiler *c, expr_ty e)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 static identifier name;
4714 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004715 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!name)
4717 return 0;
4718 }
4719 assert(e->kind == SetComp_kind);
4720 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4721 e->v.SetComp.generators,
4722 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004723}
4724
4725
4726static int
4727compiler_dictcomp(struct compiler *c, expr_ty e)
4728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 static identifier name;
4730 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004731 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 if (!name)
4733 return 0;
4734 }
4735 assert(e->kind == DictComp_kind);
4736 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4737 e->v.DictComp.generators,
4738 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004739}
4740
4741
4742static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004743compiler_visit_keyword(struct compiler *c, keyword_ty k)
4744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 VISIT(c, expr, k->value);
4746 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004747}
4748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004750 whether they are true or false.
4751
4752 Return values: 1 for true, 0 for false, -1 for non-constant.
4753 */
4754
4755static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004756expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004757{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004758 if (e->kind == Constant_kind) {
4759 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004760 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004761 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004762}
4763
Mark Shannonfee55262019-11-21 09:11:43 +00004764static int
4765compiler_with_except_finish(struct compiler *c) {
4766 basicblock *exit;
4767 exit = compiler_new_block(c);
4768 if (exit == NULL)
4769 return 0;
4770 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4771 ADDOP(c, RERAISE);
4772 compiler_use_next_block(c, exit);
4773 ADDOP(c, POP_TOP);
4774 ADDOP(c, POP_TOP);
4775 ADDOP(c, POP_TOP);
4776 ADDOP(c, POP_EXCEPT);
4777 ADDOP(c, POP_TOP);
4778 return 1;
4779}
Yury Selivanov75445082015-05-11 22:57:16 -04004780
4781/*
4782 Implements the async with statement.
4783
4784 The semantics outlined in that PEP are as follows:
4785
4786 async with EXPR as VAR:
4787 BLOCK
4788
4789 It is implemented roughly as:
4790
4791 context = EXPR
4792 exit = context.__aexit__ # not calling it
4793 value = await context.__aenter__()
4794 try:
4795 VAR = value # if VAR present in the syntax
4796 BLOCK
4797 finally:
4798 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004799 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004800 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004801 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004802 if not (await exit(*exc)):
4803 raise
4804 */
4805static int
4806compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4807{
Mark Shannonfee55262019-11-21 09:11:43 +00004808 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004809 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4810
4811 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004812 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004813 c->u->u_ste->ste_coroutine = 1;
4814 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004815 return compiler_error(c, "'async with' outside async function");
4816 }
Yury Selivanov75445082015-05-11 22:57:16 -04004817
4818 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004819 final = compiler_new_block(c);
4820 exit = compiler_new_block(c);
4821 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004822 return 0;
4823
4824 /* Evaluate EXPR */
4825 VISIT(c, expr, item->context_expr);
4826
4827 ADDOP(c, BEFORE_ASYNC_WITH);
4828 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004829 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004830 ADDOP(c, YIELD_FROM);
4831
Mark Shannonfee55262019-11-21 09:11:43 +00004832 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004833
4834 /* SETUP_ASYNC_WITH pushes a finally block. */
4835 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004836 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004837 return 0;
4838 }
4839
4840 if (item->optional_vars) {
4841 VISIT(c, expr, item->optional_vars);
4842 }
4843 else {
4844 /* Discard result from context.__aenter__() */
4845 ADDOP(c, POP_TOP);
4846 }
4847
4848 pos++;
4849 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4850 /* BLOCK code */
4851 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4852 else if (!compiler_async_with(c, s, pos))
4853 return 0;
4854
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004855 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004856 ADDOP(c, POP_BLOCK);
4857 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004858
Mark Shannonfee55262019-11-21 09:11:43 +00004859 /* For successful outcome:
4860 * call __exit__(None, None, None)
4861 */
4862 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004863 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004864 ADDOP(c, GET_AWAITABLE);
4865 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4866 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004867
Mark Shannonfee55262019-11-21 09:11:43 +00004868 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004869
Mark Shannonfee55262019-11-21 09:11:43 +00004870 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4871
4872 /* For exceptional outcome: */
4873 compiler_use_next_block(c, final);
4874
4875 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004876 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004877 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004878 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004879 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004880
Mark Shannonfee55262019-11-21 09:11:43 +00004881compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004882 return 1;
4883}
4884
4885
Guido van Rossumc2e20742006-02-27 22:32:47 +00004886/*
4887 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004888 with EXPR as VAR:
4889 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004890 is implemented as:
4891 <code for EXPR>
4892 SETUP_WITH E
4893 <code to store to VAR> or POP_TOP
4894 <code for BLOCK>
4895 LOAD_CONST (None, None, None)
4896 CALL_FUNCTION_EX 0
4897 JUMP_FORWARD EXIT
4898 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4899 POP_JUMP_IF_TRUE T:
4900 RERAISE
4901 T: POP_TOP * 3 (remove exception from stack)
4902 POP_EXCEPT
4903 POP_TOP
4904 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004905 */
Mark Shannonfee55262019-11-21 09:11:43 +00004906
Guido van Rossumc2e20742006-02-27 22:32:47 +00004907static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004908compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004909{
Mark Shannonfee55262019-11-21 09:11:43 +00004910 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004911 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004912
4913 assert(s->kind == With_kind);
4914
Guido van Rossumc2e20742006-02-27 22:32:47 +00004915 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004916 final = compiler_new_block(c);
4917 exit = compiler_new_block(c);
4918 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004919 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004920
Thomas Wouters477c8d52006-05-27 19:21:47 +00004921 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004922 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004923 /* Will push bound __exit__ */
4924 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004925
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004926 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004928 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004929 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004930 }
4931
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004932 if (item->optional_vars) {
4933 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004934 }
4935 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004937 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004938 }
4939
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004940 pos++;
4941 if (pos == asdl_seq_LEN(s->v.With.items))
4942 /* BLOCK code */
4943 VISIT_SEQ(c, stmt, s->v.With.body)
4944 else if (!compiler_with(c, s, pos))
4945 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004946
Guido van Rossumc2e20742006-02-27 22:32:47 +00004947 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004948 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004949
Mark Shannonfee55262019-11-21 09:11:43 +00004950 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004951
Mark Shannonfee55262019-11-21 09:11:43 +00004952 /* For successful outcome:
4953 * call __exit__(None, None, None)
4954 */
4955 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004956 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004957 ADDOP(c, POP_TOP);
4958 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004959
Mark Shannonfee55262019-11-21 09:11:43 +00004960 /* For exceptional outcome: */
4961 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004962
Mark Shannonfee55262019-11-21 09:11:43 +00004963 ADDOP(c, WITH_EXCEPT_START);
4964 compiler_with_except_finish(c);
4965
4966 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004967 return 1;
4968}
4969
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004970static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004971compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004973 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004974 case NamedExpr_kind:
4975 VISIT(c, expr, e->v.NamedExpr.value);
4976 ADDOP(c, DUP_TOP);
4977 VISIT(c, expr, e->v.NamedExpr.target);
4978 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 case BoolOp_kind:
4980 return compiler_boolop(c, e);
4981 case BinOp_kind:
4982 VISIT(c, expr, e->v.BinOp.left);
4983 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004984 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 break;
4986 case UnaryOp_kind:
4987 VISIT(c, expr, e->v.UnaryOp.operand);
4988 ADDOP(c, unaryop(e->v.UnaryOp.op));
4989 break;
4990 case Lambda_kind:
4991 return compiler_lambda(c, e);
4992 case IfExp_kind:
4993 return compiler_ifexp(c, e);
4994 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004995 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004997 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 case GeneratorExp_kind:
4999 return compiler_genexp(c, e);
5000 case ListComp_kind:
5001 return compiler_listcomp(c, e);
5002 case SetComp_kind:
5003 return compiler_setcomp(c, e);
5004 case DictComp_kind:
5005 return compiler_dictcomp(c, e);
5006 case Yield_kind:
5007 if (c->u->u_ste->ste_type != FunctionBlock)
5008 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005009 if (e->v.Yield.value) {
5010 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 }
5012 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005013 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005015 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005017 case YieldFrom_kind:
5018 if (c->u->u_ste->ste_type != FunctionBlock)
5019 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005020
5021 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5022 return compiler_error(c, "'yield from' inside async function");
5023
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005024 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005025 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005026 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005027 ADDOP(c, YIELD_FROM);
5028 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005029 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005030 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005031 if (c->u->u_ste->ste_type != FunctionBlock){
5032 return compiler_error(c, "'await' outside function");
5033 }
Yury Selivanov75445082015-05-11 22:57:16 -04005034
Victor Stinner331a6a52019-05-27 16:39:22 +02005035 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005036 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5037 return compiler_error(c, "'await' outside async function");
5038 }
5039 }
Yury Selivanov75445082015-05-11 22:57:16 -04005040
5041 VISIT(c, expr, e->v.Await.value);
5042 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005043 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005044 ADDOP(c, YIELD_FROM);
5045 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 case Compare_kind:
5047 return compiler_compare(c, e);
5048 case Call_kind:
5049 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005050 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005051 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005052 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005053 case JoinedStr_kind:
5054 return compiler_joined_str(c, e);
5055 case FormattedValue_kind:
5056 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 /* The following exprs can be assignment targets. */
5058 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005059 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 case Load:
5062 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5063 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005065 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5066 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5068 break;
5069 case Del:
5070 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5071 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 }
5073 break;
5074 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005075 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 case Starred_kind:
5077 switch (e->v.Starred.ctx) {
5078 case Store:
5079 /* In all legitimate cases, the Starred node was already replaced
5080 * by compiler_list/compiler_tuple. XXX: is that okay? */
5081 return compiler_error(c,
5082 "starred assignment target must be in a list or tuple");
5083 default:
5084 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005085 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005087 break;
5088 case Slice_kind:
5089 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 case Name_kind:
5091 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5092 /* child nodes of List and Tuple will have expr_context set */
5093 case List_kind:
5094 return compiler_list(c, e);
5095 case Tuple_kind:
5096 return compiler_tuple(c, e);
5097 }
5098 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005099}
5100
5101static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005102compiler_visit_expr(struct compiler *c, expr_ty e)
5103{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005104 int old_lineno = c->u->u_lineno;
5105 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005106 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005107 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005108 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005109 c->u->u_col_offset = old_col_offset;
5110 return res;
5111}
5112
5113static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005114compiler_augassign(struct compiler *c, stmt_ty s)
5115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005117 expr_ty e = s->v.AugAssign.target;
5118
5119 int old_lineno = c->u->u_lineno;
5120 int old_col_offset = c->u->u_col_offset;
5121 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 switch (e->kind) {
5124 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005125 VISIT(c, expr, e->v.Attribute.value);
5126 ADDOP(c, DUP_TOP);
5127 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 break;
5129 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005130 VISIT(c, expr, e->v.Subscript.value);
5131 VISIT(c, expr, e->v.Subscript.slice);
5132 ADDOP(c, DUP_TOP_TWO);
5133 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 break;
5135 case Name_kind:
5136 if (!compiler_nameop(c, e->v.Name.id, Load))
5137 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005138 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005139 default:
5140 PyErr_Format(PyExc_SystemError,
5141 "invalid node type (%d) for augmented assignment",
5142 e->kind);
5143 return 0;
5144 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005145
5146 c->u->u_lineno = old_lineno;
5147 c->u->u_col_offset = old_col_offset;
5148
5149 VISIT(c, expr, s->v.AugAssign.value);
5150 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5151
5152 SET_LOC(c, e);
5153
5154 switch (e->kind) {
5155 case Attribute_kind:
5156 ADDOP(c, ROT_TWO);
5157 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5158 break;
5159 case Subscript_kind:
5160 ADDOP(c, ROT_THREE);
5161 ADDOP(c, STORE_SUBSCR);
5162 break;
5163 case Name_kind:
5164 return compiler_nameop(c, e->v.Name.id, Store);
5165 default:
5166 Py_UNREACHABLE();
5167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005169}
5170
5171static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005172check_ann_expr(struct compiler *c, expr_ty e)
5173{
5174 VISIT(c, expr, e);
5175 ADDOP(c, POP_TOP);
5176 return 1;
5177}
5178
5179static int
5180check_annotation(struct compiler *c, stmt_ty s)
5181{
5182 /* Annotations are only evaluated in a module or class. */
5183 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5184 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5185 return check_ann_expr(c, s->v.AnnAssign.annotation);
5186 }
5187 return 1;
5188}
5189
5190static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005191check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005192{
5193 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005194 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005195 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005196 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197 return 0;
5198 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005199 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5200 return 0;
5201 }
5202 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5203 return 0;
5204 }
5205 return 1;
5206 case Tuple_kind: {
5207 /* extended slice */
5208 asdl_seq *elts = e->v.Tuple.elts;
5209 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005210 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005211 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005212 return 0;
5213 }
5214 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005215 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005216 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005217 default:
5218 return check_ann_expr(c, e);
5219 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220}
5221
5222static int
5223compiler_annassign(struct compiler *c, stmt_ty s)
5224{
5225 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005226 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005227
5228 assert(s->kind == AnnAssign_kind);
5229
5230 /* We perform the actual assignment first. */
5231 if (s->v.AnnAssign.value) {
5232 VISIT(c, expr, s->v.AnnAssign.value);
5233 VISIT(c, expr, targ);
5234 }
5235 switch (targ->kind) {
5236 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005237 if (forbidden_name(c, targ->v.Name.id, Store))
5238 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005239 /* If we have a simple name in a module or class, store annotation. */
5240 if (s->v.AnnAssign.simple &&
5241 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5242 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005243 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5244 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5245 }
5246 else {
5247 VISIT(c, expr, s->v.AnnAssign.annotation);
5248 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005249 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005250 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005251 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005252 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005253 }
5254 break;
5255 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005256 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5257 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005258 if (!s->v.AnnAssign.value &&
5259 !check_ann_expr(c, targ->v.Attribute.value)) {
5260 return 0;
5261 }
5262 break;
5263 case Subscript_kind:
5264 if (!s->v.AnnAssign.value &&
5265 (!check_ann_expr(c, targ->v.Subscript.value) ||
5266 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5267 return 0;
5268 }
5269 break;
5270 default:
5271 PyErr_Format(PyExc_SystemError,
5272 "invalid node type (%d) for annotated assignment",
5273 targ->kind);
5274 return 0;
5275 }
5276 /* Annotation is evaluated last. */
5277 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5278 return 0;
5279 }
5280 return 1;
5281}
5282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005283/* Raises a SyntaxError and returns 0.
5284 If something goes wrong, a different exception may be raised.
5285*/
5286
5287static int
5288compiler_error(struct compiler *c, const char *errstr)
5289{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005290 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005292
Victor Stinner14e461d2013-08-26 22:28:21 +02005293 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005294 if (!loc) {
5295 Py_INCREF(Py_None);
5296 loc = Py_None;
5297 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005298 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005299 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 if (!u)
5301 goto exit;
5302 v = Py_BuildValue("(zO)", errstr, u);
5303 if (!v)
5304 goto exit;
5305 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005306 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 Py_DECREF(loc);
5308 Py_XDECREF(u);
5309 Py_XDECREF(v);
5310 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005311}
5312
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005313/* Emits a SyntaxWarning and returns 1 on success.
5314 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5315 and returns 0.
5316*/
5317static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005318compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005319{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005320 va_list vargs;
5321#ifdef HAVE_STDARG_PROTOTYPES
5322 va_start(vargs, format);
5323#else
5324 va_start(vargs);
5325#endif
5326 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5327 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005328 if (msg == NULL) {
5329 return 0;
5330 }
5331 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5332 c->u->u_lineno, NULL, NULL) < 0)
5333 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005334 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005335 /* Replace the SyntaxWarning exception with a SyntaxError
5336 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005337 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005338 assert(PyUnicode_AsUTF8(msg) != NULL);
5339 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005340 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005341 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005342 return 0;
5343 }
5344 Py_DECREF(msg);
5345 return 1;
5346}
5347
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005348static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005349compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005351 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005353
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005354 if (ctx == Load) {
5355 if (!check_subscripter(c, e->v.Subscript.value)) {
5356 return 0;
5357 }
5358 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5359 return 0;
5360 }
5361 }
5362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 case Store: op = STORE_SUBSCR; break;
5366 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005368 assert(op);
5369 VISIT(c, expr, e->v.Subscript.value);
5370 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 ADDOP(c, op);
5372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373}
5374
5375static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005376compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 int n = 2;
5379 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 /* only handles the cases where BUILD_SLICE is emitted */
5382 if (s->v.Slice.lower) {
5383 VISIT(c, expr, s->v.Slice.lower);
5384 }
5385 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005386 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 if (s->v.Slice.upper) {
5390 VISIT(c, expr, s->v.Slice.upper);
5391 }
5392 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005393 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 }
5395
5396 if (s->v.Slice.step) {
5397 n++;
5398 VISIT(c, expr, s->v.Slice.step);
5399 }
5400 ADDOP_I(c, BUILD_SLICE, n);
5401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402}
5403
Thomas Wouters89f507f2006-12-13 04:49:30 +00005404/* End of the compiler section, beginning of the assembler section */
5405
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005406/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005407 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408
5409 XXX must handle implicit jumps from one block to next
5410*/
5411
Thomas Wouters89f507f2006-12-13 04:49:30 +00005412struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 PyObject *a_bytecode; /* string containing bytecode */
5414 int a_offset; /* offset into bytecode */
5415 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005416 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 PyObject *a_lnotab; /* string containing lnotab */
5418 int a_lnotab_off; /* offset into lnotab */
5419 int a_lineno; /* last lineno of emitted instruction */
5420 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005421};
5422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005423static void
T. Wouters99b54d62019-09-12 07:05:33 -07005424dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425{
T. Wouters99b54d62019-09-12 07:05:33 -07005426 int i, j;
5427
5428 /* Get rid of recursion for normal control flow.
5429 Since the number of blocks is limited, unused space in a_postorder
5430 (from a_nblocks to end) can be used as a stack for still not ordered
5431 blocks. */
5432 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005433 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005434 assert(a->a_nblocks < j);
5435 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 }
T. Wouters99b54d62019-09-12 07:05:33 -07005437 while (j < end) {
5438 b = a->a_postorder[j++];
5439 for (i = 0; i < b->b_iused; i++) {
5440 struct instr *instr = &b->b_instr[i];
5441 if (instr->i_jrel || instr->i_jabs)
5442 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005443 }
T. Wouters99b54d62019-09-12 07:05:33 -07005444 assert(a->a_nblocks < j);
5445 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447}
5448
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005449Py_LOCAL_INLINE(void)
5450stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005452 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005453 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005454 assert(b->b_startdepth < 0);
5455 b->b_startdepth = depth;
5456 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458}
5459
5460/* Find the flow path that needs the largest stack. We assume that
5461 * cycles in the flow graph have no net effect on the stack depth.
5462 */
5463static int
5464stackdepth(struct compiler *c)
5465{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005466 basicblock *b, *entryblock = NULL;
5467 basicblock **stack, **sp;
5468 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 b->b_startdepth = INT_MIN;
5471 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005472 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 }
5474 if (!entryblock)
5475 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005476 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5477 if (!stack) {
5478 PyErr_NoMemory();
5479 return -1;
5480 }
5481
5482 sp = stack;
5483 stackdepth_push(&sp, entryblock, 0);
5484 while (sp != stack) {
5485 b = *--sp;
5486 int depth = b->b_startdepth;
5487 assert(depth >= 0);
5488 basicblock *next = b->b_next;
5489 for (int i = 0; i < b->b_iused; i++) {
5490 struct instr *instr = &b->b_instr[i];
5491 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5492 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005493 _Py_FatalErrorFormat(__func__,
5494 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005495 }
5496 int new_depth = depth + effect;
5497 if (new_depth > maxdepth) {
5498 maxdepth = new_depth;
5499 }
5500 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5501 if (instr->i_jrel || instr->i_jabs) {
5502 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5503 assert(effect != PY_INVALID_STACK_EFFECT);
5504 int target_depth = depth + effect;
5505 if (target_depth > maxdepth) {
5506 maxdepth = target_depth;
5507 }
5508 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005509 stackdepth_push(&sp, instr->i_target, target_depth);
5510 }
5511 depth = new_depth;
5512 if (instr->i_opcode == JUMP_ABSOLUTE ||
5513 instr->i_opcode == JUMP_FORWARD ||
5514 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005515 instr->i_opcode == RAISE_VARARGS ||
5516 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005517 {
5518 /* remaining code is dead */
5519 next = NULL;
5520 break;
5521 }
5522 }
5523 if (next != NULL) {
5524 stackdepth_push(&sp, next, depth);
5525 }
5526 }
5527 PyObject_Free(stack);
5528 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005529}
5530
5531static int
5532assemble_init(struct assembler *a, int nblocks, int firstlineno)
5533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 memset(a, 0, sizeof(struct assembler));
5535 a->a_lineno = firstlineno;
5536 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5537 if (!a->a_bytecode)
5538 return 0;
5539 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5540 if (!a->a_lnotab)
5541 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005542 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 PyErr_NoMemory();
5544 return 0;
5545 }
T. Wouters99b54d62019-09-12 07:05:33 -07005546 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005548 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 PyErr_NoMemory();
5550 return 0;
5551 }
5552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005553}
5554
5555static void
5556assemble_free(struct assembler *a)
5557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 Py_XDECREF(a->a_bytecode);
5559 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005560 if (a->a_postorder)
5561 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005562}
5563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005564static int
5565blocksize(basicblock *b)
5566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 int i;
5568 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005571 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005572 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005573}
5574
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005575/* Appends a pair to the end of the line number table, a_lnotab, representing
5576 the instruction's bytecode offset and line number. See
5577 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005578
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005579static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005580assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005583 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005587 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005589 }
5590
5591 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5592 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 if (d_bytecode > 255) {
5595 int j, nbytes, ncodes = d_bytecode / 255;
5596 nbytes = a->a_lnotab_off + 2 * ncodes;
5597 len = PyBytes_GET_SIZE(a->a_lnotab);
5598 if (nbytes >= len) {
5599 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5600 len = nbytes;
5601 else if (len <= INT_MAX / 2)
5602 len *= 2;
5603 else {
5604 PyErr_NoMemory();
5605 return 0;
5606 }
5607 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5608 return 0;
5609 }
5610 lnotab = (unsigned char *)
5611 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5612 for (j = 0; j < ncodes; j++) {
5613 *lnotab++ = 255;
5614 *lnotab++ = 0;
5615 }
5616 d_bytecode -= ncodes * 255;
5617 a->a_lnotab_off += ncodes * 2;
5618 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005619 assert(0 <= d_bytecode && d_bytecode <= 255);
5620
5621 if (d_lineno < -128 || 127 < d_lineno) {
5622 int j, nbytes, ncodes, k;
5623 if (d_lineno < 0) {
5624 k = -128;
5625 /* use division on positive numbers */
5626 ncodes = (-d_lineno) / 128;
5627 }
5628 else {
5629 k = 127;
5630 ncodes = d_lineno / 127;
5631 }
5632 d_lineno -= ncodes * k;
5633 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 nbytes = a->a_lnotab_off + 2 * ncodes;
5635 len = PyBytes_GET_SIZE(a->a_lnotab);
5636 if (nbytes >= len) {
5637 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5638 len = nbytes;
5639 else if (len <= INT_MAX / 2)
5640 len *= 2;
5641 else {
5642 PyErr_NoMemory();
5643 return 0;
5644 }
5645 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5646 return 0;
5647 }
5648 lnotab = (unsigned char *)
5649 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5650 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005651 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 d_bytecode = 0;
5653 for (j = 1; j < ncodes; j++) {
5654 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005655 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005657 a->a_lnotab_off += ncodes * 2;
5658 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005659 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 len = PyBytes_GET_SIZE(a->a_lnotab);
5662 if (a->a_lnotab_off + 2 >= len) {
5663 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5664 return 0;
5665 }
5666 lnotab = (unsigned char *)
5667 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 a->a_lnotab_off += 2;
5670 if (d_bytecode) {
5671 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005672 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 }
5674 else { /* First line of a block; def stmt, etc. */
5675 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005676 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 }
5678 a->a_lineno = i->i_lineno;
5679 a->a_lineno_off = a->a_offset;
5680 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005681}
5682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005683/* assemble_emit()
5684 Extend the bytecode with a new instruction.
5685 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005686*/
5687
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005688static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005689assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005690{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005691 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005693 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005694
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005695 arg = i->i_oparg;
5696 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 if (i->i_lineno && !assemble_lnotab(a, i))
5698 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005699 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 if (len > PY_SSIZE_T_MAX / 2)
5701 return 0;
5702 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5703 return 0;
5704 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005705 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005707 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005709}
5710
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005711static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005712assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005716 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 /* Compute the size of each block and fixup jump args.
5719 Replace block pointer with position in bytecode. */
5720 do {
5721 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005722 for (i = a->a_nblocks - 1; i >= 0; i--) {
5723 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 bsize = blocksize(b);
5725 b->b_offset = totsize;
5726 totsize += bsize;
5727 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005728 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005729 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5730 bsize = b->b_offset;
5731 for (i = 0; i < b->b_iused; i++) {
5732 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005733 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 /* Relative jumps are computed relative to
5735 the instruction pointer after fetching
5736 the jump instruction.
5737 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005738 bsize += isize;
5739 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005741 if (instr->i_jrel) {
5742 instr->i_oparg -= bsize;
5743 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005744 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005745 if (instrsize(instr->i_oparg) != isize) {
5746 extended_arg_recompile = 1;
5747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 }
5750 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 /* XXX: This is an awful hack that could hurt performance, but
5753 on the bright side it should work until we come up
5754 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005756 The issue is that in the first loop blocksize() is called
5757 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005758 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 So we loop until we stop seeing new EXTENDED_ARGs.
5762 The only EXTENDED_ARGs that could be popping up are
5763 ones in jump instructions. So this should converge
5764 fairly quickly.
5765 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005766 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005767}
5768
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005769static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005770dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005773 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 tuple = PyTuple_New(size);
5776 if (tuple == NULL)
5777 return NULL;
5778 while (PyDict_Next(dict, &pos, &k, &v)) {
5779 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005780 Py_INCREF(k);
5781 assert((i - offset) < size);
5782 assert((i - offset) >= 0);
5783 PyTuple_SET_ITEM(tuple, i - offset, k);
5784 }
5785 return tuple;
5786}
5787
5788static PyObject *
5789consts_dict_keys_inorder(PyObject *dict)
5790{
5791 PyObject *consts, *k, *v;
5792 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5793
5794 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5795 if (consts == NULL)
5796 return NULL;
5797 while (PyDict_Next(dict, &pos, &k, &v)) {
5798 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005799 /* The keys of the dictionary can be tuples wrapping a contant.
5800 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5801 * the object we want is always second. */
5802 if (PyTuple_CheckExact(k)) {
5803 k = PyTuple_GET_ITEM(k, 1);
5804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005806 assert(i < size);
5807 assert(i >= 0);
5808 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005810 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005811}
5812
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005813static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005814compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005817 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005819 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 if (ste->ste_nested)
5821 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005822 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005824 if (!ste->ste_generator && ste->ste_coroutine)
5825 flags |= CO_COROUTINE;
5826 if (ste->ste_generator && ste->ste_coroutine)
5827 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 if (ste->ste_varargs)
5829 flags |= CO_VARARGS;
5830 if (ste->ste_varkeywords)
5831 flags |= CO_VARKEYWORDS;
5832 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 /* (Only) inherit compilerflags in PyCF_MASK */
5835 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005836
Pablo Galindo90235812020-03-15 04:29:22 +00005837 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005838 ste->ste_coroutine &&
5839 !ste->ste_generator) {
5840 flags |= CO_COROUTINE;
5841 }
5842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005844}
5845
INADA Naokic2e16072018-11-26 21:23:22 +09005846// Merge *tuple* with constant cache.
5847// Unlike merge_consts_recursive(), this function doesn't work recursively.
5848static int
5849merge_const_tuple(struct compiler *c, PyObject **tuple)
5850{
5851 assert(PyTuple_CheckExact(*tuple));
5852
5853 PyObject *key = _PyCode_ConstantKey(*tuple);
5854 if (key == NULL) {
5855 return 0;
5856 }
5857
5858 // t is borrowed reference
5859 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5860 Py_DECREF(key);
5861 if (t == NULL) {
5862 return 0;
5863 }
5864 if (t == key) { // tuple is new constant.
5865 return 1;
5866 }
5867
5868 PyObject *u = PyTuple_GET_ITEM(t, 1);
5869 Py_INCREF(u);
5870 Py_DECREF(*tuple);
5871 *tuple = u;
5872 return 1;
5873}
5874
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005875static PyCodeObject *
5876makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878 PyObject *tmp;
5879 PyCodeObject *co = NULL;
5880 PyObject *consts = NULL;
5881 PyObject *names = NULL;
5882 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005883 PyObject *name = NULL;
5884 PyObject *freevars = NULL;
5885 PyObject *cellvars = NULL;
5886 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005887 Py_ssize_t nlocals;
5888 int nlocals_int;
5889 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005890 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005891
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005892 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 names = dict_keys_inorder(c->u->u_names, 0);
5894 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5895 if (!consts || !names || !varnames)
5896 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5899 if (!cellvars)
5900 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005901 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 if (!freevars)
5903 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005904
INADA Naokic2e16072018-11-26 21:23:22 +09005905 if (!merge_const_tuple(c, &names) ||
5906 !merge_const_tuple(c, &varnames) ||
5907 !merge_const_tuple(c, &cellvars) ||
5908 !merge_const_tuple(c, &freevars))
5909 {
5910 goto error;
5911 }
5912
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005913 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005914 assert(nlocals < INT_MAX);
5915 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 flags = compute_code_flags(c);
5918 if (flags < 0)
5919 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5922 if (!bytecode)
5923 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5926 if (!tmp)
5927 goto error;
5928 Py_DECREF(consts);
5929 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005930 if (!merge_const_tuple(c, &consts)) {
5931 goto error;
5932 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005934 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005935 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005936 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005937 maxdepth = stackdepth(c);
5938 if (maxdepth < 0) {
5939 goto error;
5940 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005941 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005942 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005943 maxdepth, flags, bytecode, consts, names,
5944 varnames, freevars, cellvars, c->c_filename,
5945 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005946 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005947 Py_XDECREF(consts);
5948 Py_XDECREF(names);
5949 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 Py_XDECREF(name);
5951 Py_XDECREF(freevars);
5952 Py_XDECREF(cellvars);
5953 Py_XDECREF(bytecode);
5954 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005955}
5956
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005957
5958/* For debugging purposes only */
5959#if 0
5960static void
5961dump_instr(const struct instr *i)
5962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005963 const char *jrel = i->i_jrel ? "jrel " : "";
5964 const char *jabs = i->i_jabs ? "jabs " : "";
5965 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005968 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5972 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005973}
5974
5975static void
5976dump_basicblock(const basicblock *b)
5977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 const char *seen = b->b_seen ? "seen " : "";
5979 const char *b_return = b->b_return ? "return " : "";
5980 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5981 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5982 if (b->b_instr) {
5983 int i;
5984 for (i = 0; i < b->b_iused; i++) {
5985 fprintf(stderr, " [%02d] ", i);
5986 dump_instr(b->b_instr + i);
5987 }
5988 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005989}
5990#endif
5991
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005992static PyCodeObject *
5993assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 basicblock *b, *entryblock;
5996 struct assembler a;
5997 int i, j, nblocks;
5998 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006000 /* Make sure every block that falls off the end returns None.
6001 XXX NEXT_BLOCK() isn't quite right, because if the last
6002 block ends with a jump or return b_next shouldn't set.
6003 */
6004 if (!c->u->u_curblock->b_return) {
6005 NEXT_BLOCK(c);
6006 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006007 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006008 ADDOP(c, RETURN_VALUE);
6009 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 nblocks = 0;
6012 entryblock = NULL;
6013 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6014 nblocks++;
6015 entryblock = b;
6016 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 /* Set firstlineno if it wasn't explicitly set. */
6019 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006020 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006021 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
6022 else
6023 c->u->u_firstlineno = 1;
6024 }
6025 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6026 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07006027 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 /* Can't modify the bytecode after computing jump offsets. */
6030 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006031
T. Wouters99b54d62019-09-12 07:05:33 -07006032 /* Emit code in reverse postorder from dfs. */
6033 for (i = a.a_nblocks - 1; i >= 0; i--) {
6034 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006035 for (j = 0; j < b->b_iused; j++)
6036 if (!assemble_emit(&a, &b->b_instr[j]))
6037 goto error;
6038 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006040 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6041 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006042 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006043 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006046 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006047 assemble_free(&a);
6048 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006049}
Georg Brandl8334fd92010-12-04 10:26:46 +00006050
6051#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006052PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006053PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6054 PyArena *arena)
6055{
6056 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6057}