blob: 54e6516b3ad01de6b69233e2ada351aeb4e1bed4 [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
393PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394PyNode_Compile(struct _node *n, const char *filename)
395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyCodeObject *co = NULL;
397 mod_ty mod;
398 PyArena *arena = PyArena_New();
399 if (!arena)
400 return NULL;
401 mod = PyAST_FromNode(n, NULL, filename, arena);
402 if (mod)
403 co = PyAST_Compile(mod, filename, NULL, arena);
404 PyArena_Free(arena);
405 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000406}
407
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000408static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (c->c_st)
412 PySymtable_Free(c->c_st);
413 if (c->c_future)
414 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200415 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900416 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000418}
419
Guido van Rossum79f25d91997-04-29 20:08:16 +0000420static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000421list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_ssize_t i, n;
424 PyObject *v, *k;
425 PyObject *dict = PyDict_New();
426 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 n = PyList_Size(list);
429 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100430 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (!v) {
432 Py_DECREF(dict);
433 return NULL;
434 }
435 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300436 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_DECREF(v);
438 Py_DECREF(dict);
439 return NULL;
440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_DECREF(v);
442 }
443 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444}
445
446/* Return new dict containing names from src that match scope(s).
447
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000448src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450values are integers, starting at offset and increasing by one for
451each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452*/
453
454static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100455dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000456{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700457 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500459 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 assert(offset >= 0);
462 if (dest == NULL)
463 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464
Meador Inge2ca63152012-07-18 14:20:11 -0500465 /* Sort the keys so that we have a deterministic order on the indexes
466 saved in the returned dictionary. These indexes are used as indexes
467 into the free and cell var storage. Therefore if they aren't
468 deterministic, then the generated bytecode is not deterministic.
469 */
470 sorted_keys = PyDict_Keys(src);
471 if (sorted_keys == NULL)
472 return NULL;
473 if (PyList_Sort(sorted_keys) != 0) {
474 Py_DECREF(sorted_keys);
475 return NULL;
476 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500477 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500478
479 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* XXX this should probably be a macro in symtable.h */
481 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500482 k = PyList_GET_ITEM(sorted_keys, key_i);
483 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 assert(PyLong_Check(v));
485 vi = PyLong_AS_LONG(v);
486 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300489 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500491 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_DECREF(dest);
493 return NULL;
494 }
495 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300496 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500497 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_DECREF(item);
499 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return NULL;
501 }
502 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 }
504 }
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000507}
508
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509static void
510compiler_unit_check(struct compiler_unit *u)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 basicblock *block;
513 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700514 assert((uintptr_t)block != 0xcbcbcbcbU);
515 assert((uintptr_t)block != 0xfbfbfbfbU);
516 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (block->b_instr != NULL) {
518 assert(block->b_ialloc > 0);
519 assert(block->b_iused > 0);
520 assert(block->b_ialloc >= block->b_iused);
521 }
522 else {
523 assert (block->b_iused == 0);
524 assert (block->b_ialloc == 0);
525 }
526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527}
528
529static void
530compiler_unit_free(struct compiler_unit *u)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 compiler_unit_check(u);
535 b = u->u_blocks;
536 while (b != NULL) {
537 if (b->b_instr)
538 PyObject_Free((void *)b->b_instr);
539 next = b->b_list;
540 PyObject_Free((void *)b);
541 b = next;
542 }
543 Py_CLEAR(u->u_ste);
544 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400545 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 Py_CLEAR(u->u_consts);
547 Py_CLEAR(u->u_names);
548 Py_CLEAR(u->u_varnames);
549 Py_CLEAR(u->u_freevars);
550 Py_CLEAR(u->u_cellvars);
551 Py_CLEAR(u->u_private);
552 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553}
554
555static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100556compiler_enter_scope(struct compiler *c, identifier name,
557 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100560 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561
Andy Lester7668a8b2020-03-24 23:26:44 -0500562 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 struct compiler_unit));
564 if (!u) {
565 PyErr_NoMemory();
566 return 0;
567 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100568 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100570 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 u->u_kwonlyargcount = 0;
572 u->u_ste = PySymtable_Lookup(c->c_st, key);
573 if (!u->u_ste) {
574 compiler_unit_free(u);
575 return 0;
576 }
577 Py_INCREF(name);
578 u->u_name = name;
579 u->u_varnames = list2dict(u->u_ste->ste_varnames);
580 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
581 if (!u->u_varnames || !u->u_cellvars) {
582 compiler_unit_free(u);
583 return 0;
584 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500585 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000586 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500587 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300588 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500589 int res;
590 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200591 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500592 name = _PyUnicode_FromId(&PyId___class__);
593 if (!name) {
594 compiler_unit_free(u);
595 return 0;
596 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300597 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500598 if (res < 0) {
599 compiler_unit_free(u);
600 return 0;
601 }
602 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200605 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!u->u_freevars) {
607 compiler_unit_free(u);
608 return 0;
609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 u->u_blocks = NULL;
612 u->u_nfblocks = 0;
613 u->u_firstlineno = lineno;
614 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000615 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 u->u_consts = PyDict_New();
617 if (!u->u_consts) {
618 compiler_unit_free(u);
619 return 0;
620 }
621 u->u_names = PyDict_New();
622 if (!u->u_names) {
623 compiler_unit_free(u);
624 return 0;
625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 /* Push the old compiler_unit on the stack. */
630 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400631 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
633 Py_XDECREF(capsule);
634 compiler_unit_free(u);
635 return 0;
636 }
637 Py_DECREF(capsule);
638 u->u_private = c->u->u_private;
639 Py_XINCREF(u->u_private);
640 }
641 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100644
645 block = compiler_new_block(c);
646 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100648 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400650 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
651 if (!compiler_set_qualname(c))
652 return 0;
653 }
654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656}
657
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000658static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659compiler_exit_scope(struct compiler *c)
660{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100661 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 c->c_nestlevel--;
665 compiler_unit_free(c->u);
666 /* Restore c->u to the parent unit. */
667 n = PyList_GET_SIZE(c->c_stack) - 1;
668 if (n >= 0) {
669 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400670 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 assert(c->u);
672 /* we are deleting from a list so this really shouldn't fail */
673 if (PySequence_DelItem(c->c_stack, n) < 0)
674 Py_FatalError("compiler_exit_scope()");
675 compiler_unit_check(c->u);
676 }
677 else
678 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000679
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680}
681
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400682static int
683compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100684{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100685 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 _Py_static_string(dot_locals, ".<locals>");
687 Py_ssize_t stack_size;
688 struct compiler_unit *u = c->u;
689 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100690
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100692 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400693 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 if (stack_size > 1) {
695 int scope, force_global = 0;
696 struct compiler_unit *parent;
697 PyObject *mangled, *capsule;
698
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400699 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400700 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400701 assert(parent);
702
Yury Selivanov75445082015-05-11 22:57:16 -0400703 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
704 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
705 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400706 assert(u->u_name);
707 mangled = _Py_Mangle(parent->u_private, u->u_name);
708 if (!mangled)
709 return 0;
710 scope = PyST_GetScope(parent->u_ste, mangled);
711 Py_DECREF(mangled);
712 assert(scope != GLOBAL_IMPLICIT);
713 if (scope == GLOBAL_EXPLICIT)
714 force_global = 1;
715 }
716
717 if (!force_global) {
718 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400719 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
721 dot_locals_str = _PyUnicode_FromId(&dot_locals);
722 if (dot_locals_str == NULL)
723 return 0;
724 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
725 if (base == NULL)
726 return 0;
727 }
728 else {
729 Py_INCREF(parent->u_qualname);
730 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400731 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100732 }
733 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400734
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400735 if (base != NULL) {
736 dot_str = _PyUnicode_FromId(&dot);
737 if (dot_str == NULL) {
738 Py_DECREF(base);
739 return 0;
740 }
741 name = PyUnicode_Concat(base, dot_str);
742 Py_DECREF(base);
743 if (name == NULL)
744 return 0;
745 PyUnicode_Append(&name, u->u_name);
746 if (name == NULL)
747 return 0;
748 }
749 else {
750 Py_INCREF(u->u_name);
751 name = u->u_name;
752 }
753 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100754
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400755 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100756}
757
Eric V. Smith235a6f02015-09-19 14:51:32 -0400758
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000759/* Allocate a new block and return a pointer to it.
760 Returns NULL on error.
761*/
762
763static basicblock *
764compiler_new_block(struct compiler *c)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 basicblock *b;
767 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500770 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (b == NULL) {
772 PyErr_NoMemory();
773 return NULL;
774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 /* Extend the singly linked list of blocks with new block. */
776 b->b_list = u->u_blocks;
777 u->u_blocks = b;
778 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779}
780
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782compiler_next_block(struct compiler *c)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 basicblock *block = compiler_new_block(c);
785 if (block == NULL)
786 return NULL;
787 c->u->u_curblock->b_next = block;
788 c->u->u_curblock = block;
789 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790}
791
792static basicblock *
793compiler_use_next_block(struct compiler *c, basicblock *block)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(block != NULL);
796 c->u->u_curblock->b_next = block;
797 c->u->u_curblock = block;
798 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799}
800
801/* Returns the offset of the next instruction in the current block's
802 b_instr array. Resizes the b_instr as necessary.
803 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000805
806static int
Andy Lester76d58772020-03-10 21:18:12 -0500807compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(b != NULL);
810 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500811 b->b_instr = (struct instr *)PyObject_Calloc(
812 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (b->b_instr == NULL) {
814 PyErr_NoMemory();
815 return -1;
816 }
817 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 }
819 else if (b->b_iused == b->b_ialloc) {
820 struct instr *tmp;
821 size_t oldsize, newsize;
822 oldsize = b->b_ialloc * sizeof(struct instr);
823 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000824
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700825 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyErr_NoMemory();
827 return -1;
828 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (newsize == 0) {
831 PyErr_NoMemory();
832 return -1;
833 }
834 b->b_ialloc <<= 1;
835 tmp = (struct instr *)PyObject_Realloc(
836 (void *)b->b_instr, newsize);
837 if (tmp == NULL) {
838 PyErr_NoMemory();
839 return -1;
840 }
841 b->b_instr = tmp;
842 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
843 }
844 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845}
846
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200847/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Christian Heimes2202f872008-02-06 14:31:34 +0000849 The line number is reset in the following cases:
850 - when entering a new scope
851 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200852 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200853 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000854*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000855
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200856#define SET_LOC(c, x) \
857 (c)->u->u_lineno = (x)->lineno; \
858 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200860/* Return the stack effect of opcode with argument oparg.
861
862 Some opcodes have different stack effect when jump to the target and
863 when not jump. The 'jump' parameter specifies the case:
864
865 * 0 -- when not jump
866 * 1 -- when jump
867 * -1 -- maximal
868 */
869/* XXX Make the stack effect of WITH_CLEANUP_START and
870 WITH_CLEANUP_FINISH deterministic. */
871static int
872stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300875 case NOP:
876 case EXTENDED_ARG:
877 return 0;
878
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200879 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case POP_TOP:
881 return -1;
882 case ROT_TWO:
883 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200884 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return 0;
886 case DUP_TOP:
887 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000888 case DUP_TOP_TWO:
889 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200891 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case UNARY_POSITIVE:
893 case UNARY_NEGATIVE:
894 case UNARY_NOT:
895 case UNARY_INVERT:
896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 case SET_ADD:
899 case LIST_APPEND:
900 return -1;
901 case MAP_ADD:
902 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000903
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200904 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 case BINARY_POWER:
906 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400907 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 case BINARY_MODULO:
909 case BINARY_ADD:
910 case BINARY_SUBTRACT:
911 case BINARY_SUBSCR:
912 case BINARY_FLOOR_DIVIDE:
913 case BINARY_TRUE_DIVIDE:
914 return -1;
915 case INPLACE_FLOOR_DIVIDE:
916 case INPLACE_TRUE_DIVIDE:
917 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case INPLACE_ADD:
920 case INPLACE_SUBTRACT:
921 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400922 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 case INPLACE_MODULO:
924 return -1;
925 case STORE_SUBSCR:
926 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case DELETE_SUBSCR:
928 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 case BINARY_LSHIFT:
931 case BINARY_RSHIFT:
932 case BINARY_AND:
933 case BINARY_XOR:
934 case BINARY_OR:
935 return -1;
936 case INPLACE_POWER:
937 return -1;
938 case GET_ITER:
939 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case PRINT_EXPR:
942 return -1;
943 case LOAD_BUILD_CLASS:
944 return 1;
945 case INPLACE_LSHIFT:
946 case INPLACE_RSHIFT:
947 case INPLACE_AND:
948 case INPLACE_XOR:
949 case INPLACE_OR:
950 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200953 /* 1 in the normal flow.
954 * Restore the stack position and push 6 values before jumping to
955 * the handler if an exception be raised. */
956 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case RETURN_VALUE:
958 return -1;
959 case IMPORT_STAR:
960 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700961 case SETUP_ANNOTATIONS:
962 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case YIELD_VALUE:
964 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500965 case YIELD_FROM:
966 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 case POP_BLOCK:
968 return 0;
969 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200970 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case STORE_NAME:
973 return -1;
974 case DELETE_NAME:
975 return 0;
976 case UNPACK_SEQUENCE:
977 return oparg-1;
978 case UNPACK_EX:
979 return (oparg&0xFF) + (oparg>>8);
980 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200981 /* -1 at end of iterator, 1 if continue iterating. */
982 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 case STORE_ATTR:
985 return -2;
986 case DELETE_ATTR:
987 return -1;
988 case STORE_GLOBAL:
989 return -1;
990 case DELETE_GLOBAL:
991 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case LOAD_CONST:
993 return 1;
994 case LOAD_NAME:
995 return 1;
996 case BUILD_TUPLE:
997 case BUILD_LIST:
998 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300999 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 return 1-oparg;
1001 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001002 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001003 case BUILD_CONST_KEY_MAP:
1004 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 case LOAD_ATTR:
1006 return 0;
1007 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001008 case IS_OP:
1009 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001011 case JUMP_IF_NOT_EXC_MATCH:
1012 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 case IMPORT_NAME:
1014 return -1;
1015 case IMPORT_FROM:
1016 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001018 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case JUMP_ABSOLUTE:
1021 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001023 case JUMP_IF_TRUE_OR_POP:
1024 case JUMP_IF_FALSE_OR_POP:
1025 return jump ? 0 : -1;
1026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case POP_JUMP_IF_FALSE:
1028 case POP_JUMP_IF_TRUE:
1029 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case LOAD_GLOBAL:
1032 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001034 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001036 /* 0 in the normal flow.
1037 * Restore the stack position and push 6 values before jumping to
1038 * the handler if an exception be raised. */
1039 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001040 case RERAISE:
1041 return -3;
1042
1043 case WITH_EXCEPT_START:
1044 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case LOAD_FAST:
1047 return 1;
1048 case STORE_FAST:
1049 return -1;
1050 case DELETE_FAST:
1051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 case RAISE_VARARGS:
1054 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001055
1056 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001058 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001059 case CALL_METHOD:
1060 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001062 return -oparg-1;
1063 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001064 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001065 case MAKE_FUNCTION:
1066 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1067 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 case BUILD_SLICE:
1069 if (oparg == 3)
1070 return -2;
1071 else
1072 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001074 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case LOAD_CLOSURE:
1076 return 1;
1077 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001078 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 return 1;
1080 case STORE_DEREF:
1081 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001082 case DELETE_DEREF:
1083 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001084
1085 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001086 case GET_AWAITABLE:
1087 return 0;
1088 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001089 /* 0 in the normal flow.
1090 * Restore the stack position to the position before the result
1091 * of __aenter__ and push 6 values before jumping to the handler
1092 * if an exception be raised. */
1093 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001094 case BEFORE_ASYNC_WITH:
1095 return 1;
1096 case GET_AITER:
1097 return 0;
1098 case GET_ANEXT:
1099 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001100 case GET_YIELD_FROM_ITER:
1101 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001102 case END_ASYNC_FOR:
1103 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001104 case FORMAT_VALUE:
1105 /* If there's a fmt_spec on the stack, we go from 2->1,
1106 else 1->1. */
1107 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001108 case LOAD_METHOD:
1109 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001110 case LOAD_ASSERTION_ERROR:
1111 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001112 case LIST_TO_TUPLE:
1113 return 0;
1114 case LIST_EXTEND:
1115 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001116 case DICT_MERGE:
1117 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001118 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001120 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
Larry Hastings3a907972013-11-23 14:49:22 -08001122 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123}
1124
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001125int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001126PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1127{
1128 return stack_effect(opcode, oparg, jump);
1129}
1130
1131int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001132PyCompile_OpcodeStackEffect(int opcode, int oparg)
1133{
1134 return stack_effect(opcode, oparg, -1);
1135}
1136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137/* Add an opcode with no argument.
1138 Returns 0 on failure, 1 on success.
1139*/
1140
1141static int
1142compiler_addop(struct compiler *c, int opcode)
1143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 basicblock *b;
1145 struct instr *i;
1146 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001147 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001148 if (c->c_do_not_emit_bytecode) {
1149 return 1;
1150 }
Andy Lester76d58772020-03-10 21:18:12 -05001151 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (off < 0)
1153 return 0;
1154 b = c->u->u_curblock;
1155 i = &b->b_instr[off];
1156 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001157 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (opcode == RETURN_VALUE)
1159 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001160 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162}
1163
Victor Stinnerf8e32212013-11-19 23:56:34 +01001164static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001165compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001167 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001170 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001172 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001174 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001175 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001176 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return -1;
1179 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001180 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_DECREF(v);
1182 return -1;
1183 }
1184 Py_DECREF(v);
1185 }
1186 else
1187 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001188 return arg;
1189}
1190
INADA Naokic2e16072018-11-26 21:23:22 +09001191// Merge const *o* recursively and return constant key object.
1192static PyObject*
1193merge_consts_recursive(struct compiler *c, PyObject *o)
1194{
1195 // None and Ellipsis are singleton, and key is the singleton.
1196 // No need to merge object and key.
1197 if (o == Py_None || o == Py_Ellipsis) {
1198 Py_INCREF(o);
1199 return o;
1200 }
1201
1202 PyObject *key = _PyCode_ConstantKey(o);
1203 if (key == NULL) {
1204 return NULL;
1205 }
1206
1207 // t is borrowed reference
1208 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1209 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001210 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001211 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001212 Py_DECREF(key);
1213 return t;
1214 }
1215
INADA Naokif7e4d362018-11-29 00:58:46 +09001216 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001217 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001218 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001219 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 Py_ssize_t len = PyTuple_GET_SIZE(o);
1221 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001222 PyObject *item = PyTuple_GET_ITEM(o, i);
1223 PyObject *u = merge_consts_recursive(c, item);
1224 if (u == NULL) {
1225 Py_DECREF(key);
1226 return NULL;
1227 }
1228
1229 // See _PyCode_ConstantKey()
1230 PyObject *v; // borrowed
1231 if (PyTuple_CheckExact(u)) {
1232 v = PyTuple_GET_ITEM(u, 1);
1233 }
1234 else {
1235 v = u;
1236 }
1237 if (v != item) {
1238 Py_INCREF(v);
1239 PyTuple_SET_ITEM(o, i, v);
1240 Py_DECREF(item);
1241 }
1242
1243 Py_DECREF(u);
1244 }
1245 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001246 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001247 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001248 // constant keys.
1249 // See _PyCode_ConstantKey() for detail.
1250 assert(PyTuple_CheckExact(key));
1251 assert(PyTuple_GET_SIZE(key) == 2);
1252
1253 Py_ssize_t len = PySet_GET_SIZE(o);
1254 if (len == 0) { // empty frozenset should not be re-created.
1255 return key;
1256 }
1257 PyObject *tuple = PyTuple_New(len);
1258 if (tuple == NULL) {
1259 Py_DECREF(key);
1260 return NULL;
1261 }
1262 Py_ssize_t i = 0, pos = 0;
1263 PyObject *item;
1264 Py_hash_t hash;
1265 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1266 PyObject *k = merge_consts_recursive(c, item);
1267 if (k == NULL) {
1268 Py_DECREF(tuple);
1269 Py_DECREF(key);
1270 return NULL;
1271 }
1272 PyObject *u;
1273 if (PyTuple_CheckExact(k)) {
1274 u = PyTuple_GET_ITEM(k, 1);
1275 Py_INCREF(u);
1276 Py_DECREF(k);
1277 }
1278 else {
1279 u = k;
1280 }
1281 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1282 i++;
1283 }
1284
1285 // Instead of rewriting o, we create new frozenset and embed in the
1286 // key tuple. Caller should get merged frozenset from the key tuple.
1287 PyObject *new = PyFrozenSet_New(tuple);
1288 Py_DECREF(tuple);
1289 if (new == NULL) {
1290 Py_DECREF(key);
1291 return NULL;
1292 }
1293 assert(PyTuple_GET_ITEM(key, 1) == o);
1294 Py_DECREF(o);
1295 PyTuple_SET_ITEM(key, 1, new);
1296 }
INADA Naokic2e16072018-11-26 21:23:22 +09001297
1298 return key;
1299}
1300
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001301static Py_ssize_t
1302compiler_add_const(struct compiler *c, PyObject *o)
1303{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001304 if (c->c_do_not_emit_bytecode) {
1305 return 0;
1306 }
1307
INADA Naokic2e16072018-11-26 21:23:22 +09001308 PyObject *key = merge_consts_recursive(c, o);
1309 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001311 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001312
Andy Lester76d58772020-03-10 21:18:12 -05001313 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001314 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001316}
1317
1318static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001319compiler_addop_load_const(struct compiler *c, PyObject *o)
1320{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001321 if (c->c_do_not_emit_bytecode) {
1322 return 1;
1323 }
1324
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001325 Py_ssize_t arg = compiler_add_const(c, o);
1326 if (arg < 0)
1327 return 0;
1328 return compiler_addop_i(c, LOAD_CONST, arg);
1329}
1330
1331static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001335 if (c->c_do_not_emit_bytecode) {
1336 return 1;
1337 }
1338
Andy Lester76d58772020-03-10 21:18:12 -05001339 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 return compiler_addop_i(c, opcode, arg);
1343}
1344
1345static int
1346compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001349 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001350
1351 if (c->c_do_not_emit_bytecode) {
1352 return 1;
1353 }
1354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1356 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001357 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001358 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 Py_DECREF(mangled);
1360 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362 return compiler_addop_i(c, opcode, arg);
1363}
1364
1365/* Add an opcode with an integer argument.
1366 Returns 0 on failure, 1 on success.
1367*/
1368
1369static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001370compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 struct instr *i;
1373 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001374
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001375 if (c->c_do_not_emit_bytecode) {
1376 return 1;
1377 }
1378
Victor Stinner2ad474b2016-03-01 23:34:47 +01001379 /* oparg value is unsigned, but a signed C int is usually used to store
1380 it in the C code (like Python/ceval.c).
1381
1382 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1383
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001384 The argument of a concrete bytecode instruction is limited to 8-bit.
1385 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1386 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001387 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001388
Andy Lester76d58772020-03-10 21:18:12 -05001389 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (off < 0)
1391 return 0;
1392 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001393 i->i_opcode = opcode;
1394 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001395 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397}
1398
1399static int
1400compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 struct instr *i;
1403 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001405 if (c->c_do_not_emit_bytecode) {
1406 return 1;
1407 }
1408
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001409 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001411 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (off < 0)
1413 return 0;
1414 i = &c->u->u_curblock->b_instr[off];
1415 i->i_opcode = opcode;
1416 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (absolute)
1418 i->i_jabs = 1;
1419 else
1420 i->i_jrel = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001421 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423}
1424
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001425/* NEXT_BLOCK() creates an implicit jump from the current block
1426 to the new block.
1427
1428 The returns inside this macro make it impossible to decref objects
1429 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (compiler_next_block((C)) == NULL) \
1433 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434}
1435
1436#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (!compiler_addop((C), (OP))) \
1438 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439}
1440
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001441#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (!compiler_addop((C), (OP))) { \
1443 compiler_exit_scope(c); \
1444 return 0; \
1445 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001446}
1447
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001448#define ADDOP_LOAD_CONST(C, O) { \
1449 if (!compiler_addop_load_const((C), (O))) \
1450 return 0; \
1451}
1452
1453/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1454#define ADDOP_LOAD_CONST_NEW(C, O) { \
1455 PyObject *__new_const = (O); \
1456 if (__new_const == NULL) { \
1457 return 0; \
1458 } \
1459 if (!compiler_addop_load_const((C), __new_const)) { \
1460 Py_DECREF(__new_const); \
1461 return 0; \
1462 } \
1463 Py_DECREF(__new_const); \
1464}
1465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001471/* Same as ADDOP_O, but steals a reference. */
1472#define ADDOP_N(C, OP, O, TYPE) { \
1473 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1474 Py_DECREF((O)); \
1475 return 0; \
1476 } \
1477 Py_DECREF((O)); \
1478}
1479
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1482 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483}
1484
1485#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (!compiler_addop_i((C), (OP), (O))) \
1487 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488}
1489
1490#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_j((C), (OP), (O), 1)) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_j((C), (OP), (O), 0)) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
Mark Shannon9af0e472020-01-14 10:12:45 +00001500
1501#define ADDOP_COMPARE(C, CMP) { \
1502 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1503 return 0; \
1504}
1505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1507 the ASDL name to synthesize the name of the C type and the visit function.
1508*/
1509
1510#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!compiler_visit_ ## TYPE((C), (V))) \
1512 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513}
1514
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001515#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (!compiler_visit_ ## TYPE((C), (V))) { \
1517 compiler_exit_scope(c); \
1518 return 0; \
1519 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001520}
1521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_visit_slice((C), (V), (CTX))) \
1524 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
1527#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 int _i; \
1529 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1530 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1531 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1532 if (!compiler_visit_ ## TYPE((C), elt)) \
1533 return 0; \
1534 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535}
1536
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001537#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 int _i; \
1539 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1540 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1541 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1542 if (!compiler_visit_ ## TYPE((C), elt)) { \
1543 compiler_exit_scope(c); \
1544 return 0; \
1545 } \
1546 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001547}
1548
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001549/* These macros allows to check only for errors and not emmit bytecode
1550 * while visiting nodes.
1551*/
1552
1553#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1554 c->c_do_not_emit_bytecode++;
1555
1556#define END_DO_NOT_EMIT_BYTECODE \
1557 c->c_do_not_emit_bytecode--; \
1558}
1559
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001560/* Search if variable annotations are present statically in a block. */
1561
1562static int
1563find_ann(asdl_seq *stmts)
1564{
1565 int i, j, res = 0;
1566 stmt_ty st;
1567
1568 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1569 st = (stmt_ty)asdl_seq_GET(stmts, i);
1570 switch (st->kind) {
1571 case AnnAssign_kind:
1572 return 1;
1573 case For_kind:
1574 res = find_ann(st->v.For.body) ||
1575 find_ann(st->v.For.orelse);
1576 break;
1577 case AsyncFor_kind:
1578 res = find_ann(st->v.AsyncFor.body) ||
1579 find_ann(st->v.AsyncFor.orelse);
1580 break;
1581 case While_kind:
1582 res = find_ann(st->v.While.body) ||
1583 find_ann(st->v.While.orelse);
1584 break;
1585 case If_kind:
1586 res = find_ann(st->v.If.body) ||
1587 find_ann(st->v.If.orelse);
1588 break;
1589 case With_kind:
1590 res = find_ann(st->v.With.body);
1591 break;
1592 case AsyncWith_kind:
1593 res = find_ann(st->v.AsyncWith.body);
1594 break;
1595 case Try_kind:
1596 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1597 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1598 st->v.Try.handlers, j);
1599 if (find_ann(handler->v.ExceptHandler.body)) {
1600 return 1;
1601 }
1602 }
1603 res = find_ann(st->v.Try.body) ||
1604 find_ann(st->v.Try.finalbody) ||
1605 find_ann(st->v.Try.orelse);
1606 break;
1607 default:
1608 res = 0;
1609 }
1610 if (res) {
1611 break;
1612 }
1613 }
1614 return res;
1615}
1616
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001617/*
1618 * Frame block handling functions
1619 */
1620
1621static int
1622compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001623 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001624{
1625 struct fblockinfo *f;
1626 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1627 PyErr_SetString(PyExc_SyntaxError,
1628 "too many statically nested blocks");
1629 return 0;
1630 }
1631 f = &c->u->u_fblock[c->u->u_nfblocks++];
1632 f->fb_type = t;
1633 f->fb_block = b;
1634 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001635 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001636 return 1;
1637}
1638
1639static void
1640compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1641{
1642 struct compiler_unit *u = c->u;
1643 assert(u->u_nfblocks > 0);
1644 u->u_nfblocks--;
1645 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1646 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1647}
1648
Mark Shannonfee55262019-11-21 09:11:43 +00001649static int
1650compiler_call_exit_with_nones(struct compiler *c) {
1651 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1652 ADDOP(c, DUP_TOP);
1653 ADDOP(c, DUP_TOP);
1654 ADDOP_I(c, CALL_FUNCTION, 3);
1655 return 1;
1656}
1657
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001658/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001659 * popping the blocks will be restored afterwards, unless another
1660 * return, break or continue is found. In which case, the TOS will
1661 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001662 */
1663static int
1664compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1665 int preserve_tos)
1666{
1667 switch (info->fb_type) {
1668 case WHILE_LOOP:
1669 return 1;
1670
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001671 case FOR_LOOP:
1672 /* Pop the iterator */
1673 if (preserve_tos) {
1674 ADDOP(c, ROT_TWO);
1675 }
1676 ADDOP(c, POP_TOP);
1677 return 1;
1678
1679 case EXCEPT:
1680 ADDOP(c, POP_BLOCK);
1681 return 1;
1682
1683 case FINALLY_TRY:
1684 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001685 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001686 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1687 return 0;
1688 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001689 }
Mark Shannon88dce262019-12-30 09:53:36 +00001690 /* Emit the finally block, restoring the line number when done */
1691 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001692 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001693 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001694 if (preserve_tos) {
1695 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001696 }
1697 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001698
Mark Shannonfee55262019-11-21 09:11:43 +00001699 case FINALLY_END:
1700 if (preserve_tos) {
1701 ADDOP(c, ROT_FOUR);
1702 }
1703 ADDOP(c, POP_TOP);
1704 ADDOP(c, POP_TOP);
1705 ADDOP(c, POP_TOP);
1706 if (preserve_tos) {
1707 ADDOP(c, ROT_FOUR);
1708 }
1709 ADDOP(c, POP_EXCEPT);
1710 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001711
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001712 case WITH:
1713 case ASYNC_WITH:
1714 ADDOP(c, POP_BLOCK);
1715 if (preserve_tos) {
1716 ADDOP(c, ROT_TWO);
1717 }
Mark Shannonfee55262019-11-21 09:11:43 +00001718 if(!compiler_call_exit_with_nones(c)) {
1719 return 0;
1720 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001721 if (info->fb_type == ASYNC_WITH) {
1722 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001723 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 ADDOP(c, YIELD_FROM);
1725 }
Mark Shannonfee55262019-11-21 09:11:43 +00001726 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 return 1;
1728
1729 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001730 if (info->fb_datum) {
1731 ADDOP(c, POP_BLOCK);
1732 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 if (preserve_tos) {
1734 ADDOP(c, ROT_FOUR);
1735 }
Mark Shannonfee55262019-11-21 09:11:43 +00001736 ADDOP(c, POP_EXCEPT);
1737 if (info->fb_datum) {
1738 ADDOP_LOAD_CONST(c, Py_None);
1739 compiler_nameop(c, info->fb_datum, Store);
1740 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001741 }
Mark Shannonfee55262019-11-21 09:11:43 +00001742 return 1;
1743
1744 case POP_VALUE:
1745 if (preserve_tos) {
1746 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001747 }
Mark Shannonfee55262019-11-21 09:11:43 +00001748 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 return 1;
1750 }
1751 Py_UNREACHABLE();
1752}
1753
Mark Shannonfee55262019-11-21 09:11:43 +00001754/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1755static int
1756compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1757 if (c->u->u_nfblocks == 0) {
1758 return 1;
1759 }
1760 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1761 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1762 *loop = top;
1763 return 1;
1764 }
1765 struct fblockinfo copy = *top;
1766 c->u->u_nfblocks--;
1767 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1768 return 0;
1769 }
1770 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1771 return 0;
1772 }
1773 c->u->u_fblock[c->u->u_nfblocks] = copy;
1774 c->u->u_nfblocks++;
1775 return 1;
1776}
1777
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001778/* Compile a sequence of statements, checking for a docstring
1779 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780
1781static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001782compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001784 int i = 0;
1785 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001786 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001787
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001788 /* Set current line number to the line number of first statement.
1789 This way line number for SETUP_ANNOTATIONS will always
1790 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301791 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001792 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001793 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001794 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001795 }
1796 /* Every annotated class and module should have __annotations__. */
1797 if (find_ann(stmts)) {
1798 ADDOP(c, SETUP_ANNOTATIONS);
1799 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001800 if (!asdl_seq_LEN(stmts))
1801 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001802 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001803 if (c->c_optimize < 2) {
1804 docstring = _PyAST_GetDocString(stmts);
1805 if (docstring) {
1806 i = 1;
1807 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1808 assert(st->kind == Expr_kind);
1809 VISIT(c, expr, st->v.Expr.value);
1810 if (!compiler_nameop(c, __doc__, Store))
1811 return 0;
1812 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001814 for (; i < asdl_seq_LEN(stmts); i++)
1815 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817}
1818
1819static PyCodeObject *
1820compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyCodeObject *co;
1823 int addNone = 1;
1824 static PyObject *module;
1825 if (!module) {
1826 module = PyUnicode_InternFromString("<module>");
1827 if (!module)
1828 return NULL;
1829 }
1830 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001831 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 return NULL;
1833 switch (mod->kind) {
1834 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001835 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 compiler_exit_scope(c);
1837 return 0;
1838 }
1839 break;
1840 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001841 if (find_ann(mod->v.Interactive.body)) {
1842 ADDOP(c, SETUP_ANNOTATIONS);
1843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 c->c_interactive = 1;
1845 VISIT_SEQ_IN_SCOPE(c, stmt,
1846 mod->v.Interactive.body);
1847 break;
1848 case Expression_kind:
1849 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1850 addNone = 0;
1851 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 default:
1853 PyErr_Format(PyExc_SystemError,
1854 "module kind %d should not be possible",
1855 mod->kind);
1856 return 0;
1857 }
1858 co = assemble(c, addNone);
1859 compiler_exit_scope(c);
1860 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001861}
1862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863/* The test for LOCAL must come before the test for FREE in order to
1864 handle classes where name is both local and free. The local var is
1865 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001866*/
1867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868static int
1869get_ref_type(struct compiler *c, PyObject *name)
1870{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001871 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001872 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001873 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001875 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001877 _Py_FatalErrorFormat(__func__,
1878 "unknown scope for %.100s in %.100s(%s)\n"
1879 "symbols: %s\nlocals: %s\nglobals: %s",
1880 PyUnicode_AsUTF8(name),
1881 PyUnicode_AsUTF8(c->u->u_name),
1882 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1883 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889}
1890
1891static int
1892compiler_lookup_arg(PyObject *dict, PyObject *name)
1893{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001894 PyObject *v;
1895 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001897 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001898 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899}
1900
1901static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001902compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001904 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001905 if (qualname == NULL)
1906 qualname = co->co_name;
1907
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001908 if (free) {
1909 for (i = 0; i < free; ++i) {
1910 /* Bypass com_addop_varname because it will generate
1911 LOAD_DEREF but LOAD_CLOSURE is needed.
1912 */
1913 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1914 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 /* Special case: If a class contains a method with a
1917 free variable that has the same name as a method,
1918 the name will be considered free *and* local in the
1919 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001920 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001921 */
1922 reftype = get_ref_type(c, name);
1923 if (reftype == CELL)
1924 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1925 else /* (reftype == FREE) */
1926 arg = compiler_lookup_arg(c->u->u_freevars, name);
1927 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001928 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001929 "lookup %s in %s %d %d\n"
1930 "freevars of %s: %s\n",
1931 PyUnicode_AsUTF8(PyObject_Repr(name)),
1932 PyUnicode_AsUTF8(c->u->u_name),
1933 reftype, arg,
1934 PyUnicode_AsUTF8(co->co_name),
1935 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001936 }
1937 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001939 flags |= 0x08;
1940 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001942 ADDOP_LOAD_CONST(c, (PyObject*)co);
1943 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001944 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946}
1947
1948static int
1949compiler_decorators(struct compiler *c, asdl_seq* decos)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (!decos)
1954 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1957 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1958 }
1959 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960}
1961
1962static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001963compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001965{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001966 /* Push a dict of keyword-only default values.
1967
1968 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1969 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001970 int i;
1971 PyObject *keys = NULL;
1972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1974 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1975 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1976 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001977 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001978 if (!mangled) {
1979 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001981 if (keys == NULL) {
1982 keys = PyList_New(1);
1983 if (keys == NULL) {
1984 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001985 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 }
1987 PyList_SET_ITEM(keys, 0, mangled);
1988 }
1989 else {
1990 int res = PyList_Append(keys, mangled);
1991 Py_DECREF(mangled);
1992 if (res == -1) {
1993 goto error;
1994 }
1995 }
1996 if (!compiler_visit_expr(c, default_)) {
1997 goto error;
1998 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
2000 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002001 if (keys != NULL) {
2002 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2003 PyObject *keys_tuple = PyList_AsTuple(keys);
2004 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002005 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002007 assert(default_count > 0);
2008 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002009 }
2010 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002011 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 }
2013
2014error:
2015 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002016 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002017}
2018
2019static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002020compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2021{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002022 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002023 return 1;
2024}
2025
2026static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002027compiler_visit_argannotation(struct compiler *c, identifier id,
2028 expr_ty annotation, PyObject *names)
2029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002031 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08002032 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2033 VISIT(c, annexpr, annotation)
2034 }
2035 else {
2036 VISIT(c, expr, annotation);
2037 }
Victor Stinner065efc32014-02-18 22:07:56 +01002038 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002039 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002040 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002041 if (PyList_Append(names, mangled) < 0) {
2042 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002043 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002044 }
2045 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002047 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002048}
2049
2050static int
2051compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
2052 PyObject *names)
2053{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002054 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 for (i = 0; i < asdl_seq_LEN(args); i++) {
2056 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 c,
2059 arg->arg,
2060 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 names))
2062 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002065}
2066
2067static int
2068compiler_visit_annotations(struct compiler *c, arguments_ty args,
2069 expr_ty returns)
2070{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002071 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002072 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002073
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002074 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 */
2076 static identifier return_str;
2077 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002078 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 names = PyList_New(0);
2080 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002081 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002083 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002085 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2086 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002087 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002089 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002091 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002093 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002094 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002095 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (!return_str) {
2099 return_str = PyUnicode_InternFromString("return");
2100 if (!return_str)
2101 goto error;
2102 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002103 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 goto error;
2105 }
2106
2107 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 PyObject *keytuple = PyList_AsTuple(names);
2110 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002111 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002113 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002115 else {
2116 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002117 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002119
2120error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002122 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002123}
2124
2125static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002126compiler_visit_defaults(struct compiler *c, arguments_ty args)
2127{
2128 VISIT_SEQ(c, expr, args->defaults);
2129 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2130 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131}
2132
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002133static Py_ssize_t
2134compiler_default_arguments(struct compiler *c, arguments_ty args)
2135{
2136 Py_ssize_t funcflags = 0;
2137 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 if (!compiler_visit_defaults(c, args))
2139 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002140 funcflags |= 0x01;
2141 }
2142 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002143 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002144 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002145 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002146 return -1;
2147 }
2148 else if (res > 0) {
2149 funcflags |= 0x02;
2150 }
2151 }
2152 return funcflags;
2153}
2154
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155static int
Yury Selivanov75445082015-05-11 22:57:16 -04002156compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002159 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002160 arguments_ty args;
2161 expr_ty returns;
2162 identifier name;
2163 asdl_seq* decos;
2164 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002165 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002166 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002167 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002168 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169
Yury Selivanov75445082015-05-11 22:57:16 -04002170 if (is_async) {
2171 assert(s->kind == AsyncFunctionDef_kind);
2172
2173 args = s->v.AsyncFunctionDef.args;
2174 returns = s->v.AsyncFunctionDef.returns;
2175 decos = s->v.AsyncFunctionDef.decorator_list;
2176 name = s->v.AsyncFunctionDef.name;
2177 body = s->v.AsyncFunctionDef.body;
2178
2179 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2180 } else {
2181 assert(s->kind == FunctionDef_kind);
2182
2183 args = s->v.FunctionDef.args;
2184 returns = s->v.FunctionDef.returns;
2185 decos = s->v.FunctionDef.decorator_list;
2186 name = s->v.FunctionDef.name;
2187 body = s->v.FunctionDef.body;
2188
2189 scope_type = COMPILER_SCOPE_FUNCTION;
2190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (!compiler_decorators(c, decos))
2193 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002194
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002195 firstlineno = s->lineno;
2196 if (asdl_seq_LEN(decos)) {
2197 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2198 }
2199
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002200 funcflags = compiler_default_arguments(c, args);
2201 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002203 }
2204
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002205 annotations = compiler_visit_annotations(c, args, returns);
2206 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002207 return 0;
2208 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002209 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002210 funcflags |= 0x04;
2211 }
2212
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002213 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002214 return 0;
2215 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216
INADA Naokicb41b272017-02-23 00:31:59 +09002217 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002218 if (c->c_optimize < 2) {
2219 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002220 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002221 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 compiler_exit_scope(c);
2223 return 0;
2224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002227 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002229 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002231 qualname = c->u->u_qualname;
2232 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002234 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002235 Py_XDECREF(qualname);
2236 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002240 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002241 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* decorators */
2245 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2246 ADDOP_I(c, CALL_FUNCTION, 1);
2247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Yury Selivanov75445082015-05-11 22:57:16 -04002249 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250}
2251
2252static int
2253compiler_class(struct compiler *c, stmt_ty s)
2254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 PyCodeObject *co;
2256 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002257 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (!compiler_decorators(c, decos))
2261 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002262
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002263 firstlineno = s->lineno;
2264 if (asdl_seq_LEN(decos)) {
2265 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2266 }
2267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* ultimately generate code for:
2269 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2270 where:
2271 <func> is a function/closure created from the class body;
2272 it has a single argument (__locals__) where the dict
2273 (or MutableSequence) representing the locals is passed
2274 <name> is the class name
2275 <bases> is the positional arguments and *varargs argument
2276 <keywords> is the keyword arguments and **kwds argument
2277 This borrows from compiler_call.
2278 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002281 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002282 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 return 0;
2284 /* this block represents what we do in the new scope */
2285 {
2286 /* use the class name for name mangling */
2287 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002288 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* load (global) __name__ ... */
2290 str = PyUnicode_InternFromString("__name__");
2291 if (!str || !compiler_nameop(c, str, Load)) {
2292 Py_XDECREF(str);
2293 compiler_exit_scope(c);
2294 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_DECREF(str);
2297 /* ... and store it as __module__ */
2298 str = PyUnicode_InternFromString("__module__");
2299 if (!str || !compiler_nameop(c, str, Store)) {
2300 Py_XDECREF(str);
2301 compiler_exit_scope(c);
2302 return 0;
2303 }
2304 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002305 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002306 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002307 str = PyUnicode_InternFromString("__qualname__");
2308 if (!str || !compiler_nameop(c, str, Store)) {
2309 Py_XDECREF(str);
2310 compiler_exit_scope(c);
2311 return 0;
2312 }
2313 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002315 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 compiler_exit_scope(c);
2317 return 0;
2318 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002319 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002320 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002321 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002322 str = PyUnicode_InternFromString("__class__");
2323 if (str == NULL) {
2324 compiler_exit_scope(c);
2325 return 0;
2326 }
2327 i = compiler_lookup_arg(c->u->u_cellvars, str);
2328 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002329 if (i < 0) {
2330 compiler_exit_scope(c);
2331 return 0;
2332 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002333 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002336 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002337 str = PyUnicode_InternFromString("__classcell__");
2338 if (!str || !compiler_nameop(c, str, Store)) {
2339 Py_XDECREF(str);
2340 compiler_exit_scope(c);
2341 return 0;
2342 }
2343 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002345 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002346 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002347 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002348 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002349 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002350 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* create the code object */
2352 co = assemble(c, 1);
2353 }
2354 /* leave the new scope */
2355 compiler_exit_scope(c);
2356 if (co == NULL)
2357 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* 2. load the 'build_class' function */
2360 ADDOP(c, LOAD_BUILD_CLASS);
2361
2362 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002363 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 Py_DECREF(co);
2365
2366 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002367 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368
2369 /* 5. generate the rest of the code for the call */
2370 if (!compiler_call_helper(c, 2,
2371 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002372 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 return 0;
2374
2375 /* 6. apply decorators */
2376 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2377 ADDOP_I(c, CALL_FUNCTION, 1);
2378 }
2379
2380 /* 7. store into <name> */
2381 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2382 return 0;
2383 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384}
2385
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002386/* Return 0 if the expression is a constant value except named singletons.
2387 Return 1 otherwise. */
2388static int
2389check_is_arg(expr_ty e)
2390{
2391 if (e->kind != Constant_kind) {
2392 return 1;
2393 }
2394 PyObject *value = e->v.Constant.value;
2395 return (value == Py_None
2396 || value == Py_False
2397 || value == Py_True
2398 || value == Py_Ellipsis);
2399}
2400
2401/* Check operands of identity chacks ("is" and "is not").
2402 Emit a warning if any operand is a constant except named singletons.
2403 Return 0 on error.
2404 */
2405static int
2406check_compare(struct compiler *c, expr_ty e)
2407{
2408 Py_ssize_t i, n;
2409 int left = check_is_arg(e->v.Compare.left);
2410 n = asdl_seq_LEN(e->v.Compare.ops);
2411 for (i = 0; i < n; i++) {
2412 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2413 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2414 if (op == Is || op == IsNot) {
2415 if (!right || !left) {
2416 const char *msg = (op == Is)
2417 ? "\"is\" with a literal. Did you mean \"==\"?"
2418 : "\"is not\" with a literal. Did you mean \"!=\"?";
2419 return compiler_warn(c, msg);
2420 }
2421 }
2422 left = right;
2423 }
2424 return 1;
2425}
2426
Mark Shannon9af0e472020-01-14 10:12:45 +00002427static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002428{
Mark Shannon9af0e472020-01-14 10:12:45 +00002429 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002430 switch (op) {
2431 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002432 cmp = Py_EQ;
2433 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002434 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002435 cmp = Py_NE;
2436 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002437 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002438 cmp = Py_LT;
2439 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002440 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002441 cmp = Py_LE;
2442 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002443 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002444 cmp = Py_GT;
2445 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002446 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002447 cmp = Py_GE;
2448 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002449 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002450 ADDOP_I(c, IS_OP, 0);
2451 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002452 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002453 ADDOP_I(c, IS_OP, 1);
2454 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002455 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002456 ADDOP_I(c, CONTAINS_OP, 0);
2457 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002458 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002459 ADDOP_I(c, CONTAINS_OP, 1);
2460 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002464 ADDOP_I(c, COMPARE_OP, cmp);
2465 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002466}
2467
Mark Shannon9af0e472020-01-14 10:12:45 +00002468
2469
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470static int
2471compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2472{
2473 switch (e->kind) {
2474 case UnaryOp_kind:
2475 if (e->v.UnaryOp.op == Not)
2476 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2477 /* fallback to general implementation */
2478 break;
2479 case BoolOp_kind: {
2480 asdl_seq *s = e->v.BoolOp.values;
2481 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2482 assert(n >= 0);
2483 int cond2 = e->v.BoolOp.op == Or;
2484 basicblock *next2 = next;
2485 if (!cond2 != !cond) {
2486 next2 = compiler_new_block(c);
2487 if (next2 == NULL)
2488 return 0;
2489 }
2490 for (i = 0; i < n; ++i) {
2491 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2492 return 0;
2493 }
2494 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2495 return 0;
2496 if (next2 != next)
2497 compiler_use_next_block(c, next2);
2498 return 1;
2499 }
2500 case IfExp_kind: {
2501 basicblock *end, *next2;
2502 end = compiler_new_block(c);
2503 if (end == NULL)
2504 return 0;
2505 next2 = compiler_new_block(c);
2506 if (next2 == NULL)
2507 return 0;
2508 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2509 return 0;
2510 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2511 return 0;
2512 ADDOP_JREL(c, JUMP_FORWARD, end);
2513 compiler_use_next_block(c, next2);
2514 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2515 return 0;
2516 compiler_use_next_block(c, end);
2517 return 1;
2518 }
2519 case Compare_kind: {
2520 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2521 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002522 if (!check_compare(c, e)) {
2523 return 0;
2524 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002525 basicblock *cleanup = compiler_new_block(c);
2526 if (cleanup == NULL)
2527 return 0;
2528 VISIT(c, expr, e->v.Compare.left);
2529 for (i = 0; i < n; i++) {
2530 VISIT(c, expr,
2531 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2532 ADDOP(c, DUP_TOP);
2533 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002534 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002535 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2536 NEXT_BLOCK(c);
2537 }
2538 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002539 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002540 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2541 basicblock *end = compiler_new_block(c);
2542 if (end == NULL)
2543 return 0;
2544 ADDOP_JREL(c, JUMP_FORWARD, end);
2545 compiler_use_next_block(c, cleanup);
2546 ADDOP(c, POP_TOP);
2547 if (!cond) {
2548 ADDOP_JREL(c, JUMP_FORWARD, next);
2549 }
2550 compiler_use_next_block(c, end);
2551 return 1;
2552 }
2553 /* fallback to general implementation */
2554 break;
2555 }
2556 default:
2557 /* fallback to general implementation */
2558 break;
2559 }
2560
2561 /* general implementation */
2562 VISIT(c, expr, e);
2563 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2564 return 1;
2565}
2566
2567static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002568compiler_ifexp(struct compiler *c, expr_ty e)
2569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 basicblock *end, *next;
2571
2572 assert(e->kind == IfExp_kind);
2573 end = compiler_new_block(c);
2574 if (end == NULL)
2575 return 0;
2576 next = compiler_new_block(c);
2577 if (next == NULL)
2578 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002579 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2580 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 VISIT(c, expr, e->v.IfExp.body);
2582 ADDOP_JREL(c, JUMP_FORWARD, end);
2583 compiler_use_next_block(c, next);
2584 VISIT(c, expr, e->v.IfExp.orelse);
2585 compiler_use_next_block(c, end);
2586 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002587}
2588
2589static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590compiler_lambda(struct compiler *c, expr_ty e)
2591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002593 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002595 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 arguments_ty args = e->v.Lambda.args;
2597 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (!name) {
2600 name = PyUnicode_InternFromString("<lambda>");
2601 if (!name)
2602 return 0;
2603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002605 funcflags = compiler_default_arguments(c, args);
2606 if (funcflags == -1) {
2607 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002609
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002610 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002611 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 /* Make None the first constant, so the lambda can't have a
2615 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002616 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002620 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2622 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2623 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002624 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 }
2626 else {
2627 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002628 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002630 qualname = c->u->u_qualname;
2631 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002633 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002636 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002637 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 Py_DECREF(co);
2639
2640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641}
2642
2643static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644compiler_if(struct compiler *c, stmt_ty s)
2645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 basicblock *end, *next;
2647 int constant;
2648 assert(s->kind == If_kind);
2649 end = compiler_new_block(c);
2650 if (end == NULL)
2651 return 0;
2652
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002653 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002654 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 * constant = 1: "if 1", "if 2", ...
2656 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002657 if (constant == 0) {
2658 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002660 END_DO_NOT_EMIT_BYTECODE
2661 if (s->v.If.orelse) {
2662 VISIT_SEQ(c, stmt, s->v.If.orelse);
2663 }
2664 } else if (constant == 1) {
2665 VISIT_SEQ(c, stmt, s->v.If.body);
2666 if (s->v.If.orelse) {
2667 BEGIN_DO_NOT_EMIT_BYTECODE
2668 VISIT_SEQ(c, stmt, s->v.If.orelse);
2669 END_DO_NOT_EMIT_BYTECODE
2670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002672 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 next = compiler_new_block(c);
2674 if (next == NULL)
2675 return 0;
2676 }
Mark Shannonfee55262019-11-21 09:11:43 +00002677 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002679 }
2680 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002681 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002684 if (asdl_seq_LEN(s->v.If.orelse)) {
2685 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 compiler_use_next_block(c, next);
2687 VISIT_SEQ(c, stmt, s->v.If.orelse);
2688 }
2689 }
2690 compiler_use_next_block(c, end);
2691 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692}
2693
2694static int
2695compiler_for(struct compiler *c, stmt_ty s)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 start = compiler_new_block(c);
2700 cleanup = compiler_new_block(c);
2701 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002702 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002704 }
2705 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002707 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 VISIT(c, expr, s->v.For.iter);
2709 ADDOP(c, GET_ITER);
2710 compiler_use_next_block(c, start);
2711 ADDOP_JREL(c, FOR_ITER, cleanup);
2712 VISIT(c, expr, s->v.For.target);
2713 VISIT_SEQ(c, stmt, s->v.For.body);
2714 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2715 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002716
2717 compiler_pop_fblock(c, FOR_LOOP, start);
2718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 VISIT_SEQ(c, stmt, s->v.For.orelse);
2720 compiler_use_next_block(c, end);
2721 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722}
2723
Yury Selivanov75445082015-05-11 22:57:16 -04002724
2725static int
2726compiler_async_for(struct compiler *c, stmt_ty s)
2727{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002728 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002729 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002730 c->u->u_ste->ste_coroutine = 1;
2731 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002732 return compiler_error(c, "'async for' outside async function");
2733 }
2734
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002735 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002736 except = compiler_new_block(c);
2737 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002738
Mark Shannonfee55262019-11-21 09:11:43 +00002739 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002740 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002741 }
Yury Selivanov75445082015-05-11 22:57:16 -04002742 VISIT(c, expr, s->v.AsyncFor.iter);
2743 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002744
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002745 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002746 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002747 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002748 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002749 /* SETUP_FINALLY to guard the __anext__ call */
2750 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002751 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002752 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002753 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002754 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002755
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002756 /* Success block for __anext__ */
2757 VISIT(c, expr, s->v.AsyncFor.target);
2758 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2759 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2760
2761 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002762
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002763 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002764 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002765 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002766
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002767 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002768 VISIT_SEQ(c, stmt, s->v.For.orelse);
2769
2770 compiler_use_next_block(c, end);
2771
2772 return 1;
2773}
2774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775static int
2776compiler_while(struct compiler *c, stmt_ty s)
2777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002779 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002782 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002783 // Push a dummy block so the VISIT_SEQ knows that we are
2784 // inside a while loop so it can correctly evaluate syntax
2785 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002786 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002787 return 0;
2788 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002789 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002790 // Remove the dummy block now that is not needed.
2791 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002792 END_DO_NOT_EMIT_BYTECODE
2793 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 return 1;
2797 }
2798 loop = compiler_new_block(c);
2799 end = compiler_new_block(c);
2800 if (constant == -1) {
2801 anchor = compiler_new_block(c);
2802 if (anchor == NULL)
2803 return 0;
2804 }
2805 if (loop == NULL || end == NULL)
2806 return 0;
2807 if (s->v.While.orelse) {
2808 orelse = compiler_new_block(c);
2809 if (orelse == NULL)
2810 return 0;
2811 }
2812 else
2813 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002816 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return 0;
2818 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002819 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2820 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 }
2822 VISIT_SEQ(c, stmt, s->v.While.body);
2823 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* XXX should the two POP instructions be in a separate block
2826 if there is no else clause ?
2827 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002829 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002831 compiler_pop_fblock(c, WHILE_LOOP, loop);
2832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 if (orelse != NULL) /* what if orelse is just pass? */
2834 VISIT_SEQ(c, stmt, s->v.While.orelse);
2835 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838}
2839
2840static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002841compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002843 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002844 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 if (c->u->u_ste->ste_type != FunctionBlock)
2846 return compiler_error(c, "'return' outside function");
2847 if (s->v.Return.value != NULL &&
2848 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2849 {
2850 return compiler_error(
2851 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002853 if (preserve_tos) {
2854 VISIT(c, expr, s->v.Return.value);
2855 }
Mark Shannonfee55262019-11-21 09:11:43 +00002856 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2857 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002858 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002859 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002860 }
2861 else if (!preserve_tos) {
2862 VISIT(c, expr, s->v.Return.value);
2863 }
2864 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867}
2868
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002869static int
2870compiler_break(struct compiler *c)
2871{
Mark Shannonfee55262019-11-21 09:11:43 +00002872 struct fblockinfo *loop = NULL;
2873 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2874 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 }
Mark Shannonfee55262019-11-21 09:11:43 +00002876 if (loop == NULL) {
2877 return compiler_error(c, "'break' outside loop");
2878 }
2879 if (!compiler_unwind_fblock(c, loop, 0)) {
2880 return 0;
2881 }
2882 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_exit);
2883 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884}
2885
2886static int
2887compiler_continue(struct compiler *c)
2888{
Mark Shannonfee55262019-11-21 09:11:43 +00002889 struct fblockinfo *loop = NULL;
2890 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2891 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 }
Mark Shannonfee55262019-11-21 09:11:43 +00002893 if (loop == NULL) {
2894 return compiler_error(c, "'continue' not properly in loop");
2895 }
2896 ADDOP_JABS(c, JUMP_ABSOLUTE, loop->fb_block);
2897 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002898}
2899
2900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902
2903 SETUP_FINALLY L
2904 <code for body>
2905 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002906 <code for finalbody>
2907 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002908 L:
2909 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002910 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 The special instructions use the block stack. Each block
2913 stack entry contains the instruction that created it (here
2914 SETUP_FINALLY), the level of the value stack at the time the
2915 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 Pushes the current value stack level and the label
2919 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002921 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002924 when a SETUP_FINALLY entry is found, the raised and the caught
2925 exceptions are pushed onto the value stack (and the exception
2926 condition is cleared), and the interpreter jumps to the label
2927 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928*/
2929
2930static int
2931compiler_try_finally(struct compiler *c, stmt_ty s)
2932{
Mark Shannonfee55262019-11-21 09:11:43 +00002933 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 body = compiler_new_block(c);
2936 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002937 exit = compiler_new_block(c);
2938 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 ADDOP_JREL(c, SETUP_FINALLY, end);
2943 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002944 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002946 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2947 if (!compiler_try_except(c, s))
2948 return 0;
2949 }
2950 else {
2951 VISIT_SEQ(c, stmt, s->v.Try.body);
2952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002954 compiler_pop_fblock(c, FINALLY_TRY, body);
2955 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2956 ADDOP_JREL(c, JUMP_FORWARD, exit);
2957 /* `finally` block */
2958 compiler_use_next_block(c, end);
2959 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2960 return 0;
2961 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2962 compiler_pop_fblock(c, FINALLY_END, end);
2963 ADDOP(c, RERAISE);
2964 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966}
2967
2968/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002969 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970 (The contents of the value stack is shown in [], with the top
2971 at the right; 'tb' is trace-back info, 'val' the exception's
2972 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973
2974 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002975 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 [] <code for S>
2977 [] POP_BLOCK
2978 [] JUMP_FORWARD L0
2979
2980 [tb, val, exc] L1: DUP )
2981 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00002982 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 [tb, val, exc] POP
2984 [tb, val] <assign to V1> (or POP if no V1)
2985 [tb] POP
2986 [] <code for S1>
2987 JUMP_FORWARD L0
2988
2989 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 .............................etc.......................
2991
Mark Shannonfee55262019-11-21 09:11:43 +00002992 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993
2994 [] L0: <next statement>
2995
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 Of course, parts are not generated if Vi or Ei is not present.
2997*/
2998static int
2999compiler_try_except(struct compiler *c, stmt_ty s)
3000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003002 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 body = compiler_new_block(c);
3005 except = compiler_new_block(c);
3006 orelse = compiler_new_block(c);
3007 end = compiler_new_block(c);
3008 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3009 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003010 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003012 if (!compiler_push_fblock(c, EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003014 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 ADDOP(c, POP_BLOCK);
3016 compiler_pop_fblock(c, EXCEPT, body);
3017 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003018 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 compiler_use_next_block(c, except);
3020 for (i = 0; i < n; i++) {
3021 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003022 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 if (!handler->v.ExceptHandler.type && i < n-1)
3024 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003025 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 except = compiler_new_block(c);
3027 if (except == NULL)
3028 return 0;
3029 if (handler->v.ExceptHandler.type) {
3030 ADDOP(c, DUP_TOP);
3031 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon9af0e472020-01-14 10:12:45 +00003032 ADDOP_JABS(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 }
3034 ADDOP(c, POP_TOP);
3035 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003036 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003037
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003038 cleanup_end = compiler_new_block(c);
3039 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003040 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003041 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003042 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003043
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003044 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3045 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 /*
3048 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003049 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003050 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003051 try:
3052 # body
3053 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003054 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003055 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003056 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 /* second try: */
3059 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
3060 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003061 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003062 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003064 /* second # body */
3065 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003066 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003067 ADDOP(c, POP_BLOCK);
3068 ADDOP(c, POP_EXCEPT);
3069 /* name = None; del name */
3070 ADDOP_LOAD_CONST(c, Py_None);
3071 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3072 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
3073 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Mark Shannonfee55262019-11-21 09:11:43 +00003075 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003078 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003079 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082
Mark Shannonfee55262019-11-21 09:11:43 +00003083 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 }
3085 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003086 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003088 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003089 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003090 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091
Guido van Rossumb940e112007-01-10 16:19:56 +00003092 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 ADDOP(c, POP_TOP);
3094 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003095 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003096 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003098 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003099 ADDOP(c, POP_EXCEPT);
3100 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 compiler_use_next_block(c, except);
3103 }
Mark Shannonfee55262019-11-21 09:11:43 +00003104 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003106 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 compiler_use_next_block(c, end);
3108 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109}
3110
3111static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003112compiler_try(struct compiler *c, stmt_ty s) {
3113 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3114 return compiler_try_finally(c, s);
3115 else
3116 return compiler_try_except(c, s);
3117}
3118
3119
3120static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003121compiler_import_as(struct compiler *c, identifier name, identifier asname)
3122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 /* The IMPORT_NAME opcode was already generated. This function
3124 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003127 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003129 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3130 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003131 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003132 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003135 while (1) {
3136 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003138 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003139 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003140 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003141 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003143 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003144 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003145 if (dot == -1) {
3146 break;
3147 }
3148 ADDOP(c, ROT_TWO);
3149 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003151 if (!compiler_nameop(c, asname, Store)) {
3152 return 0;
3153 }
3154 ADDOP(c, POP_TOP);
3155 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
3157 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158}
3159
3160static int
3161compiler_import(struct compiler *c, stmt_ty s)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* The Import node stores a module name like a.b.c as a single
3164 string. This is convenient for all cases except
3165 import a.b.c as d
3166 where we need to parse that string to extract the individual
3167 module names.
3168 XXX Perhaps change the representation to make this case simpler?
3169 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003170 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 for (i = 0; i < n; i++) {
3173 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3174 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003176 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3177 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 if (alias->asname) {
3181 r = compiler_import_as(c, alias->name, alias->asname);
3182 if (!r)
3183 return r;
3184 }
3185 else {
3186 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003187 Py_ssize_t dot = PyUnicode_FindChar(
3188 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003189 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003190 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003191 if (tmp == NULL)
3192 return 0;
3193 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003195 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 Py_DECREF(tmp);
3197 }
3198 if (!r)
3199 return r;
3200 }
3201 }
3202 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203}
3204
3205static int
3206compiler_from_import(struct compiler *c, stmt_ty s)
3207{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003208 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003209 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (!empty_string) {
3213 empty_string = PyUnicode_FromString("");
3214 if (!empty_string)
3215 return 0;
3216 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003217
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003218 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003219
3220 names = PyTuple_New(n);
3221 if (!names)
3222 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 /* build up the names */
3225 for (i = 0; i < n; i++) {
3226 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3227 Py_INCREF(alias->name);
3228 PyTuple_SET_ITEM(names, i, alias->name);
3229 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003232 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 Py_DECREF(names);
3234 return compiler_error(c, "from __future__ imports must occur "
3235 "at the beginning of the file");
3236 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003237 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 if (s->v.ImportFrom.module) {
3240 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3241 }
3242 else {
3243 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3244 }
3245 for (i = 0; i < n; i++) {
3246 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3247 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003249 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 assert(n == 1);
3251 ADDOP(c, IMPORT_STAR);
3252 return 1;
3253 }
3254
3255 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3256 store_name = alias->name;
3257 if (alias->asname)
3258 store_name = alias->asname;
3259
3260 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 return 0;
3262 }
3263 }
3264 /* remove imported module */
3265 ADDOP(c, POP_TOP);
3266 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267}
3268
3269static int
3270compiler_assert(struct compiler *c, stmt_ty s)
3271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273
Georg Brandl8334fd92010-12-04 10:26:46 +00003274 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003277 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3278 {
3279 if (!compiler_warn(c, "assertion is always true, "
3280 "perhaps remove parentheses?"))
3281 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003282 return 0;
3283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 end = compiler_new_block(c);
3286 if (end == NULL)
3287 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003288 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3289 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003290 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 if (s->v.Assert.msg) {
3292 VISIT(c, expr, s->v.Assert.msg);
3293 ADDOP_I(c, CALL_FUNCTION, 1);
3294 }
3295 ADDOP_I(c, RAISE_VARARGS, 1);
3296 compiler_use_next_block(c, end);
3297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298}
3299
3300static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003301compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3302{
3303 if (c->c_interactive && c->c_nestlevel <= 1) {
3304 VISIT(c, expr, value);
3305 ADDOP(c, PRINT_EXPR);
3306 return 1;
3307 }
3308
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003309 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003310 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003311 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003312 }
3313
3314 VISIT(c, expr, value);
3315 ADDOP(c, POP_TOP);
3316 return 1;
3317}
3318
3319static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320compiler_visit_stmt(struct compiler *c, stmt_ty s)
3321{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003322 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003325 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 switch (s->kind) {
3328 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003329 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 case ClassDef_kind:
3331 return compiler_class(c, s);
3332 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003333 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 case Delete_kind:
3335 VISIT_SEQ(c, expr, s->v.Delete.targets)
3336 break;
3337 case Assign_kind:
3338 n = asdl_seq_LEN(s->v.Assign.targets);
3339 VISIT(c, expr, s->v.Assign.value);
3340 for (i = 0; i < n; i++) {
3341 if (i < n - 1)
3342 ADDOP(c, DUP_TOP);
3343 VISIT(c, expr,
3344 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3345 }
3346 break;
3347 case AugAssign_kind:
3348 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003349 case AnnAssign_kind:
3350 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 case For_kind:
3352 return compiler_for(c, s);
3353 case While_kind:
3354 return compiler_while(c, s);
3355 case If_kind:
3356 return compiler_if(c, s);
3357 case Raise_kind:
3358 n = 0;
3359 if (s->v.Raise.exc) {
3360 VISIT(c, expr, s->v.Raise.exc);
3361 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003362 if (s->v.Raise.cause) {
3363 VISIT(c, expr, s->v.Raise.cause);
3364 n++;
3365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003367 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003369 case Try_kind:
3370 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 case Assert_kind:
3372 return compiler_assert(c, s);
3373 case Import_kind:
3374 return compiler_import(c, s);
3375 case ImportFrom_kind:
3376 return compiler_from_import(c, s);
3377 case Global_kind:
3378 case Nonlocal_kind:
3379 break;
3380 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003381 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 case Pass_kind:
3383 break;
3384 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003385 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 case Continue_kind:
3387 return compiler_continue(c);
3388 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003389 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003390 case AsyncFunctionDef_kind:
3391 return compiler_function(c, s, 1);
3392 case AsyncWith_kind:
3393 return compiler_async_with(c, s, 0);
3394 case AsyncFor_kind:
3395 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 }
Yury Selivanov75445082015-05-11 22:57:16 -04003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399}
3400
3401static int
3402unaryop(unaryop_ty op)
3403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 switch (op) {
3405 case Invert:
3406 return UNARY_INVERT;
3407 case Not:
3408 return UNARY_NOT;
3409 case UAdd:
3410 return UNARY_POSITIVE;
3411 case USub:
3412 return UNARY_NEGATIVE;
3413 default:
3414 PyErr_Format(PyExc_SystemError,
3415 "unary op %d should not be possible", op);
3416 return 0;
3417 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418}
3419
3420static int
Andy Lester76d58772020-03-10 21:18:12 -05003421binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 switch (op) {
3424 case Add:
3425 return BINARY_ADD;
3426 case Sub:
3427 return BINARY_SUBTRACT;
3428 case Mult:
3429 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003430 case MatMult:
3431 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 case Div:
3433 return BINARY_TRUE_DIVIDE;
3434 case Mod:
3435 return BINARY_MODULO;
3436 case Pow:
3437 return BINARY_POWER;
3438 case LShift:
3439 return BINARY_LSHIFT;
3440 case RShift:
3441 return BINARY_RSHIFT;
3442 case BitOr:
3443 return BINARY_OR;
3444 case BitXor:
3445 return BINARY_XOR;
3446 case BitAnd:
3447 return BINARY_AND;
3448 case FloorDiv:
3449 return BINARY_FLOOR_DIVIDE;
3450 default:
3451 PyErr_Format(PyExc_SystemError,
3452 "binary op %d should not be possible", op);
3453 return 0;
3454 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003455}
3456
3457static int
Andy Lester76d58772020-03-10 21:18:12 -05003458inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 switch (op) {
3461 case Add:
3462 return INPLACE_ADD;
3463 case Sub:
3464 return INPLACE_SUBTRACT;
3465 case Mult:
3466 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003467 case MatMult:
3468 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 case Div:
3470 return INPLACE_TRUE_DIVIDE;
3471 case Mod:
3472 return INPLACE_MODULO;
3473 case Pow:
3474 return INPLACE_POWER;
3475 case LShift:
3476 return INPLACE_LSHIFT;
3477 case RShift:
3478 return INPLACE_RSHIFT;
3479 case BitOr:
3480 return INPLACE_OR;
3481 case BitXor:
3482 return INPLACE_XOR;
3483 case BitAnd:
3484 return INPLACE_AND;
3485 case FloorDiv:
3486 return INPLACE_FLOOR_DIVIDE;
3487 default:
3488 PyErr_Format(PyExc_SystemError,
3489 "inplace binary op %d should not be possible", op);
3490 return 0;
3491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003492}
3493
3494static int
3495compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3496{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003497 int op, scope;
3498 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 PyObject *dict = c->u->u_names;
3502 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003504 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3505 !_PyUnicode_EqualToASCIIString(name, "True") &&
3506 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003507
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003508 mangled = _Py_Mangle(c->u->u_private, name);
3509 if (!mangled)
3510 return 0;
3511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 op = 0;
3513 optype = OP_NAME;
3514 scope = PyST_GetScope(c->u->u_ste, mangled);
3515 switch (scope) {
3516 case FREE:
3517 dict = c->u->u_freevars;
3518 optype = OP_DEREF;
3519 break;
3520 case CELL:
3521 dict = c->u->u_cellvars;
3522 optype = OP_DEREF;
3523 break;
3524 case LOCAL:
3525 if (c->u->u_ste->ste_type == FunctionBlock)
3526 optype = OP_FAST;
3527 break;
3528 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003529 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 optype = OP_GLOBAL;
3531 break;
3532 case GLOBAL_EXPLICIT:
3533 optype = OP_GLOBAL;
3534 break;
3535 default:
3536 /* scope can be 0 */
3537 break;
3538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003541 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 switch (optype) {
3544 case OP_DEREF:
3545 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003546 case Load:
3547 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3548 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003549 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003550 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 }
3552 break;
3553 case OP_FAST:
3554 switch (ctx) {
3555 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003556 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003559 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 return 1;
3561 case OP_GLOBAL:
3562 switch (ctx) {
3563 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003564 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 }
3567 break;
3568 case OP_NAME:
3569 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003570 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003571 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 }
3574 break;
3575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003578 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 Py_DECREF(mangled);
3580 if (arg < 0)
3581 return 0;
3582 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583}
3584
3585static int
3586compiler_boolop(struct compiler *c, expr_ty e)
3587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003589 int jumpi;
3590 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 assert(e->kind == BoolOp_kind);
3594 if (e->v.BoolOp.op == And)
3595 jumpi = JUMP_IF_FALSE_OR_POP;
3596 else
3597 jumpi = JUMP_IF_TRUE_OR_POP;
3598 end = compiler_new_block(c);
3599 if (end == NULL)
3600 return 0;
3601 s = e->v.BoolOp.values;
3602 n = asdl_seq_LEN(s) - 1;
3603 assert(n >= 0);
3604 for (i = 0; i < n; ++i) {
3605 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3606 ADDOP_JABS(c, jumpi, end);
3607 }
3608 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3609 compiler_use_next_block(c, end);
3610 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611}
3612
3613static int
Mark Shannon13bc1392020-01-23 09:25:17 +00003614starunpack_helper(struct compiler *c, asdl_seq *elts, int pushed,
3615 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003616{
3617 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003618 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003619 if (n > 2 && are_all_items_const(elts, 0, n)) {
3620 PyObject *folded = PyTuple_New(n);
3621 if (folded == NULL) {
3622 return 0;
3623 }
3624 PyObject *val;
3625 for (i = 0; i < n; i++) {
3626 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3627 Py_INCREF(val);
3628 PyTuple_SET_ITEM(folded, i, val);
3629 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003630 if (tuple) {
3631 ADDOP_LOAD_CONST_NEW(c, folded);
3632 } else {
3633 if (add == SET_ADD) {
3634 Py_SETREF(folded, PyFrozenSet_New(folded));
3635 if (folded == NULL) {
3636 return 0;
3637 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003638 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003639 ADDOP_I(c, build, pushed);
3640 ADDOP_LOAD_CONST_NEW(c, folded);
3641 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003642 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003643 return 1;
3644 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003645
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003646 for (i = 0; i < n; i++) {
3647 expr_ty elt = asdl_seq_GET(elts, i);
3648 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003649 seen_star = 1;
3650 }
3651 }
3652 if (seen_star) {
3653 seen_star = 0;
3654 for (i = 0; i < n; i++) {
3655 expr_ty elt = asdl_seq_GET(elts, i);
3656 if (elt->kind == Starred_kind) {
3657 if (seen_star == 0) {
3658 ADDOP_I(c, build, i+pushed);
3659 seen_star = 1;
3660 }
3661 VISIT(c, expr, elt->v.Starred.value);
3662 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003663 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003664 else {
3665 VISIT(c, expr, elt);
3666 if (seen_star) {
3667 ADDOP_I(c, add, 1);
3668 }
3669 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003670 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003671 assert(seen_star);
3672 if (tuple) {
3673 ADDOP(c, LIST_TO_TUPLE);
3674 }
3675 }
3676 else {
3677 for (i = 0; i < n; i++) {
3678 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003679 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003680 }
3681 if (tuple) {
3682 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3683 } else {
3684 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003685 }
3686 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 return 1;
3688}
3689
3690static int
3691assignment_helper(struct compiler *c, asdl_seq *elts)
3692{
3693 Py_ssize_t n = asdl_seq_LEN(elts);
3694 Py_ssize_t i;
3695 int seen_star = 0;
3696 for (i = 0; i < n; i++) {
3697 expr_ty elt = asdl_seq_GET(elts, i);
3698 if (elt->kind == Starred_kind && !seen_star) {
3699 if ((i >= (1 << 8)) ||
3700 (n-i-1 >= (INT_MAX >> 8)))
3701 return compiler_error(c,
3702 "too many expressions in "
3703 "star-unpacking assignment");
3704 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3705 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003706 }
3707 else if (elt->kind == Starred_kind) {
3708 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003709 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 }
3711 }
3712 if (!seen_star) {
3713 ADDOP_I(c, UNPACK_SEQUENCE, n);
3714 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003715 for (i = 0; i < n; i++) {
3716 expr_ty elt = asdl_seq_GET(elts, i);
3717 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3718 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003719 return 1;
3720}
3721
3722static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723compiler_list(struct compiler *c, expr_ty e)
3724{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003726 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003730 return starunpack_helper(c, elts, 0, BUILD_LIST,
3731 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 else
3734 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736}
3737
3738static int
3739compiler_tuple(struct compiler *c, expr_ty e)
3740{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003741 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003742 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003743 return assignment_helper(c, elts);
3744 }
3745 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003746 return starunpack_helper(c, elts, 0, BUILD_LIST,
3747 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003748 }
3749 else
3750 VISIT_SEQ(c, expr, elts);
3751 return 1;
3752}
3753
3754static int
3755compiler_set(struct compiler *c, expr_ty e)
3756{
Mark Shannon13bc1392020-01-23 09:25:17 +00003757 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3758 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003759}
3760
3761static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003762are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3763{
3764 Py_ssize_t i;
3765 for (i = begin; i < end; i++) {
3766 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003767 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003768 return 0;
3769 }
3770 return 1;
3771}
3772
3773static int
3774compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3775{
3776 Py_ssize_t i, n = end - begin;
3777 PyObject *keys, *key;
3778 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3779 for (i = begin; i < end; i++) {
3780 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3781 }
3782 keys = PyTuple_New(n);
3783 if (keys == NULL) {
3784 return 0;
3785 }
3786 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003787 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003788 Py_INCREF(key);
3789 PyTuple_SET_ITEM(keys, i - begin, key);
3790 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003791 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003792 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3793 }
3794 else {
3795 for (i = begin; i < end; i++) {
3796 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3797 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3798 }
3799 ADDOP_I(c, BUILD_MAP, n);
3800 }
3801 return 1;
3802}
3803
3804static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805compiler_dict(struct compiler *c, expr_ty e)
3806{
Victor Stinner976bb402016-03-23 11:36:19 +01003807 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003808 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 int is_unpacking = 0;
3810 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003811 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003812 elements = 0;
3813 for (i = 0; i < n; i++) {
3814 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003815 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003816 if (elements) {
3817 if (!compiler_subdict(c, e, i - elements, i)) {
3818 return 0;
3819 }
3820 if (have_dict) {
3821 ADDOP_I(c, DICT_UPDATE, 1);
3822 }
3823 have_dict = 1;
3824 elements = 0;
3825 }
3826 if (have_dict == 0) {
3827 ADDOP_I(c, BUILD_MAP, 0);
3828 have_dict = 1;
3829 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003830 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003831 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003832 }
3833 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003834 if (elements == 0xFFFF) {
3835 if (!compiler_subdict(c, e, i - elements, i)) {
3836 return 0;
3837 }
3838 if (have_dict) {
3839 ADDOP_I(c, DICT_UPDATE, 1);
3840 }
3841 have_dict = 1;
3842 elements = 0;
3843 }
3844 else {
3845 elements++;
3846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 }
3848 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003849 if (elements) {
3850 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003851 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003852 }
3853 if (have_dict) {
3854 ADDOP_I(c, DICT_UPDATE, 1);
3855 }
3856 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003857 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003858 if (!have_dict) {
3859 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 }
3861 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862}
3863
3864static int
3865compiler_compare(struct compiler *c, expr_ty e)
3866{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003867 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003869 if (!check_compare(c, e)) {
3870 return 0;
3871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003873 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3874 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3875 if (n == 0) {
3876 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003877 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003878 }
3879 else {
3880 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 if (cleanup == NULL)
3882 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003883 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 VISIT(c, expr,
3885 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003886 ADDOP(c, DUP_TOP);
3887 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003888 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003889 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3890 NEXT_BLOCK(c);
3891 }
3892 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003893 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 basicblock *end = compiler_new_block(c);
3895 if (end == NULL)
3896 return 0;
3897 ADDOP_JREL(c, JUMP_FORWARD, end);
3898 compiler_use_next_block(c, cleanup);
3899 ADDOP(c, ROT_TWO);
3900 ADDOP(c, POP_TOP);
3901 compiler_use_next_block(c, end);
3902 }
3903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904}
3905
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003906static PyTypeObject *
3907infer_type(expr_ty e)
3908{
3909 switch (e->kind) {
3910 case Tuple_kind:
3911 return &PyTuple_Type;
3912 case List_kind:
3913 case ListComp_kind:
3914 return &PyList_Type;
3915 case Dict_kind:
3916 case DictComp_kind:
3917 return &PyDict_Type;
3918 case Set_kind:
3919 case SetComp_kind:
3920 return &PySet_Type;
3921 case GeneratorExp_kind:
3922 return &PyGen_Type;
3923 case Lambda_kind:
3924 return &PyFunction_Type;
3925 case JoinedStr_kind:
3926 case FormattedValue_kind:
3927 return &PyUnicode_Type;
3928 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003929 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003930 default:
3931 return NULL;
3932 }
3933}
3934
3935static int
3936check_caller(struct compiler *c, expr_ty e)
3937{
3938 switch (e->kind) {
3939 case Constant_kind:
3940 case Tuple_kind:
3941 case List_kind:
3942 case ListComp_kind:
3943 case Dict_kind:
3944 case DictComp_kind:
3945 case Set_kind:
3946 case SetComp_kind:
3947 case GeneratorExp_kind:
3948 case JoinedStr_kind:
3949 case FormattedValue_kind:
3950 return compiler_warn(c, "'%.200s' object is not callable; "
3951 "perhaps you missed a comma?",
3952 infer_type(e)->tp_name);
3953 default:
3954 return 1;
3955 }
3956}
3957
3958static int
3959check_subscripter(struct compiler *c, expr_ty e)
3960{
3961 PyObject *v;
3962
3963 switch (e->kind) {
3964 case Constant_kind:
3965 v = e->v.Constant.value;
3966 if (!(v == Py_None || v == Py_Ellipsis ||
3967 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3968 PyAnySet_Check(v)))
3969 {
3970 return 1;
3971 }
3972 /* fall through */
3973 case Set_kind:
3974 case SetComp_kind:
3975 case GeneratorExp_kind:
3976 case Lambda_kind:
3977 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3978 "perhaps you missed a comma?",
3979 infer_type(e)->tp_name);
3980 default:
3981 return 1;
3982 }
3983}
3984
3985static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02003986check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003987{
3988 PyObject *v;
3989
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02003990 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003991 if (index_type == NULL
3992 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3993 || index_type == &PySlice_Type) {
3994 return 1;
3995 }
3996
3997 switch (e->kind) {
3998 case Constant_kind:
3999 v = e->v.Constant.value;
4000 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4001 return 1;
4002 }
4003 /* fall through */
4004 case Tuple_kind:
4005 case List_kind:
4006 case ListComp_kind:
4007 case JoinedStr_kind:
4008 case FormattedValue_kind:
4009 return compiler_warn(c, "%.200s indices must be integers or slices, "
4010 "not %.200s; "
4011 "perhaps you missed a comma?",
4012 infer_type(e)->tp_name,
4013 index_type->tp_name);
4014 default:
4015 return 1;
4016 }
4017}
4018
Zackery Spytz97f5de02019-03-22 01:30:32 -06004019// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004021maybe_optimize_method_call(struct compiler *c, expr_ty e)
4022{
4023 Py_ssize_t argsl, i;
4024 expr_ty meth = e->v.Call.func;
4025 asdl_seq *args = e->v.Call.args;
4026
4027 /* Check that the call node is an attribute access, and that
4028 the call doesn't have keyword parameters. */
4029 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4030 asdl_seq_LEN(e->v.Call.keywords))
4031 return -1;
4032
4033 /* Check that there are no *varargs types of arguments. */
4034 argsl = asdl_seq_LEN(args);
4035 for (i = 0; i < argsl; i++) {
4036 expr_ty elt = asdl_seq_GET(args, i);
4037 if (elt->kind == Starred_kind) {
4038 return -1;
4039 }
4040 }
4041
4042 /* Alright, we can optimize the code. */
4043 VISIT(c, expr, meth->v.Attribute.value);
4044 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4045 VISIT_SEQ(c, expr, e->v.Call.args);
4046 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4047 return 1;
4048}
4049
4050static int
Zackery Spytz08050e92020-04-06 00:47:47 -06004051validate_keywords(struct compiler *c, asdl_seq *keywords)
4052{
4053 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4054 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004055 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4056 if (key->arg == NULL) {
4057 continue;
4058 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004059 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004060 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4061 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4062 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4063 if (msg == NULL) {
4064 return -1;
4065 }
4066 c->u->u_col_offset = other->col_offset;
4067 compiler_error(c, PyUnicode_AsUTF8(msg));
4068 Py_DECREF(msg);
4069 return -1;
4070 }
4071 }
4072 }
4073 return 0;
4074}
4075
4076static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077compiler_call(struct compiler *c, expr_ty e)
4078{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004079 int ret = maybe_optimize_method_call(c, e);
4080 if (ret >= 0) {
4081 return ret;
4082 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004083 if (!check_caller(c, e->v.Call.func)) {
4084 return 0;
4085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 VISIT(c, expr, e->v.Call.func);
4087 return compiler_call_helper(c, 0,
4088 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004089 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004090}
4091
Eric V. Smith235a6f02015-09-19 14:51:32 -04004092static int
4093compiler_joined_str(struct compiler *c, expr_ty e)
4094{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004095 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004096 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4097 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004098 return 1;
4099}
4100
Eric V. Smitha78c7952015-11-03 12:45:05 -05004101/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004102static int
4103compiler_formatted_value(struct compiler *c, expr_ty e)
4104{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004105 /* Our oparg encodes 2 pieces of information: the conversion
4106 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004107
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004108 Convert the conversion char to 3 bits:
4109 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004110 !s : 001 0x1 FVC_STR
4111 !r : 010 0x2 FVC_REPR
4112 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004113
Eric V. Smitha78c7952015-11-03 12:45:05 -05004114 next bit is whether or not we have a format spec:
4115 yes : 100 0x4
4116 no : 000 0x0
4117 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004118
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004119 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004120 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004121
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004122 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004123 VISIT(c, expr, e->v.FormattedValue.value);
4124
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004125 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004126 case 's': oparg = FVC_STR; break;
4127 case 'r': oparg = FVC_REPR; break;
4128 case 'a': oparg = FVC_ASCII; break;
4129 case -1: oparg = FVC_NONE; break;
4130 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004131 PyErr_Format(PyExc_SystemError,
4132 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004133 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004134 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004135 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004136 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004137 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004138 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004139 }
4140
Eric V. Smitha78c7952015-11-03 12:45:05 -05004141 /* And push our opcode and oparg */
4142 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004143
Eric V. Smith235a6f02015-09-19 14:51:32 -04004144 return 1;
4145}
4146
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004147static int
4148compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4149{
4150 Py_ssize_t i, n = end - begin;
4151 keyword_ty kw;
4152 PyObject *keys, *key;
4153 assert(n > 0);
4154 if (n > 1) {
4155 for (i = begin; i < end; i++) {
4156 kw = asdl_seq_GET(keywords, i);
4157 VISIT(c, expr, kw->value);
4158 }
4159 keys = PyTuple_New(n);
4160 if (keys == NULL) {
4161 return 0;
4162 }
4163 for (i = begin; i < end; i++) {
4164 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4165 Py_INCREF(key);
4166 PyTuple_SET_ITEM(keys, i - begin, key);
4167 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004168 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004169 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4170 }
4171 else {
4172 /* a for loop only executes once */
4173 for (i = begin; i < end; i++) {
4174 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004175 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004176 VISIT(c, expr, kw->value);
4177 }
4178 ADDOP_I(c, BUILD_MAP, n);
4179 }
4180 return 1;
4181}
4182
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004183/* shared code between compiler_call and compiler_class */
4184static int
4185compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004186 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004187 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004188 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004189{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004190 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004191
Pablo Galindo254ec782020-04-03 20:37:13 +01004192 if (validate_keywords(c, keywords) == -1) {
4193 return 0;
4194 }
4195
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004196 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004197 nkwelts = asdl_seq_LEN(keywords);
4198
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004199 for (i = 0; i < nelts; i++) {
4200 expr_ty elt = asdl_seq_GET(args, i);
4201 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004202 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004203 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004204 }
4205 for (i = 0; i < nkwelts; i++) {
4206 keyword_ty kw = asdl_seq_GET(keywords, i);
4207 if (kw->arg == NULL) {
4208 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004211
Mark Shannon13bc1392020-01-23 09:25:17 +00004212 /* No * or ** args, so can use faster calling sequence */
4213 for (i = 0; i < nelts; i++) {
4214 expr_ty elt = asdl_seq_GET(args, i);
4215 assert(elt->kind != Starred_kind);
4216 VISIT(c, expr, elt);
4217 }
4218 if (nkwelts) {
4219 PyObject *names;
4220 VISIT_SEQ(c, keyword, keywords);
4221 names = PyTuple_New(nkwelts);
4222 if (names == NULL) {
4223 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004224 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004225 for (i = 0; i < nkwelts; i++) {
4226 keyword_ty kw = asdl_seq_GET(keywords, i);
4227 Py_INCREF(kw->arg);
4228 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004229 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004230 ADDOP_LOAD_CONST_NEW(c, names);
4231 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4232 return 1;
4233 }
4234 else {
4235 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4236 return 1;
4237 }
4238
4239ex_call:
4240
4241 /* Do positional arguments. */
4242 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4243 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4244 }
4245 else if (starunpack_helper(c, args, n, BUILD_LIST,
4246 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4247 return 0;
4248 }
4249 /* Then keyword arguments */
4250 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004251 /* Has a new dict been pushed */
4252 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004253
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004254 nseen = 0; /* the number of keyword arguments on the stack following */
4255 for (i = 0; i < nkwelts; i++) {
4256 keyword_ty kw = asdl_seq_GET(keywords, i);
4257 if (kw->arg == NULL) {
4258 /* A keyword argument unpacking. */
4259 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004260 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004261 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004262 }
4263 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004265 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004266 if (!have_dict) {
4267 ADDOP_I(c, BUILD_MAP, 0);
4268 have_dict = 1;
4269 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004270 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004271 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004272 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004273 else {
4274 nseen++;
4275 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004276 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004277 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004278 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004279 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004280 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004281 }
4282 if (have_dict) {
4283 ADDOP_I(c, DICT_MERGE, 1);
4284 }
4285 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004286 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004287 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004289 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4290 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291}
4292
Nick Coghlan650f0d02007-04-15 12:05:43 +00004293
4294/* List and set comprehensions and generator expressions work by creating a
4295 nested function to perform the actual iteration. This means that the
4296 iteration variables don't leak into the current scope.
4297 The defined function is called immediately following its definition, with the
4298 result of that call being the result of the expression.
4299 The LC/SC version returns the populated container, while the GE version is
4300 flagged in symtable.c as a generator, so it returns the generator object
4301 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004302
4303 Possible cleanups:
4304 - iterate over the generator sequence instead of using recursion
4305*/
4306
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309compiler_comprehension_generator(struct compiler *c,
4310 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004311 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004313{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004314 comprehension_ty gen;
4315 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4316 if (gen->is_async) {
4317 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004318 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004319 } else {
4320 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004321 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004322 }
4323}
4324
4325static int
4326compiler_sync_comprehension_generator(struct compiler *c,
4327 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004328 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004329 expr_ty elt, expr_ty val, int type)
4330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 /* generate code for the iterator, then each of the ifs,
4332 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 comprehension_ty gen;
4335 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004336 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 start = compiler_new_block(c);
4339 skip = compiler_new_block(c);
4340 if_cleanup = compiler_new_block(c);
4341 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4344 anchor == NULL)
4345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (gen_index == 0) {
4350 /* Receive outermost iter as an implicit argument */
4351 c->u->u_argcount = 1;
4352 ADDOP_I(c, LOAD_FAST, 0);
4353 }
4354 else {
4355 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004356 /* Fast path for the temporary variable assignment idiom:
4357 for y in [f(x)]
4358 */
4359 asdl_seq *elts;
4360 switch (gen->iter->kind) {
4361 case List_kind:
4362 elts = gen->iter->v.List.elts;
4363 break;
4364 case Tuple_kind:
4365 elts = gen->iter->v.Tuple.elts;
4366 break;
4367 default:
4368 elts = NULL;
4369 }
4370 if (asdl_seq_LEN(elts) == 1) {
4371 expr_ty elt = asdl_seq_GET(elts, 0);
4372 if (elt->kind != Starred_kind) {
4373 VISIT(c, expr, elt);
4374 start = NULL;
4375 }
4376 }
4377 if (start) {
4378 VISIT(c, expr, gen->iter);
4379 ADDOP(c, GET_ITER);
4380 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004382 if (start) {
4383 depth++;
4384 compiler_use_next_block(c, start);
4385 ADDOP_JREL(c, FOR_ITER, anchor);
4386 NEXT_BLOCK(c);
4387 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 /* XXX this needs to be cleaned up...a lot! */
4391 n = asdl_seq_LEN(gen->ifs);
4392 for (i = 0; i < n; i++) {
4393 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004394 if (!compiler_jump_if(c, e, if_cleanup, 0))
4395 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 NEXT_BLOCK(c);
4397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 if (++gen_index < asdl_seq_LEN(generators))
4400 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004401 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 elt, val, type))
4403 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 /* only append after the last for generator */
4406 if (gen_index >= asdl_seq_LEN(generators)) {
4407 /* comprehension specific code */
4408 switch (type) {
4409 case COMP_GENEXP:
4410 VISIT(c, expr, elt);
4411 ADDOP(c, YIELD_VALUE);
4412 ADDOP(c, POP_TOP);
4413 break;
4414 case COMP_LISTCOMP:
4415 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004416 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 break;
4418 case COMP_SETCOMP:
4419 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004420 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 break;
4422 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004423 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004426 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004427 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 break;
4429 default:
4430 return 0;
4431 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 compiler_use_next_block(c, skip);
4434 }
4435 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004436 if (start) {
4437 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4438 compiler_use_next_block(c, anchor);
4439 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440
4441 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442}
4443
4444static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004445compiler_async_comprehension_generator(struct compiler *c,
4446 asdl_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004447 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004448 expr_ty elt, expr_ty val, int type)
4449{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004450 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004451 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004452 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004453 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004454 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004455 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004456
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004457 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004458 return 0;
4459 }
4460
4461 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4462
4463 if (gen_index == 0) {
4464 /* Receive outermost iter as an implicit argument */
4465 c->u->u_argcount = 1;
4466 ADDOP_I(c, LOAD_FAST, 0);
4467 }
4468 else {
4469 /* Sub-iter - calculate on the fly */
4470 VISIT(c, expr, gen->iter);
4471 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004472 }
4473
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004474 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004475
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004476 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004477 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004478 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004479 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004480 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004481 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004482
4483 n = asdl_seq_LEN(gen->ifs);
4484 for (i = 0; i < n; i++) {
4485 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004486 if (!compiler_jump_if(c, e, if_cleanup, 0))
4487 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488 NEXT_BLOCK(c);
4489 }
4490
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004491 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492 if (++gen_index < asdl_seq_LEN(generators))
4493 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004494 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004495 elt, val, type))
4496 return 0;
4497
4498 /* only append after the last for generator */
4499 if (gen_index >= asdl_seq_LEN(generators)) {
4500 /* comprehension specific code */
4501 switch (type) {
4502 case COMP_GENEXP:
4503 VISIT(c, expr, elt);
4504 ADDOP(c, YIELD_VALUE);
4505 ADDOP(c, POP_TOP);
4506 break;
4507 case COMP_LISTCOMP:
4508 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004509 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510 break;
4511 case COMP_SETCOMP:
4512 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004513 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514 break;
4515 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004516 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004517 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004518 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004519 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004520 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521 break;
4522 default:
4523 return 0;
4524 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 }
4526 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004527 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4528
4529 compiler_use_next_block(c, except);
4530 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531
4532 return 1;
4533}
4534
4535static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004536compiler_comprehension(struct compiler *c, expr_ty e, int type,
4537 identifier name, asdl_seq *generators, expr_ty elt,
4538 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004541 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004542 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004543 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004544
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004545 if (IS_TOP_LEVEL_AWAIT(c)) {
4546 c->u->u_ste->ste_coroutine = 1;
4547 }
4548 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004549
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004550 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004551 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4552 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 }
4556
4557 is_async_generator = c->u->u_ste->ste_coroutine;
4558
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004559 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004560 compiler_error(c, "asynchronous comprehension outside of "
4561 "an asynchronous function");
4562 goto error_in_scope;
4563 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 if (type != COMP_GENEXP) {
4566 int op;
4567 switch (type) {
4568 case COMP_LISTCOMP:
4569 op = BUILD_LIST;
4570 break;
4571 case COMP_SETCOMP:
4572 op = BUILD_SET;
4573 break;
4574 case COMP_DICTCOMP:
4575 op = BUILD_MAP;
4576 break;
4577 default:
4578 PyErr_Format(PyExc_SystemError,
4579 "unknown comprehension type %d", type);
4580 goto error_in_scope;
4581 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 ADDOP_I(c, op, 0);
4584 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004585
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004586 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 val, type))
4588 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 if (type != COMP_GENEXP) {
4591 ADDOP(c, RETURN_VALUE);
4592 }
4593
4594 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004595 qualname = c->u->u_qualname;
4596 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004598 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 goto error;
4600
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004601 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004603 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 Py_DECREF(co);
4605
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004606 VISIT(c, expr, outermost->iter);
4607
4608 if (outermost->is_async) {
4609 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004610 } else {
4611 ADDOP(c, GET_ITER);
4612 }
4613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004615
4616 if (is_async_generator && type != COMP_GENEXP) {
4617 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004618 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004619 ADDOP(c, YIELD_FROM);
4620 }
4621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004623error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004625error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004626 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 Py_XDECREF(co);
4628 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004629}
4630
4631static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004632compiler_genexp(struct compiler *c, expr_ty e)
4633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 static identifier name;
4635 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004636 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 if (!name)
4638 return 0;
4639 }
4640 assert(e->kind == GeneratorExp_kind);
4641 return compiler_comprehension(c, e, COMP_GENEXP, name,
4642 e->v.GeneratorExp.generators,
4643 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004644}
4645
4646static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004647compiler_listcomp(struct compiler *c, expr_ty e)
4648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 static identifier name;
4650 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004651 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (!name)
4653 return 0;
4654 }
4655 assert(e->kind == ListComp_kind);
4656 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4657 e->v.ListComp.generators,
4658 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004659}
4660
4661static int
4662compiler_setcomp(struct compiler *c, expr_ty e)
4663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 static identifier name;
4665 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004666 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 if (!name)
4668 return 0;
4669 }
4670 assert(e->kind == SetComp_kind);
4671 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4672 e->v.SetComp.generators,
4673 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004674}
4675
4676
4677static int
4678compiler_dictcomp(struct compiler *c, expr_ty e)
4679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 static identifier name;
4681 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004682 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 if (!name)
4684 return 0;
4685 }
4686 assert(e->kind == DictComp_kind);
4687 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4688 e->v.DictComp.generators,
4689 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004690}
4691
4692
4693static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004694compiler_visit_keyword(struct compiler *c, keyword_ty k)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 VISIT(c, expr, k->value);
4697 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698}
4699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004701 whether they are true or false.
4702
4703 Return values: 1 for true, 0 for false, -1 for non-constant.
4704 */
4705
4706static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004707expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004708{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004709 if (e->kind == Constant_kind) {
4710 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004711 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004712 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004713}
4714
Mark Shannonfee55262019-11-21 09:11:43 +00004715static int
4716compiler_with_except_finish(struct compiler *c) {
4717 basicblock *exit;
4718 exit = compiler_new_block(c);
4719 if (exit == NULL)
4720 return 0;
4721 ADDOP_JABS(c, POP_JUMP_IF_TRUE, exit);
4722 ADDOP(c, RERAISE);
4723 compiler_use_next_block(c, exit);
4724 ADDOP(c, POP_TOP);
4725 ADDOP(c, POP_TOP);
4726 ADDOP(c, POP_TOP);
4727 ADDOP(c, POP_EXCEPT);
4728 ADDOP(c, POP_TOP);
4729 return 1;
4730}
Yury Selivanov75445082015-05-11 22:57:16 -04004731
4732/*
4733 Implements the async with statement.
4734
4735 The semantics outlined in that PEP are as follows:
4736
4737 async with EXPR as VAR:
4738 BLOCK
4739
4740 It is implemented roughly as:
4741
4742 context = EXPR
4743 exit = context.__aexit__ # not calling it
4744 value = await context.__aenter__()
4745 try:
4746 VAR = value # if VAR present in the syntax
4747 BLOCK
4748 finally:
4749 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004750 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004751 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004752 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004753 if not (await exit(*exc)):
4754 raise
4755 */
4756static int
4757compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4758{
Mark Shannonfee55262019-11-21 09:11:43 +00004759 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004760 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4761
4762 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004763 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004764 c->u->u_ste->ste_coroutine = 1;
4765 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004766 return compiler_error(c, "'async with' outside async function");
4767 }
Yury Selivanov75445082015-05-11 22:57:16 -04004768
4769 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004770 final = compiler_new_block(c);
4771 exit = compiler_new_block(c);
4772 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004773 return 0;
4774
4775 /* Evaluate EXPR */
4776 VISIT(c, expr, item->context_expr);
4777
4778 ADDOP(c, BEFORE_ASYNC_WITH);
4779 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004780 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004781 ADDOP(c, YIELD_FROM);
4782
Mark Shannonfee55262019-11-21 09:11:43 +00004783 ADDOP_JREL(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004784
4785 /* SETUP_ASYNC_WITH pushes a finally block. */
4786 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004787 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004788 return 0;
4789 }
4790
4791 if (item->optional_vars) {
4792 VISIT(c, expr, item->optional_vars);
4793 }
4794 else {
4795 /* Discard result from context.__aenter__() */
4796 ADDOP(c, POP_TOP);
4797 }
4798
4799 pos++;
4800 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4801 /* BLOCK code */
4802 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4803 else if (!compiler_async_with(c, s, pos))
4804 return 0;
4805
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004806 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004807 ADDOP(c, POP_BLOCK);
4808 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004809
Mark Shannonfee55262019-11-21 09:11:43 +00004810 /* For successful outcome:
4811 * call __exit__(None, None, None)
4812 */
4813 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004814 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004815 ADDOP(c, GET_AWAITABLE);
4816 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4817 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004818
Mark Shannonfee55262019-11-21 09:11:43 +00004819 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004820
Mark Shannonfee55262019-11-21 09:11:43 +00004821 ADDOP_JABS(c, JUMP_ABSOLUTE, exit);
4822
4823 /* For exceptional outcome: */
4824 compiler_use_next_block(c, final);
4825
4826 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004827 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004828 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004829 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004830 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004831
Mark Shannonfee55262019-11-21 09:11:43 +00004832compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004833 return 1;
4834}
4835
4836
Guido van Rossumc2e20742006-02-27 22:32:47 +00004837/*
4838 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004839 with EXPR as VAR:
4840 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004841 is implemented as:
4842 <code for EXPR>
4843 SETUP_WITH E
4844 <code to store to VAR> or POP_TOP
4845 <code for BLOCK>
4846 LOAD_CONST (None, None, None)
4847 CALL_FUNCTION_EX 0
4848 JUMP_FORWARD EXIT
4849 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4850 POP_JUMP_IF_TRUE T:
4851 RERAISE
4852 T: POP_TOP * 3 (remove exception from stack)
4853 POP_EXCEPT
4854 POP_TOP
4855 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004856 */
Mark Shannonfee55262019-11-21 09:11:43 +00004857
Guido van Rossumc2e20742006-02-27 22:32:47 +00004858static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004859compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004860{
Mark Shannonfee55262019-11-21 09:11:43 +00004861 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004862 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004863
4864 assert(s->kind == With_kind);
4865
Guido van Rossumc2e20742006-02-27 22:32:47 +00004866 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004867 final = compiler_new_block(c);
4868 exit = compiler_new_block(c);
4869 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004870 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004871
Thomas Wouters477c8d52006-05-27 19:21:47 +00004872 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004873 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004874 /* Will push bound __exit__ */
4875 ADDOP_JREL(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004876
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004877 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004878 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004879 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004880 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004881 }
4882
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004883 if (item->optional_vars) {
4884 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004885 }
4886 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004888 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004889 }
4890
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004891 pos++;
4892 if (pos == asdl_seq_LEN(s->v.With.items))
4893 /* BLOCK code */
4894 VISIT_SEQ(c, stmt, s->v.With.body)
4895 else if (!compiler_with(c, s, pos))
4896 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004897
Guido van Rossumc2e20742006-02-27 22:32:47 +00004898 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004899 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004900
Mark Shannonfee55262019-11-21 09:11:43 +00004901 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004902
Mark Shannonfee55262019-11-21 09:11:43 +00004903 /* For successful outcome:
4904 * call __exit__(None, None, None)
4905 */
4906 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004907 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004908 ADDOP(c, POP_TOP);
4909 ADDOP_JREL(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910
Mark Shannonfee55262019-11-21 09:11:43 +00004911 /* For exceptional outcome: */
4912 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913
Mark Shannonfee55262019-11-21 09:11:43 +00004914 ADDOP(c, WITH_EXCEPT_START);
4915 compiler_with_except_finish(c);
4916
4917 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918 return 1;
4919}
4920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004921static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004922compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004925 case NamedExpr_kind:
4926 VISIT(c, expr, e->v.NamedExpr.value);
4927 ADDOP(c, DUP_TOP);
4928 VISIT(c, expr, e->v.NamedExpr.target);
4929 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 case BoolOp_kind:
4931 return compiler_boolop(c, e);
4932 case BinOp_kind:
4933 VISIT(c, expr, e->v.BinOp.left);
4934 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004935 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 break;
4937 case UnaryOp_kind:
4938 VISIT(c, expr, e->v.UnaryOp.operand);
4939 ADDOP(c, unaryop(e->v.UnaryOp.op));
4940 break;
4941 case Lambda_kind:
4942 return compiler_lambda(c, e);
4943 case IfExp_kind:
4944 return compiler_ifexp(c, e);
4945 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004946 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004948 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 case GeneratorExp_kind:
4950 return compiler_genexp(c, e);
4951 case ListComp_kind:
4952 return compiler_listcomp(c, e);
4953 case SetComp_kind:
4954 return compiler_setcomp(c, e);
4955 case DictComp_kind:
4956 return compiler_dictcomp(c, e);
4957 case Yield_kind:
4958 if (c->u->u_ste->ste_type != FunctionBlock)
4959 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004960 if (e->v.Yield.value) {
4961 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 }
4963 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004964 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004966 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004968 case YieldFrom_kind:
4969 if (c->u->u_ste->ste_type != FunctionBlock)
4970 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004971
4972 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4973 return compiler_error(c, "'yield from' inside async function");
4974
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004975 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004976 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004977 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004978 ADDOP(c, YIELD_FROM);
4979 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004980 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00004981 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004982 if (c->u->u_ste->ste_type != FunctionBlock){
4983 return compiler_error(c, "'await' outside function");
4984 }
Yury Selivanov75445082015-05-11 22:57:16 -04004985
Victor Stinner331a6a52019-05-27 16:39:22 +02004986 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004987 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
4988 return compiler_error(c, "'await' outside async function");
4989 }
4990 }
Yury Selivanov75445082015-05-11 22:57:16 -04004991
4992 VISIT(c, expr, e->v.Await.value);
4993 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004994 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004995 ADDOP(c, YIELD_FROM);
4996 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 case Compare_kind:
4998 return compiler_compare(c, e);
4999 case Call_kind:
5000 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005001 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005002 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005003 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005004 case JoinedStr_kind:
5005 return compiler_joined_str(c, e);
5006 case FormattedValue_kind:
5007 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 /* The following exprs can be assignment targets. */
5009 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005010 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 case Load:
5013 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5014 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 case Store:
5016 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5017 break;
5018 case Del:
5019 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5020 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 }
5022 break;
5023 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005024 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 case Starred_kind:
5026 switch (e->v.Starred.ctx) {
5027 case Store:
5028 /* In all legitimate cases, the Starred node was already replaced
5029 * by compiler_list/compiler_tuple. XXX: is that okay? */
5030 return compiler_error(c,
5031 "starred assignment target must be in a list or tuple");
5032 default:
5033 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005034 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005036 break;
5037 case Slice_kind:
5038 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 case Name_kind:
5040 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5041 /* child nodes of List and Tuple will have expr_context set */
5042 case List_kind:
5043 return compiler_list(c, e);
5044 case Tuple_kind:
5045 return compiler_tuple(c, e);
5046 }
5047 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005048}
5049
5050static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005051compiler_visit_expr(struct compiler *c, expr_ty e)
5052{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005053 int old_lineno = c->u->u_lineno;
5054 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005055 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005056 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005057 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005058 c->u->u_col_offset = old_col_offset;
5059 return res;
5060}
5061
5062static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005063compiler_augassign(struct compiler *c, stmt_ty s)
5064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005066 expr_ty e = s->v.AugAssign.target;
5067
5068 int old_lineno = c->u->u_lineno;
5069 int old_col_offset = c->u->u_col_offset;
5070 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 switch (e->kind) {
5073 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005074 VISIT(c, expr, e->v.Attribute.value);
5075 ADDOP(c, DUP_TOP);
5076 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 break;
5078 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005079 VISIT(c, expr, e->v.Subscript.value);
5080 VISIT(c, expr, e->v.Subscript.slice);
5081 ADDOP(c, DUP_TOP_TWO);
5082 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 break;
5084 case Name_kind:
5085 if (!compiler_nameop(c, e->v.Name.id, Load))
5086 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005087 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 default:
5089 PyErr_Format(PyExc_SystemError,
5090 "invalid node type (%d) for augmented assignment",
5091 e->kind);
5092 return 0;
5093 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005094
5095 c->u->u_lineno = old_lineno;
5096 c->u->u_col_offset = old_col_offset;
5097
5098 VISIT(c, expr, s->v.AugAssign.value);
5099 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5100
5101 SET_LOC(c, e);
5102
5103 switch (e->kind) {
5104 case Attribute_kind:
5105 ADDOP(c, ROT_TWO);
5106 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5107 break;
5108 case Subscript_kind:
5109 ADDOP(c, ROT_THREE);
5110 ADDOP(c, STORE_SUBSCR);
5111 break;
5112 case Name_kind:
5113 return compiler_nameop(c, e->v.Name.id, Store);
5114 default:
5115 Py_UNREACHABLE();
5116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005118}
5119
5120static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005121check_ann_expr(struct compiler *c, expr_ty e)
5122{
5123 VISIT(c, expr, e);
5124 ADDOP(c, POP_TOP);
5125 return 1;
5126}
5127
5128static int
5129check_annotation(struct compiler *c, stmt_ty s)
5130{
5131 /* Annotations are only evaluated in a module or class. */
5132 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5133 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5134 return check_ann_expr(c, s->v.AnnAssign.annotation);
5135 }
5136 return 1;
5137}
5138
5139static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005140check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005141{
5142 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005143 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005144 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005145 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005146 return 0;
5147 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005148 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5149 return 0;
5150 }
5151 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5152 return 0;
5153 }
5154 return 1;
5155 case Tuple_kind: {
5156 /* extended slice */
5157 asdl_seq *elts = e->v.Tuple.elts;
5158 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005159 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005160 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005161 return 0;
5162 }
5163 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005164 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005165 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005166 default:
5167 return check_ann_expr(c, e);
5168 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005169}
5170
5171static int
5172compiler_annassign(struct compiler *c, stmt_ty s)
5173{
5174 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005175 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005176
5177 assert(s->kind == AnnAssign_kind);
5178
5179 /* We perform the actual assignment first. */
5180 if (s->v.AnnAssign.value) {
5181 VISIT(c, expr, s->v.AnnAssign.value);
5182 VISIT(c, expr, targ);
5183 }
5184 switch (targ->kind) {
5185 case Name_kind:
5186 /* If we have a simple name in a module or class, store annotation. */
5187 if (s->v.AnnAssign.simple &&
5188 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5189 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005190 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5191 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5192 }
5193 else {
5194 VISIT(c, expr, s->v.AnnAssign.annotation);
5195 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005196 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005197 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005198 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005199 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005200 }
5201 break;
5202 case Attribute_kind:
5203 if (!s->v.AnnAssign.value &&
5204 !check_ann_expr(c, targ->v.Attribute.value)) {
5205 return 0;
5206 }
5207 break;
5208 case Subscript_kind:
5209 if (!s->v.AnnAssign.value &&
5210 (!check_ann_expr(c, targ->v.Subscript.value) ||
5211 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5212 return 0;
5213 }
5214 break;
5215 default:
5216 PyErr_Format(PyExc_SystemError,
5217 "invalid node type (%d) for annotated assignment",
5218 targ->kind);
5219 return 0;
5220 }
5221 /* Annotation is evaluated last. */
5222 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5223 return 0;
5224 }
5225 return 1;
5226}
5227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005228/* Raises a SyntaxError and returns 0.
5229 If something goes wrong, a different exception may be raised.
5230*/
5231
5232static int
5233compiler_error(struct compiler *c, const char *errstr)
5234{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005235 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005237
Victor Stinner14e461d2013-08-26 22:28:21 +02005238 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 if (!loc) {
5240 Py_INCREF(Py_None);
5241 loc = Py_None;
5242 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005243 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005244 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 if (!u)
5246 goto exit;
5247 v = Py_BuildValue("(zO)", errstr, u);
5248 if (!v)
5249 goto exit;
5250 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005251 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005252 Py_DECREF(loc);
5253 Py_XDECREF(u);
5254 Py_XDECREF(v);
5255 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005256}
5257
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005258/* Emits a SyntaxWarning and returns 1 on success.
5259 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5260 and returns 0.
5261*/
5262static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005263compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005264{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005265 va_list vargs;
5266#ifdef HAVE_STDARG_PROTOTYPES
5267 va_start(vargs, format);
5268#else
5269 va_start(vargs);
5270#endif
5271 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5272 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005273 if (msg == NULL) {
5274 return 0;
5275 }
5276 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5277 c->u->u_lineno, NULL, NULL) < 0)
5278 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005279 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005280 /* Replace the SyntaxWarning exception with a SyntaxError
5281 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005282 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005283 assert(PyUnicode_AsUTF8(msg) != NULL);
5284 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005285 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005286 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005287 return 0;
5288 }
5289 Py_DECREF(msg);
5290 return 1;
5291}
5292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005293static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005294compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005296 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005298
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005299 if (ctx == Load) {
5300 if (!check_subscripter(c, e->v.Subscript.value)) {
5301 return 0;
5302 }
5303 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5304 return 0;
5305 }
5306 }
5307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005310 case Store: op = STORE_SUBSCR; break;
5311 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005313 assert(op);
5314 VISIT(c, expr, e->v.Subscript.value);
5315 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 ADDOP(c, op);
5317 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318}
5319
5320static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005321compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 int n = 2;
5324 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 /* only handles the cases where BUILD_SLICE is emitted */
5327 if (s->v.Slice.lower) {
5328 VISIT(c, expr, s->v.Slice.lower);
5329 }
5330 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005331 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 if (s->v.Slice.upper) {
5335 VISIT(c, expr, s->v.Slice.upper);
5336 }
5337 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005338 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 }
5340
5341 if (s->v.Slice.step) {
5342 n++;
5343 VISIT(c, expr, s->v.Slice.step);
5344 }
5345 ADDOP_I(c, BUILD_SLICE, n);
5346 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347}
5348
Thomas Wouters89f507f2006-12-13 04:49:30 +00005349/* End of the compiler section, beginning of the assembler section */
5350
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005352 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005353
5354 XXX must handle implicit jumps from one block to next
5355*/
5356
Thomas Wouters89f507f2006-12-13 04:49:30 +00005357struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005358 PyObject *a_bytecode; /* string containing bytecode */
5359 int a_offset; /* offset into bytecode */
5360 int a_nblocks; /* number of reachable blocks */
T. Wouters99b54d62019-09-12 07:05:33 -07005361 basicblock **a_postorder; /* list of blocks in dfs postorder */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 PyObject *a_lnotab; /* string containing lnotab */
5363 int a_lnotab_off; /* offset into lnotab */
5364 int a_lineno; /* last lineno of emitted instruction */
5365 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005366};
5367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368static void
T. Wouters99b54d62019-09-12 07:05:33 -07005369dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370{
T. Wouters99b54d62019-09-12 07:05:33 -07005371 int i, j;
5372
5373 /* Get rid of recursion for normal control flow.
5374 Since the number of blocks is limited, unused space in a_postorder
5375 (from a_nblocks to end) can be used as a stack for still not ordered
5376 blocks. */
5377 for (j = end; b && !b->b_seen; b = b->b_next) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005378 b->b_seen = 1;
T. Wouters99b54d62019-09-12 07:05:33 -07005379 assert(a->a_nblocks < j);
5380 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 }
T. Wouters99b54d62019-09-12 07:05:33 -07005382 while (j < end) {
5383 b = a->a_postorder[j++];
5384 for (i = 0; i < b->b_iused; i++) {
5385 struct instr *instr = &b->b_instr[i];
5386 if (instr->i_jrel || instr->i_jabs)
5387 dfs(c, instr->i_target, a, j);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005388 }
T. Wouters99b54d62019-09-12 07:05:33 -07005389 assert(a->a_nblocks < j);
5390 a->a_postorder[a->a_nblocks++] = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005392}
5393
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005394Py_LOCAL_INLINE(void)
5395stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005396{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005397 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005398 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005399 assert(b->b_startdepth < 0);
5400 b->b_startdepth = depth;
5401 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005403}
5404
5405/* Find the flow path that needs the largest stack. We assume that
5406 * cycles in the flow graph have no net effect on the stack depth.
5407 */
5408static int
5409stackdepth(struct compiler *c)
5410{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005411 basicblock *b, *entryblock = NULL;
5412 basicblock **stack, **sp;
5413 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 b->b_startdepth = INT_MIN;
5416 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005417 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 }
5419 if (!entryblock)
5420 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005421 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5422 if (!stack) {
5423 PyErr_NoMemory();
5424 return -1;
5425 }
5426
5427 sp = stack;
5428 stackdepth_push(&sp, entryblock, 0);
5429 while (sp != stack) {
5430 b = *--sp;
5431 int depth = b->b_startdepth;
5432 assert(depth >= 0);
5433 basicblock *next = b->b_next;
5434 for (int i = 0; i < b->b_iused; i++) {
5435 struct instr *instr = &b->b_instr[i];
5436 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5437 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005438 _Py_FatalErrorFormat(__func__,
5439 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005440 }
5441 int new_depth = depth + effect;
5442 if (new_depth > maxdepth) {
5443 maxdepth = new_depth;
5444 }
5445 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5446 if (instr->i_jrel || instr->i_jabs) {
5447 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5448 assert(effect != PY_INVALID_STACK_EFFECT);
5449 int target_depth = depth + effect;
5450 if (target_depth > maxdepth) {
5451 maxdepth = target_depth;
5452 }
5453 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005454 stackdepth_push(&sp, instr->i_target, target_depth);
5455 }
5456 depth = new_depth;
5457 if (instr->i_opcode == JUMP_ABSOLUTE ||
5458 instr->i_opcode == JUMP_FORWARD ||
5459 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005460 instr->i_opcode == RAISE_VARARGS ||
5461 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005462 {
5463 /* remaining code is dead */
5464 next = NULL;
5465 break;
5466 }
5467 }
5468 if (next != NULL) {
5469 stackdepth_push(&sp, next, depth);
5470 }
5471 }
5472 PyObject_Free(stack);
5473 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005474}
5475
5476static int
5477assemble_init(struct assembler *a, int nblocks, int firstlineno)
5478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 memset(a, 0, sizeof(struct assembler));
5480 a->a_lineno = firstlineno;
5481 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5482 if (!a->a_bytecode)
5483 return 0;
5484 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5485 if (!a->a_lnotab)
5486 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005487 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 PyErr_NoMemory();
5489 return 0;
5490 }
T. Wouters99b54d62019-09-12 07:05:33 -07005491 a->a_postorder = (basicblock **)PyObject_Malloc(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 sizeof(basicblock *) * nblocks);
T. Wouters99b54d62019-09-12 07:05:33 -07005493 if (!a->a_postorder) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 PyErr_NoMemory();
5495 return 0;
5496 }
5497 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005498}
5499
5500static void
5501assemble_free(struct assembler *a)
5502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 Py_XDECREF(a->a_bytecode);
5504 Py_XDECREF(a->a_lnotab);
T. Wouters99b54d62019-09-12 07:05:33 -07005505 if (a->a_postorder)
5506 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507}
5508
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005509static int
5510blocksize(basicblock *b)
5511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 int i;
5513 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005516 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005518}
5519
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005520/* Appends a pair to the end of the line number table, a_lnotab, representing
5521 the instruction's bytecode offset and line number. See
5522 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005523
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005524static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005525assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005528 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 d_lineno = i->i_lineno - a->a_lineno;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005532 if (d_lineno == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 return 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005534 }
5535
5536 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
5537 assert(d_bytecode >= 0);
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 if (d_bytecode > 255) {
5540 int j, nbytes, ncodes = d_bytecode / 255;
5541 nbytes = a->a_lnotab_off + 2 * ncodes;
5542 len = PyBytes_GET_SIZE(a->a_lnotab);
5543 if (nbytes >= len) {
5544 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5545 len = nbytes;
5546 else if (len <= INT_MAX / 2)
5547 len *= 2;
5548 else {
5549 PyErr_NoMemory();
5550 return 0;
5551 }
5552 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5553 return 0;
5554 }
5555 lnotab = (unsigned char *)
5556 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5557 for (j = 0; j < ncodes; j++) {
5558 *lnotab++ = 255;
5559 *lnotab++ = 0;
5560 }
5561 d_bytecode -= ncodes * 255;
5562 a->a_lnotab_off += ncodes * 2;
5563 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005564 assert(0 <= d_bytecode && d_bytecode <= 255);
5565
5566 if (d_lineno < -128 || 127 < d_lineno) {
5567 int j, nbytes, ncodes, k;
5568 if (d_lineno < 0) {
5569 k = -128;
5570 /* use division on positive numbers */
5571 ncodes = (-d_lineno) / 128;
5572 }
5573 else {
5574 k = 127;
5575 ncodes = d_lineno / 127;
5576 }
5577 d_lineno -= ncodes * k;
5578 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 nbytes = a->a_lnotab_off + 2 * ncodes;
5580 len = PyBytes_GET_SIZE(a->a_lnotab);
5581 if (nbytes >= len) {
5582 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5583 len = nbytes;
5584 else if (len <= INT_MAX / 2)
5585 len *= 2;
5586 else {
5587 PyErr_NoMemory();
5588 return 0;
5589 }
5590 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5591 return 0;
5592 }
5593 lnotab = (unsigned char *)
5594 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5595 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005596 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005597 d_bytecode = 0;
5598 for (j = 1; j < ncodes; j++) {
5599 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005600 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 a->a_lnotab_off += ncodes * 2;
5603 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005604 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005606 len = PyBytes_GET_SIZE(a->a_lnotab);
5607 if (a->a_lnotab_off + 2 >= len) {
5608 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5609 return 0;
5610 }
5611 lnotab = (unsigned char *)
5612 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005614 a->a_lnotab_off += 2;
5615 if (d_bytecode) {
5616 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005617 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 }
5619 else { /* First line of a block; def stmt, etc. */
5620 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005621 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 }
5623 a->a_lineno = i->i_lineno;
5624 a->a_lineno_off = a->a_offset;
5625 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005626}
5627
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005628/* assemble_emit()
5629 Extend the bytecode with a new instruction.
5630 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005631*/
5632
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005633static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005634assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005635{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005636 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005638 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005639
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005640 arg = i->i_oparg;
5641 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 if (i->i_lineno && !assemble_lnotab(a, i))
5643 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005644 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 if (len > PY_SSIZE_T_MAX / 2)
5646 return 0;
5647 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5648 return 0;
5649 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005650 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005652 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005654}
5655
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005656static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005657assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005660 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 /* Compute the size of each block and fixup jump args.
5664 Replace block pointer with position in bytecode. */
5665 do {
5666 totsize = 0;
T. Wouters99b54d62019-09-12 07:05:33 -07005667 for (i = a->a_nblocks - 1; i >= 0; i--) {
5668 b = a->a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 bsize = blocksize(b);
5670 b->b_offset = totsize;
5671 totsize += bsize;
5672 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005673 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5675 bsize = b->b_offset;
5676 for (i = 0; i < b->b_iused; i++) {
5677 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005678 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 /* Relative jumps are computed relative to
5680 the instruction pointer after fetching
5681 the jump instruction.
5682 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005683 bsize += isize;
5684 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005686 if (instr->i_jrel) {
5687 instr->i_oparg -= bsize;
5688 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005689 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005690 if (instrsize(instr->i_oparg) != isize) {
5691 extended_arg_recompile = 1;
5692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 }
5695 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 /* XXX: This is an awful hack that could hurt performance, but
5698 on the bright side it should work until we come up
5699 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 The issue is that in the first loop blocksize() is called
5702 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005703 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 So we loop until we stop seeing new EXTENDED_ARGs.
5707 The only EXTENDED_ARGs that could be popping up are
5708 ones in jump instructions. So this should converge
5709 fairly quickly.
5710 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005711 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005712}
5713
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005714static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005715dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005718 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005720 tuple = PyTuple_New(size);
5721 if (tuple == NULL)
5722 return NULL;
5723 while (PyDict_Next(dict, &pos, &k, &v)) {
5724 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005725 Py_INCREF(k);
5726 assert((i - offset) < size);
5727 assert((i - offset) >= 0);
5728 PyTuple_SET_ITEM(tuple, i - offset, k);
5729 }
5730 return tuple;
5731}
5732
5733static PyObject *
5734consts_dict_keys_inorder(PyObject *dict)
5735{
5736 PyObject *consts, *k, *v;
5737 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5738
5739 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5740 if (consts == NULL)
5741 return NULL;
5742 while (PyDict_Next(dict, &pos, &k, &v)) {
5743 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005744 /* The keys of the dictionary can be tuples wrapping a contant.
5745 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5746 * the object we want is always second. */
5747 if (PyTuple_CheckExact(k)) {
5748 k = PyTuple_GET_ITEM(k, 1);
5749 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005751 assert(i < size);
5752 assert(i >= 0);
5753 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005755 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005756}
5757
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005758static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005759compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005762 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005764 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 if (ste->ste_nested)
5766 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005767 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005769 if (!ste->ste_generator && ste->ste_coroutine)
5770 flags |= CO_COROUTINE;
5771 if (ste->ste_generator && ste->ste_coroutine)
5772 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 if (ste->ste_varargs)
5774 flags |= CO_VARARGS;
5775 if (ste->ste_varkeywords)
5776 flags |= CO_VARKEYWORDS;
5777 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 /* (Only) inherit compilerflags in PyCF_MASK */
5780 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005781
Pablo Galindo90235812020-03-15 04:29:22 +00005782 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005783 ste->ste_coroutine &&
5784 !ste->ste_generator) {
5785 flags |= CO_COROUTINE;
5786 }
5787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005789}
5790
INADA Naokic2e16072018-11-26 21:23:22 +09005791// Merge *tuple* with constant cache.
5792// Unlike merge_consts_recursive(), this function doesn't work recursively.
5793static int
5794merge_const_tuple(struct compiler *c, PyObject **tuple)
5795{
5796 assert(PyTuple_CheckExact(*tuple));
5797
5798 PyObject *key = _PyCode_ConstantKey(*tuple);
5799 if (key == NULL) {
5800 return 0;
5801 }
5802
5803 // t is borrowed reference
5804 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5805 Py_DECREF(key);
5806 if (t == NULL) {
5807 return 0;
5808 }
5809 if (t == key) { // tuple is new constant.
5810 return 1;
5811 }
5812
5813 PyObject *u = PyTuple_GET_ITEM(t, 1);
5814 Py_INCREF(u);
5815 Py_DECREF(*tuple);
5816 *tuple = u;
5817 return 1;
5818}
5819
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005820static PyCodeObject *
5821makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 PyObject *tmp;
5824 PyCodeObject *co = NULL;
5825 PyObject *consts = NULL;
5826 PyObject *names = NULL;
5827 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 PyObject *name = NULL;
5829 PyObject *freevars = NULL;
5830 PyObject *cellvars = NULL;
5831 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005832 Py_ssize_t nlocals;
5833 int nlocals_int;
5834 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005835 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005836
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005837 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 names = dict_keys_inorder(c->u->u_names, 0);
5839 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5840 if (!consts || !names || !varnames)
5841 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5844 if (!cellvars)
5845 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005846 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 if (!freevars)
5848 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005849
INADA Naokic2e16072018-11-26 21:23:22 +09005850 if (!merge_const_tuple(c, &names) ||
5851 !merge_const_tuple(c, &varnames) ||
5852 !merge_const_tuple(c, &cellvars) ||
5853 !merge_const_tuple(c, &freevars))
5854 {
5855 goto error;
5856 }
5857
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005858 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005859 assert(nlocals < INT_MAX);
5860 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 flags = compute_code_flags(c);
5863 if (flags < 0)
5864 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5867 if (!bytecode)
5868 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5871 if (!tmp)
5872 goto error;
5873 Py_DECREF(consts);
5874 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005875 if (!merge_const_tuple(c, &consts)) {
5876 goto error;
5877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005879 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005880 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005881 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005882 maxdepth = stackdepth(c);
5883 if (maxdepth < 0) {
5884 goto error;
5885 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005886 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005887 posonlyargcount, kwonlyargcount, nlocals_int,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005888 maxdepth, flags, bytecode, consts, names,
5889 varnames, freevars, cellvars, c->c_filename,
5890 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005891 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 Py_XDECREF(consts);
5893 Py_XDECREF(names);
5894 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 Py_XDECREF(name);
5896 Py_XDECREF(freevars);
5897 Py_XDECREF(cellvars);
5898 Py_XDECREF(bytecode);
5899 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005900}
5901
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005902
5903/* For debugging purposes only */
5904#if 0
5905static void
5906dump_instr(const struct instr *i)
5907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 const char *jrel = i->i_jrel ? "jrel " : "";
5909 const char *jabs = i->i_jabs ? "jabs " : "";
5910 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005913 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005915 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5917 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005918}
5919
5920static void
5921dump_basicblock(const basicblock *b)
5922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 const char *seen = b->b_seen ? "seen " : "";
5924 const char *b_return = b->b_return ? "return " : "";
5925 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5926 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5927 if (b->b_instr) {
5928 int i;
5929 for (i = 0; i < b->b_iused; i++) {
5930 fprintf(stderr, " [%02d] ", i);
5931 dump_instr(b->b_instr + i);
5932 }
5933 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005934}
5935#endif
5936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005937static PyCodeObject *
5938assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 basicblock *b, *entryblock;
5941 struct assembler a;
5942 int i, j, nblocks;
5943 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 /* Make sure every block that falls off the end returns None.
5946 XXX NEXT_BLOCK() isn't quite right, because if the last
5947 block ends with a jump or return b_next shouldn't set.
5948 */
5949 if (!c->u->u_curblock->b_return) {
5950 NEXT_BLOCK(c);
5951 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005952 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 ADDOP(c, RETURN_VALUE);
5954 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 nblocks = 0;
5957 entryblock = NULL;
5958 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5959 nblocks++;
5960 entryblock = b;
5961 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005963 /* Set firstlineno if it wasn't explicitly set. */
5964 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005965 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5967 else
5968 c->u->u_firstlineno = 1;
5969 }
5970 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5971 goto error;
T. Wouters99b54d62019-09-12 07:05:33 -07005972 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 /* Can't modify the bytecode after computing jump offsets. */
5975 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005976
T. Wouters99b54d62019-09-12 07:05:33 -07005977 /* Emit code in reverse postorder from dfs. */
5978 for (i = a.a_nblocks - 1; i >= 0; i--) {
5979 b = a.a_postorder[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 for (j = 0; j < b->b_iused; j++)
5981 if (!assemble_emit(&a, &b->b_instr[j]))
5982 goto error;
5983 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5986 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005987 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005988 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005991 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005992 assemble_free(&a);
5993 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005994}
Georg Brandl8334fd92010-12-04 10:26:46 +00005995
5996#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005997PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005998PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5999 PyArena *arena)
6000{
6001 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6002}