blob: dd27ba840f758c0670ed896d77680448ef3e2f65 [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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#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
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 unsigned i_jabs : 1;
45 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
67 unsigned b_seen : 1;
68 /* b_return is true if a RETURN_VALUE opcode is inserted. */
69 unsigned b_return : 1;
70 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
73 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020083enum fblocktype { WHILE_LOOP, FOR_LOOP, EXCEPT, FINALLY_TRY, FINALLY_END,
84 WITH, ASYNC_WITH, HANDLER_CLEANUP };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000085
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +020089 /* (optional) type-specific exit or cleanup block */
90 basicblock *fb_exit;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040097 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040098 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010099 COMPILER_SCOPE_COMPREHENSION,
100};
101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000102/* The following items change on entry and exit of code blocks.
103 They must be saved and restored when returning to a block.
104*/
105struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400109 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100110 int u_scope_type;
111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 /* The following fields are dicts that map objects to
113 the index of them in co_XXX. The index is used as
114 the argument for opcodes that refer to those collections.
115 */
116 PyObject *u_consts; /* all constants */
117 PyObject *u_names; /* all names */
118 PyObject *u_varnames; /* local variables */
119 PyObject *u_cellvars; /* cell variables */
120 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Victor Stinnerf8e32212013-11-19 23:56:34 +0100124 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100125 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100126 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 /* Pointer to the most recently allocated block. By following b_list
128 members, you can reach all early allocated blocks. */
129 basicblock *u_blocks;
130 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_nfblocks;
133 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_firstlineno; /* the first lineno of the block */
136 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000137 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 int u_lineno_set; /* boolean to indicate whether instr
139 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140};
141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000147
148Note that we don't track recursion levels during compilation - the
149task of detecting and rejecting excessive levels of nesting is
150handled by the symbol analysis pass.
151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000152*/
153
154struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200155 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 struct symtable *c_st;
157 PyFutureFeatures *c_future; /* pointer to module's __future__ */
158 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Georg Brandl8334fd92010-12-04 10:26:46 +0000160 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 int c_interactive; /* true if in interactive mode */
162 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163
INADA Naokic2e16072018-11-26 21:23:22 +0900164 PyObject *c_const_cache; /* Python dict holding all constants,
165 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 struct compiler_unit *u; /* compiler state for current block */
167 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
168 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169};
170
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100171static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172static void compiler_free(struct compiler *);
173static basicblock *compiler_new_block(struct compiler *);
174static int compiler_next_instr(struct compiler *, basicblock *);
175static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100176static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200179static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
181
182static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
183static int compiler_visit_stmt(struct compiler *, stmt_ty);
184static int compiler_visit_keyword(struct compiler *, keyword_ty);
185static int compiler_visit_expr(struct compiler *, expr_ty);
186static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700187static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000191static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200192static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500194static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400195static int compiler_async_with(struct compiler *, stmt_ty, int);
196static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100197static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400199 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500200static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400201static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000202
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700203static int compiler_sync_comprehension_generator(
204 struct compiler *c,
205 asdl_seq *generators, int gen_index,
206 expr_ty elt, expr_ty val, int type);
207
208static int compiler_async_comprehension_generator(
209 struct compiler *c,
210 asdl_seq *generators, int gen_index,
211 expr_ty elt, expr_ty val, int type);
212
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000214static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400216#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Name mangling: __private becomes _classname__private.
222 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 PyObject *result;
224 size_t nlen, plen, ipriv;
225 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200227 PyUnicode_READ_CHAR(ident, 0) != '_' ||
228 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 Py_INCREF(ident);
230 return ident;
231 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200232 nlen = PyUnicode_GET_LENGTH(ident);
233 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 The only time a name with a dot can occur is when
237 we are compiling an import statement that has a
238 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 TODO(jhylton): Decide whether we want to support
241 mangling of the module name, e.g. __M.X.
242 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
244 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
245 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_INCREF(ident);
247 return ident; /* Don't mangle __whatever__ */
248 }
249 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200250 ipriv = 0;
251 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
252 ipriv++;
253 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_INCREF(ident);
255 return ident; /* Don't mangle if class is just underscores */
256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200257 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000258
Antoine Pitrou55bff892013-04-06 21:21:04 +0200259 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
260 PyErr_SetString(PyExc_OverflowError,
261 "private identifier too large to be mangled");
262 return NULL;
263 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
266 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
267 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
268
269 result = PyUnicode_New(1 + nlen + plen, maxchar);
270 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200272 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
273 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200274 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
275 Py_DECREF(result);
276 return NULL;
277 }
278 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
279 Py_DECREF(result);
280 return NULL;
281 }
Victor Stinner8f825062012-04-27 13:55:39 +0200282 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200283 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000284}
285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286static int
287compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290
INADA Naokic2e16072018-11-26 21:23:22 +0900291 c->c_const_cache = PyDict_New();
292 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900294 }
295
296 c->c_stack = PyList_New(0);
297 if (!c->c_stack) {
298 Py_CLEAR(c->c_const_cache);
299 return 0;
300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303}
304
305PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200306PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
307 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 struct compiler c;
310 PyCodeObject *co = NULL;
311 PyCompilerFlags local_flags;
312 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!__doc__) {
315 __doc__ = PyUnicode_InternFromString("__doc__");
316 if (!__doc__)
317 return NULL;
318 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000319 if (!__annotations__) {
320 __annotations__ = PyUnicode_InternFromString("__annotations__");
321 if (!__annotations__)
322 return NULL;
323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!compiler_init(&c))
325 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200326 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 c.c_filename = filename;
328 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200329 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (c.c_future == NULL)
331 goto finally;
332 if (!flags) {
333 local_flags.cf_flags = 0;
Guido van Rossum495da292019-03-07 12:38:08 -0800334 local_flags.cf_feature_version = PY_MINOR_VERSION;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 flags = &local_flags;
336 }
337 merged = c.c_future->ff_features | flags->cf_flags;
338 c.c_future->ff_features = merged;
339 flags->cf_flags = merged;
340 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000341 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200344 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900345 goto finally;
346 }
347
Victor Stinner14e461d2013-08-26 22:28:21 +0200348 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (c.c_st == NULL) {
350 if (!PyErr_Occurred())
351 PyErr_SetString(PyExc_SystemError, "no symtable");
352 goto finally;
353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356
Thomas Wouters1175c432006-02-27 22:49:54 +0000357 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 compiler_free(&c);
359 assert(co || PyErr_Occurred());
360 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361}
362
363PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200364PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
365 int optimize, PyArena *arena)
366{
367 PyObject *filename;
368 PyCodeObject *co;
369 filename = PyUnicode_DecodeFSDefault(filename_str);
370 if (filename == NULL)
371 return NULL;
372 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
373 Py_DECREF(filename);
374 return co;
375
376}
377
378PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000379PyNode_Compile(struct _node *n, const char *filename)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyCodeObject *co = NULL;
382 mod_ty mod;
383 PyArena *arena = PyArena_New();
384 if (!arena)
385 return NULL;
386 mod = PyAST_FromNode(n, NULL, filename, arena);
387 if (mod)
388 co = PyAST_Compile(mod, filename, NULL, arena);
389 PyArena_Free(arena);
390 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000391}
392
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000393static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (c->c_st)
397 PySymtable_Free(c->c_st);
398 if (c->c_future)
399 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200400 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900401 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000403}
404
Guido van Rossum79f25d91997-04-29 20:08:16 +0000405static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_ssize_t i, n;
409 PyObject *v, *k;
410 PyObject *dict = PyDict_New();
411 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 n = PyList_Size(list);
414 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100415 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (!v) {
417 Py_DECREF(dict);
418 return NULL;
419 }
420 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300421 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 Py_DECREF(v);
423 Py_DECREF(dict);
424 return NULL;
425 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 Py_DECREF(v);
427 }
428 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429}
430
431/* Return new dict containing names from src that match scope(s).
432
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000433src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435values are integers, starting at offset and increasing by one for
436each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437*/
438
439static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100440dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700442 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500444 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(offset >= 0);
447 if (dest == NULL)
448 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Meador Inge2ca63152012-07-18 14:20:11 -0500450 /* Sort the keys so that we have a deterministic order on the indexes
451 saved in the returned dictionary. These indexes are used as indexes
452 into the free and cell var storage. Therefore if they aren't
453 deterministic, then the generated bytecode is not deterministic.
454 */
455 sorted_keys = PyDict_Keys(src);
456 if (sorted_keys == NULL)
457 return NULL;
458 if (PyList_Sort(sorted_keys) != 0) {
459 Py_DECREF(sorted_keys);
460 return NULL;
461 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500462 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500463
464 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* XXX this should probably be a macro in symtable.h */
466 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500467 k = PyList_GET_ITEM(sorted_keys, key_i);
468 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 assert(PyLong_Check(v));
470 vi = PyLong_AS_LONG(v);
471 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300474 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500476 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_DECREF(dest);
478 return NULL;
479 }
480 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300481 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500482 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_DECREF(item);
484 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
486 }
487 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
489 }
Meador Inge2ca63152012-07-18 14:20:11 -0500490 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000492}
493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494static void
495compiler_unit_check(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *block;
498 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700499 assert((uintptr_t)block != 0xcbcbcbcbU);
500 assert((uintptr_t)block != 0xfbfbfbfbU);
501 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (block->b_instr != NULL) {
503 assert(block->b_ialloc > 0);
504 assert(block->b_iused > 0);
505 assert(block->b_ialloc >= block->b_iused);
506 }
507 else {
508 assert (block->b_iused == 0);
509 assert (block->b_ialloc == 0);
510 }
511 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000512}
513
514static void
515compiler_unit_free(struct compiler_unit *u)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 compiler_unit_check(u);
520 b = u->u_blocks;
521 while (b != NULL) {
522 if (b->b_instr)
523 PyObject_Free((void *)b->b_instr);
524 next = b->b_list;
525 PyObject_Free((void *)b);
526 b = next;
527 }
528 Py_CLEAR(u->u_ste);
529 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400530 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 Py_CLEAR(u->u_consts);
532 Py_CLEAR(u->u_names);
533 Py_CLEAR(u->u_varnames);
534 Py_CLEAR(u->u_freevars);
535 Py_CLEAR(u->u_cellvars);
536 Py_CLEAR(u->u_private);
537 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538}
539
540static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100541compiler_enter_scope(struct compiler *c, identifier name,
542 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100545 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
548 struct compiler_unit));
549 if (!u) {
550 PyErr_NoMemory();
551 return 0;
552 }
553 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100554 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100556 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 u->u_kwonlyargcount = 0;
558 u->u_ste = PySymtable_Lookup(c->c_st, key);
559 if (!u->u_ste) {
560 compiler_unit_free(u);
561 return 0;
562 }
563 Py_INCREF(name);
564 u->u_name = name;
565 u->u_varnames = list2dict(u->u_ste->ste_varnames);
566 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
567 if (!u->u_varnames || !u->u_cellvars) {
568 compiler_unit_free(u);
569 return 0;
570 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000572 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300574 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500575 int res;
576 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200577 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500578 name = _PyUnicode_FromId(&PyId___class__);
579 if (!name) {
580 compiler_unit_free(u);
581 return 0;
582 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300583 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500584 if (res < 0) {
585 compiler_unit_free(u);
586 return 0;
587 }
588 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200591 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (!u->u_freevars) {
593 compiler_unit_free(u);
594 return 0;
595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 u->u_blocks = NULL;
598 u->u_nfblocks = 0;
599 u->u_firstlineno = lineno;
600 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000601 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 u->u_lineno_set = 0;
603 u->u_consts = PyDict_New();
604 if (!u->u_consts) {
605 compiler_unit_free(u);
606 return 0;
607 }
608 u->u_names = PyDict_New();
609 if (!u->u_names) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Push the old compiler_unit on the stack. */
617 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400618 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
620 Py_XDECREF(capsule);
621 compiler_unit_free(u);
622 return 0;
623 }
624 Py_DECREF(capsule);
625 u->u_private = c->u->u_private;
626 Py_XINCREF(u->u_private);
627 }
628 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100631
632 block = compiler_new_block(c);
633 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100635 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400637 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
638 if (!compiler_set_qualname(c))
639 return 0;
640 }
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643}
644
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000645static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646compiler_exit_scope(struct compiler *c)
647{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100648 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel--;
652 compiler_unit_free(c->u);
653 /* Restore c->u to the parent unit. */
654 n = PyList_GET_SIZE(c->c_stack) - 1;
655 if (n >= 0) {
656 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400657 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(c->u);
659 /* we are deleting from a list so this really shouldn't fail */
660 if (PySequence_DelItem(c->c_stack, n) < 0)
661 Py_FatalError("compiler_exit_scope()");
662 compiler_unit_check(c->u);
663 }
664 else
665 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667}
668
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400669static int
670compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100671{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100672 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400673 _Py_static_string(dot_locals, ".<locals>");
674 Py_ssize_t stack_size;
675 struct compiler_unit *u = c->u;
676 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400678 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100679 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400680 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 if (stack_size > 1) {
682 int scope, force_global = 0;
683 struct compiler_unit *parent;
684 PyObject *mangled, *capsule;
685
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400686 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400687 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400688 assert(parent);
689
Yury Selivanov75445082015-05-11 22:57:16 -0400690 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
691 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
692 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400693 assert(u->u_name);
694 mangled = _Py_Mangle(parent->u_private, u->u_name);
695 if (!mangled)
696 return 0;
697 scope = PyST_GetScope(parent->u_ste, mangled);
698 Py_DECREF(mangled);
699 assert(scope != GLOBAL_IMPLICIT);
700 if (scope == GLOBAL_EXPLICIT)
701 force_global = 1;
702 }
703
704 if (!force_global) {
705 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400706 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
708 dot_locals_str = _PyUnicode_FromId(&dot_locals);
709 if (dot_locals_str == NULL)
710 return 0;
711 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
712 if (base == NULL)
713 return 0;
714 }
715 else {
716 Py_INCREF(parent->u_qualname);
717 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400718 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100719 }
720 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400722 if (base != NULL) {
723 dot_str = _PyUnicode_FromId(&dot);
724 if (dot_str == NULL) {
725 Py_DECREF(base);
726 return 0;
727 }
728 name = PyUnicode_Concat(base, dot_str);
729 Py_DECREF(base);
730 if (name == NULL)
731 return 0;
732 PyUnicode_Append(&name, u->u_name);
733 if (name == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(u->u_name);
738 name = u->u_name;
739 }
740 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400742 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100743}
744
Eric V. Smith235a6f02015-09-19 14:51:32 -0400745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000746/* Allocate a new block and return a pointer to it.
747 Returns NULL on error.
748*/
749
750static basicblock *
751compiler_new_block(struct compiler *c)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 basicblock *b;
754 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 u = c->u;
757 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
758 if (b == NULL) {
759 PyErr_NoMemory();
760 return NULL;
761 }
762 memset((void *)b, 0, sizeof(basicblock));
763 /* Extend the singly linked list of blocks with new block. */
764 b->b_list = u->u_blocks;
765 u->u_blocks = b;
766 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767}
768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770compiler_next_block(struct compiler *c)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 basicblock *block = compiler_new_block(c);
773 if (block == NULL)
774 return NULL;
775 c->u->u_curblock->b_next = block;
776 c->u->u_curblock = block;
777 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778}
779
780static basicblock *
781compiler_use_next_block(struct compiler *c, basicblock *block)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 assert(block != NULL);
784 c->u->u_curblock->b_next = block;
785 c->u->u_curblock = block;
786 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
789/* Returns the offset of the next instruction in the current block's
790 b_instr array. Resizes the b_instr as necessary.
791 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793
794static int
795compiler_next_instr(struct compiler *c, basicblock *b)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 assert(b != NULL);
798 if (b->b_instr == NULL) {
799 b->b_instr = (struct instr *)PyObject_Malloc(
800 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
801 if (b->b_instr == NULL) {
802 PyErr_NoMemory();
803 return -1;
804 }
805 b->b_ialloc = DEFAULT_BLOCK_SIZE;
806 memset((char *)b->b_instr, 0,
807 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
808 }
809 else if (b->b_iused == b->b_ialloc) {
810 struct instr *tmp;
811 size_t oldsize, newsize;
812 oldsize = b->b_ialloc * sizeof(struct instr);
813 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000814
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700815 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PyErr_NoMemory();
817 return -1;
818 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (newsize == 0) {
821 PyErr_NoMemory();
822 return -1;
823 }
824 b->b_ialloc <<= 1;
825 tmp = (struct instr *)PyObject_Realloc(
826 (void *)b->b_instr, newsize);
827 if (tmp == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_instr = tmp;
832 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
833 }
834 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835}
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837/* Set the i_lineno member of the instruction at offset off if the
838 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839 already been set. If it has been set, the call has no effect.
840
Christian Heimes2202f872008-02-06 14:31:34 +0000841 The line number is reset in the following cases:
842 - when entering a new scope
843 - on each statement
844 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200845 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000846 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000849static void
850compiler_set_lineno(struct compiler *c, int off)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 basicblock *b;
853 if (c->u->u_lineno_set)
854 return;
855 c->u->u_lineno_set = 1;
856 b = c->u->u_curblock;
857 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000858}
859
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;
Yury Selivanov75445082015-05-11 22:57:16 -0400957 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200958 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400959 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200960 /* Pop a variable number of values pushed by WITH_CLEANUP_START
961 * + __exit__ or __aexit__. */
962 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case RETURN_VALUE:
964 return -1;
965 case IMPORT_STAR:
966 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700967 case SETUP_ANNOTATIONS:
968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 case YIELD_VALUE:
970 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500971 case YIELD_FROM:
972 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case POP_BLOCK:
974 return 0;
975 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200976 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200978 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200979 /* Pop 6 values when an exception was raised. */
980 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case STORE_NAME:
983 return -1;
984 case DELETE_NAME:
985 return 0;
986 case UNPACK_SEQUENCE:
987 return oparg-1;
988 case UNPACK_EX:
989 return (oparg&0xFF) + (oparg>>8);
990 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200991 /* -1 at end of iterator, 1 if continue iterating. */
992 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 case STORE_ATTR:
995 return -2;
996 case DELETE_ATTR:
997 return -1;
998 case STORE_GLOBAL:
999 return -1;
1000 case DELETE_GLOBAL:
1001 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case LOAD_CONST:
1003 return 1;
1004 case LOAD_NAME:
1005 return 1;
1006 case BUILD_TUPLE:
1007 case BUILD_LIST:
1008 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001009 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001011 case BUILD_LIST_UNPACK:
1012 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001013 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001014 case BUILD_SET_UNPACK:
1015 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001016 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001017 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001019 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001020 case BUILD_CONST_KEY_MAP:
1021 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case LOAD_ATTR:
1023 return 0;
1024 case COMPARE_OP:
1025 return -1;
1026 case IMPORT_NAME:
1027 return -1;
1028 case IMPORT_FROM:
1029 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001031 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case JUMP_ABSOLUTE:
1034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001036 case JUMP_IF_TRUE_OR_POP:
1037 case JUMP_IF_FALSE_OR_POP:
1038 return jump ? 0 : -1;
1039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 case POP_JUMP_IF_FALSE:
1041 case POP_JUMP_IF_TRUE:
1042 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 case LOAD_GLOBAL:
1045 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001047 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001049 /* 0 in the normal flow.
1050 * Restore the stack position and push 6 values before jumping to
1051 * the handler if an exception be raised. */
1052 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001053 case BEGIN_FINALLY:
1054 /* Actually pushes 1 value, but count 6 for balancing with
1055 * END_FINALLY and POP_FINALLY.
1056 * This is the main reason of using this opcode instead of
1057 * "LOAD_CONST None". */
1058 return 6;
1059 case CALL_FINALLY:
1060 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 case LOAD_FAST:
1063 return 1;
1064 case STORE_FAST:
1065 return -1;
1066 case DELETE_FAST:
1067 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case RAISE_VARARGS:
1070 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001071
1072 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001074 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001075 case CALL_METHOD:
1076 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001078 return -oparg-1;
1079 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001080 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001081 case MAKE_FUNCTION:
1082 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1083 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 case BUILD_SLICE:
1085 if (oparg == 3)
1086 return -2;
1087 else
1088 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001090 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case LOAD_CLOSURE:
1092 return 1;
1093 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001094 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return 1;
1096 case STORE_DEREF:
1097 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001098 case DELETE_DEREF:
1099 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001100
1101 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001102 case GET_AWAITABLE:
1103 return 0;
1104 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001105 /* 0 in the normal flow.
1106 * Restore the stack position to the position before the result
1107 * of __aenter__ and push 6 values before jumping to the handler
1108 * if an exception be raised. */
1109 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001110 case BEFORE_ASYNC_WITH:
1111 return 1;
1112 case GET_AITER:
1113 return 0;
1114 case GET_ANEXT:
1115 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001116 case GET_YIELD_FROM_ITER:
1117 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001118 case END_ASYNC_FOR:
1119 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001120 case FORMAT_VALUE:
1121 /* If there's a fmt_spec on the stack, we go from 2->1,
1122 else 1->1. */
1123 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001124 case LOAD_METHOD:
1125 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001127 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
Larry Hastings3a907972013-11-23 14:49:22 -08001129 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130}
1131
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001132int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001133PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1134{
1135 return stack_effect(opcode, oparg, jump);
1136}
1137
1138int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001139PyCompile_OpcodeStackEffect(int opcode, int oparg)
1140{
1141 return stack_effect(opcode, oparg, -1);
1142}
1143
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144/* Add an opcode with no argument.
1145 Returns 0 on failure, 1 on success.
1146*/
1147
1148static int
1149compiler_addop(struct compiler *c, int opcode)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 basicblock *b;
1152 struct instr *i;
1153 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001154 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 off = compiler_next_instr(c, c->u->u_curblock);
1156 if (off < 0)
1157 return 0;
1158 b = c->u->u_curblock;
1159 i = &b->b_instr[off];
1160 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001161 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (opcode == RETURN_VALUE)
1163 b->b_return = 1;
1164 compiler_set_lineno(c, off);
1165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
Victor Stinnerf8e32212013-11-19 23:56:34 +01001168static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1170{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001171 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001174 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001176 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001178 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001179 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001180 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return -1;
1183 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001184 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 Py_DECREF(v);
1186 return -1;
1187 }
1188 Py_DECREF(v);
1189 }
1190 else
1191 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001192 return arg;
1193}
1194
INADA Naokic2e16072018-11-26 21:23:22 +09001195// Merge const *o* recursively and return constant key object.
1196static PyObject*
1197merge_consts_recursive(struct compiler *c, PyObject *o)
1198{
1199 // None and Ellipsis are singleton, and key is the singleton.
1200 // No need to merge object and key.
1201 if (o == Py_None || o == Py_Ellipsis) {
1202 Py_INCREF(o);
1203 return o;
1204 }
1205
1206 PyObject *key = _PyCode_ConstantKey(o);
1207 if (key == NULL) {
1208 return NULL;
1209 }
1210
1211 // t is borrowed reference
1212 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1213 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001214 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001215 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001216 Py_DECREF(key);
1217 return t;
1218 }
1219
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001221 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001223 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 Py_ssize_t len = PyTuple_GET_SIZE(o);
1225 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001226 PyObject *item = PyTuple_GET_ITEM(o, i);
1227 PyObject *u = merge_consts_recursive(c, item);
1228 if (u == NULL) {
1229 Py_DECREF(key);
1230 return NULL;
1231 }
1232
1233 // See _PyCode_ConstantKey()
1234 PyObject *v; // borrowed
1235 if (PyTuple_CheckExact(u)) {
1236 v = PyTuple_GET_ITEM(u, 1);
1237 }
1238 else {
1239 v = u;
1240 }
1241 if (v != item) {
1242 Py_INCREF(v);
1243 PyTuple_SET_ITEM(o, i, v);
1244 Py_DECREF(item);
1245 }
1246
1247 Py_DECREF(u);
1248 }
1249 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001250 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001251 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 // constant keys.
1253 // See _PyCode_ConstantKey() for detail.
1254 assert(PyTuple_CheckExact(key));
1255 assert(PyTuple_GET_SIZE(key) == 2);
1256
1257 Py_ssize_t len = PySet_GET_SIZE(o);
1258 if (len == 0) { // empty frozenset should not be re-created.
1259 return key;
1260 }
1261 PyObject *tuple = PyTuple_New(len);
1262 if (tuple == NULL) {
1263 Py_DECREF(key);
1264 return NULL;
1265 }
1266 Py_ssize_t i = 0, pos = 0;
1267 PyObject *item;
1268 Py_hash_t hash;
1269 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1270 PyObject *k = merge_consts_recursive(c, item);
1271 if (k == NULL) {
1272 Py_DECREF(tuple);
1273 Py_DECREF(key);
1274 return NULL;
1275 }
1276 PyObject *u;
1277 if (PyTuple_CheckExact(k)) {
1278 u = PyTuple_GET_ITEM(k, 1);
1279 Py_INCREF(u);
1280 Py_DECREF(k);
1281 }
1282 else {
1283 u = k;
1284 }
1285 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1286 i++;
1287 }
1288
1289 // Instead of rewriting o, we create new frozenset and embed in the
1290 // key tuple. Caller should get merged frozenset from the key tuple.
1291 PyObject *new = PyFrozenSet_New(tuple);
1292 Py_DECREF(tuple);
1293 if (new == NULL) {
1294 Py_DECREF(key);
1295 return NULL;
1296 }
1297 assert(PyTuple_GET_ITEM(key, 1) == o);
1298 Py_DECREF(o);
1299 PyTuple_SET_ITEM(key, 1, new);
1300 }
INADA Naokic2e16072018-11-26 21:23:22 +09001301
1302 return key;
1303}
1304
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001305static Py_ssize_t
1306compiler_add_const(struct compiler *c, PyObject *o)
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
INADA Naokic2e16072018-11-26 21:23:22 +09001313 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1314 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{
1321 Py_ssize_t arg = compiler_add_const(c, o);
1322 if (arg < 0)
1323 return 0;
1324 return compiler_addop_i(c, LOAD_CONST, arg);
1325}
1326
1327static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001331 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001333 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 return compiler_addop_i(c, opcode, arg);
1335}
1336
1337static int
1338compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001341 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1343 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001344 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 arg = compiler_add_o(c, dict, mangled);
1346 Py_DECREF(mangled);
1347 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 return compiler_addop_i(c, opcode, arg);
1350}
1351
1352/* Add an opcode with an integer argument.
1353 Returns 0 on failure, 1 on success.
1354*/
1355
1356static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001357compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 struct instr *i;
1360 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001361
Victor Stinner2ad474b2016-03-01 23:34:47 +01001362 /* oparg value is unsigned, but a signed C int is usually used to store
1363 it in the C code (like Python/ceval.c).
1364
1365 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1366
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001367 The argument of a concrete bytecode instruction is limited to 8-bit.
1368 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1369 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001370 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 off = compiler_next_instr(c, c->u->u_curblock);
1373 if (off < 0)
1374 return 0;
1375 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001376 i->i_opcode = opcode;
1377 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 compiler_set_lineno(c, off);
1379 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380}
1381
1382static int
1383compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 struct instr *i;
1386 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001388 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 assert(b != NULL);
1390 off = compiler_next_instr(c, c->u->u_curblock);
1391 if (off < 0)
1392 return 0;
1393 i = &c->u->u_curblock->b_instr[off];
1394 i->i_opcode = opcode;
1395 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (absolute)
1397 i->i_jabs = 1;
1398 else
1399 i->i_jrel = 1;
1400 compiler_set_lineno(c, off);
1401 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402}
1403
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001404/* NEXT_BLOCK() creates an implicit jump from the current block
1405 to the new block.
1406
1407 The returns inside this macro make it impossible to decref objects
1408 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 if (compiler_next_block((C)) == NULL) \
1412 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413}
1414
1415#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 if (!compiler_addop((C), (OP))) \
1417 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418}
1419
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001420#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (!compiler_addop((C), (OP))) { \
1422 compiler_exit_scope(c); \
1423 return 0; \
1424 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001425}
1426
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001427#define ADDOP_LOAD_CONST(C, O) { \
1428 if (!compiler_addop_load_const((C), (O))) \
1429 return 0; \
1430}
1431
1432/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1433#define ADDOP_LOAD_CONST_NEW(C, O) { \
1434 PyObject *__new_const = (O); \
1435 if (__new_const == NULL) { \
1436 return 0; \
1437 } \
1438 if (!compiler_addop_load_const((C), __new_const)) { \
1439 Py_DECREF(__new_const); \
1440 return 0; \
1441 } \
1442 Py_DECREF(__new_const); \
1443}
1444
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1447 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448}
1449
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001450/* Same as ADDOP_O, but steals a reference. */
1451#define ADDOP_N(C, OP, O, TYPE) { \
1452 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1453 Py_DECREF((O)); \
1454 return 0; \
1455 } \
1456 Py_DECREF((O)); \
1457}
1458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1461 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462}
1463
1464#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 if (!compiler_addop_i((C), (OP), (O))) \
1466 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467}
1468
1469#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!compiler_addop_j((C), (OP), (O), 1)) \
1471 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472}
1473
1474#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (!compiler_addop_j((C), (OP), (O), 0)) \
1476 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477}
1478
1479/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1480 the ASDL name to synthesize the name of the C type and the visit function.
1481*/
1482
1483#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 if (!compiler_visit_ ## TYPE((C), (V))) \
1485 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486}
1487
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001488#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (!compiler_visit_ ## TYPE((C), (V))) { \
1490 compiler_exit_scope(c); \
1491 return 0; \
1492 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001493}
1494
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001495#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_visit_slice((C), (V), (CTX))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
1500#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 int _i; \
1502 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1503 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1504 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1505 if (!compiler_visit_ ## TYPE((C), elt)) \
1506 return 0; \
1507 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001510#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 int _i; \
1512 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1513 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1514 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1515 if (!compiler_visit_ ## TYPE((C), elt)) { \
1516 compiler_exit_scope(c); \
1517 return 0; \
1518 } \
1519 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001520}
1521
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001522/* Search if variable annotations are present statically in a block. */
1523
1524static int
1525find_ann(asdl_seq *stmts)
1526{
1527 int i, j, res = 0;
1528 stmt_ty st;
1529
1530 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1531 st = (stmt_ty)asdl_seq_GET(stmts, i);
1532 switch (st->kind) {
1533 case AnnAssign_kind:
1534 return 1;
1535 case For_kind:
1536 res = find_ann(st->v.For.body) ||
1537 find_ann(st->v.For.orelse);
1538 break;
1539 case AsyncFor_kind:
1540 res = find_ann(st->v.AsyncFor.body) ||
1541 find_ann(st->v.AsyncFor.orelse);
1542 break;
1543 case While_kind:
1544 res = find_ann(st->v.While.body) ||
1545 find_ann(st->v.While.orelse);
1546 break;
1547 case If_kind:
1548 res = find_ann(st->v.If.body) ||
1549 find_ann(st->v.If.orelse);
1550 break;
1551 case With_kind:
1552 res = find_ann(st->v.With.body);
1553 break;
1554 case AsyncWith_kind:
1555 res = find_ann(st->v.AsyncWith.body);
1556 break;
1557 case Try_kind:
1558 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1559 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1560 st->v.Try.handlers, j);
1561 if (find_ann(handler->v.ExceptHandler.body)) {
1562 return 1;
1563 }
1564 }
1565 res = find_ann(st->v.Try.body) ||
1566 find_ann(st->v.Try.finalbody) ||
1567 find_ann(st->v.Try.orelse);
1568 break;
1569 default:
1570 res = 0;
1571 }
1572 if (res) {
1573 break;
1574 }
1575 }
1576 return res;
1577}
1578
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001579/*
1580 * Frame block handling functions
1581 */
1582
1583static int
1584compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1585 basicblock *exit)
1586{
1587 struct fblockinfo *f;
1588 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1589 PyErr_SetString(PyExc_SyntaxError,
1590 "too many statically nested blocks");
1591 return 0;
1592 }
1593 f = &c->u->u_fblock[c->u->u_nfblocks++];
1594 f->fb_type = t;
1595 f->fb_block = b;
1596 f->fb_exit = exit;
1597 return 1;
1598}
1599
1600static void
1601compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1602{
1603 struct compiler_unit *u = c->u;
1604 assert(u->u_nfblocks > 0);
1605 u->u_nfblocks--;
1606 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1607 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1608}
1609
1610/* Unwind a frame block. If preserve_tos is true, the TOS before
1611 * popping the blocks will be restored afterwards.
1612 */
1613static int
1614compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1615 int preserve_tos)
1616{
1617 switch (info->fb_type) {
1618 case WHILE_LOOP:
1619 return 1;
1620
1621 case FINALLY_END:
1622 ADDOP_I(c, POP_FINALLY, preserve_tos);
1623 return 1;
1624
1625 case FOR_LOOP:
1626 /* Pop the iterator */
1627 if (preserve_tos) {
1628 ADDOP(c, ROT_TWO);
1629 }
1630 ADDOP(c, POP_TOP);
1631 return 1;
1632
1633 case EXCEPT:
1634 ADDOP(c, POP_BLOCK);
1635 return 1;
1636
1637 case FINALLY_TRY:
1638 ADDOP(c, POP_BLOCK);
1639 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1640 return 1;
1641
1642 case WITH:
1643 case ASYNC_WITH:
1644 ADDOP(c, POP_BLOCK);
1645 if (preserve_tos) {
1646 ADDOP(c, ROT_TWO);
1647 }
1648 ADDOP(c, BEGIN_FINALLY);
1649 ADDOP(c, WITH_CLEANUP_START);
1650 if (info->fb_type == ASYNC_WITH) {
1651 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001652 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001653 ADDOP(c, YIELD_FROM);
1654 }
1655 ADDOP(c, WITH_CLEANUP_FINISH);
1656 ADDOP_I(c, POP_FINALLY, 0);
1657 return 1;
1658
1659 case HANDLER_CLEANUP:
1660 if (preserve_tos) {
1661 ADDOP(c, ROT_FOUR);
1662 }
1663 if (info->fb_exit) {
1664 ADDOP(c, POP_BLOCK);
1665 ADDOP(c, POP_EXCEPT);
1666 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1667 }
1668 else {
1669 ADDOP(c, POP_EXCEPT);
1670 }
1671 return 1;
1672 }
1673 Py_UNREACHABLE();
1674}
1675
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001676/* Compile a sequence of statements, checking for a docstring
1677 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678
1679static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001680compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001681{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001682 int i = 0;
1683 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001684 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001685
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001686 /* Set current line number to the line number of first statement.
1687 This way line number for SETUP_ANNOTATIONS will always
1688 coincide with the line number of first "real" statement in module.
1689 If body is empy, then lineno will be set later in assemble. */
1690 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1691 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001692 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001693 c->u->u_lineno = st->lineno;
1694 }
1695 /* Every annotated class and module should have __annotations__. */
1696 if (find_ann(stmts)) {
1697 ADDOP(c, SETUP_ANNOTATIONS);
1698 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001699 if (!asdl_seq_LEN(stmts))
1700 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001701 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001702 if (c->c_optimize < 2) {
1703 docstring = _PyAST_GetDocString(stmts);
1704 if (docstring) {
1705 i = 1;
1706 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1707 assert(st->kind == Expr_kind);
1708 VISIT(c, expr, st->v.Expr.value);
1709 if (!compiler_nameop(c, __doc__, Store))
1710 return 0;
1711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001713 for (; i < asdl_seq_LEN(stmts); i++)
1714 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001716}
1717
1718static PyCodeObject *
1719compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyCodeObject *co;
1722 int addNone = 1;
1723 static PyObject *module;
1724 if (!module) {
1725 module = PyUnicode_InternFromString("<module>");
1726 if (!module)
1727 return NULL;
1728 }
1729 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001730 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 return NULL;
1732 switch (mod->kind) {
1733 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001734 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 compiler_exit_scope(c);
1736 return 0;
1737 }
1738 break;
1739 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001740 if (find_ann(mod->v.Interactive.body)) {
1741 ADDOP(c, SETUP_ANNOTATIONS);
1742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 c->c_interactive = 1;
1744 VISIT_SEQ_IN_SCOPE(c, stmt,
1745 mod->v.Interactive.body);
1746 break;
1747 case Expression_kind:
1748 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1749 addNone = 0;
1750 break;
1751 case Suite_kind:
1752 PyErr_SetString(PyExc_SystemError,
1753 "suite should not be possible");
1754 return 0;
1755 default:
1756 PyErr_Format(PyExc_SystemError,
1757 "module kind %d should not be possible",
1758 mod->kind);
1759 return 0;
1760 }
1761 co = assemble(c, addNone);
1762 compiler_exit_scope(c);
1763 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001764}
1765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766/* The test for LOCAL must come before the test for FREE in order to
1767 handle classes where name is both local and free. The local var is
1768 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001769*/
1770
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771static int
1772get_ref_type(struct compiler *c, PyObject *name)
1773{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001774 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001775 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001776 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001777 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001778 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 if (scope == 0) {
1780 char buf[350];
1781 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001782 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001784 PyUnicode_AsUTF8(name),
1785 PyUnicode_AsUTF8(c->u->u_name),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1787 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1788 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1789 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 );
1791 Py_FatalError(buf);
1792 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795}
1796
1797static int
1798compiler_lookup_arg(PyObject *dict, PyObject *name)
1799{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001800 PyObject *v;
1801 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001803 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001804 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805}
1806
1807static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001808compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001810 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001811 if (qualname == NULL)
1812 qualname = co->co_name;
1813
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001814 if (free) {
1815 for (i = 0; i < free; ++i) {
1816 /* Bypass com_addop_varname because it will generate
1817 LOAD_DEREF but LOAD_CLOSURE is needed.
1818 */
1819 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1820 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822 /* Special case: If a class contains a method with a
1823 free variable that has the same name as a method,
1824 the name will be considered free *and* local in the
1825 class. It should be handled by the closure, as
1826 well as by the normal name loookup logic.
1827 */
1828 reftype = get_ref_type(c, name);
1829 if (reftype == CELL)
1830 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1831 else /* (reftype == FREE) */
1832 arg = compiler_lookup_arg(c->u->u_freevars, name);
1833 if (arg == -1) {
1834 fprintf(stderr,
1835 "lookup %s in %s %d %d\n"
1836 "freevars of %s: %s\n",
1837 PyUnicode_AsUTF8(PyObject_Repr(name)),
1838 PyUnicode_AsUTF8(c->u->u_name),
1839 reftype, arg,
1840 PyUnicode_AsUTF8(co->co_name),
1841 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1842 Py_FatalError("compiler_make_closure()");
1843 }
1844 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001846 flags |= 0x08;
1847 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001849 ADDOP_LOAD_CONST(c, (PyObject*)co);
1850 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001851 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853}
1854
1855static int
1856compiler_decorators(struct compiler *c, asdl_seq* decos)
1857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (!decos)
1861 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1864 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1865 }
1866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867}
1868
1869static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001870compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001872{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001873 /* Push a dict of keyword-only default values.
1874
1875 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1876 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001877 int i;
1878 PyObject *keys = NULL;
1879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1881 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1882 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1883 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001884 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001885 if (!mangled) {
1886 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001888 if (keys == NULL) {
1889 keys = PyList_New(1);
1890 if (keys == NULL) {
1891 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001892 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001893 }
1894 PyList_SET_ITEM(keys, 0, mangled);
1895 }
1896 else {
1897 int res = PyList_Append(keys, mangled);
1898 Py_DECREF(mangled);
1899 if (res == -1) {
1900 goto error;
1901 }
1902 }
1903 if (!compiler_visit_expr(c, default_)) {
1904 goto error;
1905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
1907 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001908 if (keys != NULL) {
1909 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1910 PyObject *keys_tuple = PyList_AsTuple(keys);
1911 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001912 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001913 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001914 assert(default_count > 0);
1915 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001916 }
1917 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001918 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001919 }
1920
1921error:
1922 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001923 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001924}
1925
1926static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001927compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1928{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001929 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001930 return 1;
1931}
1932
1933static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001934compiler_visit_argannotation(struct compiler *c, identifier id,
1935 expr_ty annotation, PyObject *names)
1936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001938 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001939 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1940 VISIT(c, annexpr, annotation)
1941 }
1942 else {
1943 VISIT(c, expr, annotation);
1944 }
Victor Stinner065efc32014-02-18 22:07:56 +01001945 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001946 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001947 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001948 if (PyList_Append(names, mangled) < 0) {
1949 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001950 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001951 }
1952 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001954 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001955}
1956
1957static int
1958compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1959 PyObject *names)
1960{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001961 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 for (i = 0; i < asdl_seq_LEN(args); i++) {
1963 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001964 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 c,
1966 arg->arg,
1967 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001968 names))
1969 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001971 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001972}
1973
1974static int
1975compiler_visit_annotations(struct compiler *c, arguments_ty args,
1976 expr_ty returns)
1977{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001978 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001979 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001980
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001981 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 */
1983 static identifier return_str;
1984 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001985 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 names = PyList_New(0);
1987 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001988 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001989
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001990 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001992 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001993 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001994 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001996 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001998 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001999 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002000 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (!return_str) {
2004 return_str = PyUnicode_InternFromString("return");
2005 if (!return_str)
2006 goto error;
2007 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002008 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 goto error;
2010 }
2011
2012 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 PyObject *keytuple = PyList_AsTuple(names);
2015 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002016 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002018 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002020 else {
2021 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002022 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002023 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002024
2025error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002027 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002028}
2029
2030static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031compiler_visit_defaults(struct compiler *c, arguments_ty args)
2032{
2033 VISIT_SEQ(c, expr, args->defaults);
2034 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2035 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036}
2037
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002038static Py_ssize_t
2039compiler_default_arguments(struct compiler *c, arguments_ty args)
2040{
2041 Py_ssize_t funcflags = 0;
2042 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002043 if (!compiler_visit_defaults(c, args))
2044 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002045 funcflags |= 0x01;
2046 }
2047 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002048 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002050 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002051 return -1;
2052 }
2053 else if (res > 0) {
2054 funcflags |= 0x02;
2055 }
2056 }
2057 return funcflags;
2058}
2059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060static int
Yury Selivanov75445082015-05-11 22:57:16 -04002061compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002064 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002065 arguments_ty args;
2066 expr_ty returns;
2067 identifier name;
2068 asdl_seq* decos;
2069 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002070 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002071 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002072 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002073 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074
Yury Selivanov75445082015-05-11 22:57:16 -04002075 if (is_async) {
2076 assert(s->kind == AsyncFunctionDef_kind);
2077
2078 args = s->v.AsyncFunctionDef.args;
2079 returns = s->v.AsyncFunctionDef.returns;
2080 decos = s->v.AsyncFunctionDef.decorator_list;
2081 name = s->v.AsyncFunctionDef.name;
2082 body = s->v.AsyncFunctionDef.body;
2083
2084 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2085 } else {
2086 assert(s->kind == FunctionDef_kind);
2087
2088 args = s->v.FunctionDef.args;
2089 returns = s->v.FunctionDef.returns;
2090 decos = s->v.FunctionDef.decorator_list;
2091 name = s->v.FunctionDef.name;
2092 body = s->v.FunctionDef.body;
2093
2094 scope_type = COMPILER_SCOPE_FUNCTION;
2095 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (!compiler_decorators(c, decos))
2098 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002099
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002100 firstlineno = s->lineno;
2101 if (asdl_seq_LEN(decos)) {
2102 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2103 }
2104
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002105 funcflags = compiler_default_arguments(c, args);
2106 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002108 }
2109
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110 annotations = compiler_visit_annotations(c, args, returns);
2111 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 return 0;
2113 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002114 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002115 funcflags |= 0x04;
2116 }
2117
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002118 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002119 return 0;
2120 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121
INADA Naokicb41b272017-02-23 00:31:59 +09002122 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002123 if (c->c_optimize < 2) {
2124 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002125 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002126 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 compiler_exit_scope(c);
2128 return 0;
2129 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002132 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002134 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002136 qualname = c->u->u_qualname;
2137 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002139 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002140 Py_XDECREF(qualname);
2141 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002143 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002145 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002146 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /* decorators */
2150 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2151 ADDOP_I(c, CALL_FUNCTION, 1);
2152 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153
Yury Selivanov75445082015-05-11 22:57:16 -04002154 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002155}
2156
2157static int
2158compiler_class(struct compiler *c, stmt_ty s)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyCodeObject *co;
2161 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002162 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (!compiler_decorators(c, decos))
2166 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002167
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002168 firstlineno = s->lineno;
2169 if (asdl_seq_LEN(decos)) {
2170 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2171 }
2172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* ultimately generate code for:
2174 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2175 where:
2176 <func> is a function/closure created from the class body;
2177 it has a single argument (__locals__) where the dict
2178 (or MutableSequence) representing the locals is passed
2179 <name> is the class name
2180 <bases> is the positional arguments and *varargs argument
2181 <keywords> is the keyword arguments and **kwds argument
2182 This borrows from compiler_call.
2183 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002186 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002187 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 return 0;
2189 /* this block represents what we do in the new scope */
2190 {
2191 /* use the class name for name mangling */
2192 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002193 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 /* load (global) __name__ ... */
2195 str = PyUnicode_InternFromString("__name__");
2196 if (!str || !compiler_nameop(c, str, Load)) {
2197 Py_XDECREF(str);
2198 compiler_exit_scope(c);
2199 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002200 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 Py_DECREF(str);
2202 /* ... and store it as __module__ */
2203 str = PyUnicode_InternFromString("__module__");
2204 if (!str || !compiler_nameop(c, str, Store)) {
2205 Py_XDECREF(str);
2206 compiler_exit_scope(c);
2207 return 0;
2208 }
2209 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002210 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002211 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002212 str = PyUnicode_InternFromString("__qualname__");
2213 if (!str || !compiler_nameop(c, str, Store)) {
2214 Py_XDECREF(str);
2215 compiler_exit_scope(c);
2216 return 0;
2217 }
2218 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002220 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 compiler_exit_scope(c);
2222 return 0;
2223 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002224 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002225 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002226 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002227 str = PyUnicode_InternFromString("__class__");
2228 if (str == NULL) {
2229 compiler_exit_scope(c);
2230 return 0;
2231 }
2232 i = compiler_lookup_arg(c->u->u_cellvars, str);
2233 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002234 if (i < 0) {
2235 compiler_exit_scope(c);
2236 return 0;
2237 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002238 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002241 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002242 str = PyUnicode_InternFromString("__classcell__");
2243 if (!str || !compiler_nameop(c, str, Store)) {
2244 Py_XDECREF(str);
2245 compiler_exit_scope(c);
2246 return 0;
2247 }
2248 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002250 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002251 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002252 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002253 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002254 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002255 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* create the code object */
2257 co = assemble(c, 1);
2258 }
2259 /* leave the new scope */
2260 compiler_exit_scope(c);
2261 if (co == NULL)
2262 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 /* 2. load the 'build_class' function */
2265 ADDOP(c, LOAD_BUILD_CLASS);
2266
2267 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002268 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_DECREF(co);
2270
2271 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002272 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273
2274 /* 5. generate the rest of the code for the call */
2275 if (!compiler_call_helper(c, 2,
2276 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002277 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 return 0;
2279
2280 /* 6. apply decorators */
2281 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2282 ADDOP_I(c, CALL_FUNCTION, 1);
2283 }
2284
2285 /* 7. store into <name> */
2286 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2287 return 0;
2288 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289}
2290
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002291/* Return 0 if the expression is a constant value except named singletons.
2292 Return 1 otherwise. */
2293static int
2294check_is_arg(expr_ty e)
2295{
2296 if (e->kind != Constant_kind) {
2297 return 1;
2298 }
2299 PyObject *value = e->v.Constant.value;
2300 return (value == Py_None
2301 || value == Py_False
2302 || value == Py_True
2303 || value == Py_Ellipsis);
2304}
2305
2306/* Check operands of identity chacks ("is" and "is not").
2307 Emit a warning if any operand is a constant except named singletons.
2308 Return 0 on error.
2309 */
2310static int
2311check_compare(struct compiler *c, expr_ty e)
2312{
2313 Py_ssize_t i, n;
2314 int left = check_is_arg(e->v.Compare.left);
2315 n = asdl_seq_LEN(e->v.Compare.ops);
2316 for (i = 0; i < n; i++) {
2317 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2318 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2319 if (op == Is || op == IsNot) {
2320 if (!right || !left) {
2321 const char *msg = (op == Is)
2322 ? "\"is\" with a literal. Did you mean \"==\"?"
2323 : "\"is not\" with a literal. Did you mean \"!=\"?";
2324 return compiler_warn(c, msg);
2325 }
2326 }
2327 left = right;
2328 }
2329 return 1;
2330}
2331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002333cmpop(cmpop_ty op)
2334{
2335 switch (op) {
2336 case Eq:
2337 return PyCmp_EQ;
2338 case NotEq:
2339 return PyCmp_NE;
2340 case Lt:
2341 return PyCmp_LT;
2342 case LtE:
2343 return PyCmp_LE;
2344 case Gt:
2345 return PyCmp_GT;
2346 case GtE:
2347 return PyCmp_GE;
2348 case Is:
2349 return PyCmp_IS;
2350 case IsNot:
2351 return PyCmp_IS_NOT;
2352 case In:
2353 return PyCmp_IN;
2354 case NotIn:
2355 return PyCmp_NOT_IN;
2356 default:
2357 return PyCmp_BAD;
2358 }
2359}
2360
2361static int
2362compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2363{
2364 switch (e->kind) {
2365 case UnaryOp_kind:
2366 if (e->v.UnaryOp.op == Not)
2367 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2368 /* fallback to general implementation */
2369 break;
2370 case BoolOp_kind: {
2371 asdl_seq *s = e->v.BoolOp.values;
2372 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2373 assert(n >= 0);
2374 int cond2 = e->v.BoolOp.op == Or;
2375 basicblock *next2 = next;
2376 if (!cond2 != !cond) {
2377 next2 = compiler_new_block(c);
2378 if (next2 == NULL)
2379 return 0;
2380 }
2381 for (i = 0; i < n; ++i) {
2382 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2383 return 0;
2384 }
2385 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2386 return 0;
2387 if (next2 != next)
2388 compiler_use_next_block(c, next2);
2389 return 1;
2390 }
2391 case IfExp_kind: {
2392 basicblock *end, *next2;
2393 end = compiler_new_block(c);
2394 if (end == NULL)
2395 return 0;
2396 next2 = compiler_new_block(c);
2397 if (next2 == NULL)
2398 return 0;
2399 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2400 return 0;
2401 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2402 return 0;
2403 ADDOP_JREL(c, JUMP_FORWARD, end);
2404 compiler_use_next_block(c, next2);
2405 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2406 return 0;
2407 compiler_use_next_block(c, end);
2408 return 1;
2409 }
2410 case Compare_kind: {
2411 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2412 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002413 if (!check_compare(c, e)) {
2414 return 0;
2415 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002416 basicblock *cleanup = compiler_new_block(c);
2417 if (cleanup == NULL)
2418 return 0;
2419 VISIT(c, expr, e->v.Compare.left);
2420 for (i = 0; i < n; i++) {
2421 VISIT(c, expr,
2422 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2423 ADDOP(c, DUP_TOP);
2424 ADDOP(c, ROT_THREE);
2425 ADDOP_I(c, COMPARE_OP,
2426 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2427 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2428 NEXT_BLOCK(c);
2429 }
2430 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2431 ADDOP_I(c, COMPARE_OP,
2432 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2433 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2434 basicblock *end = compiler_new_block(c);
2435 if (end == NULL)
2436 return 0;
2437 ADDOP_JREL(c, JUMP_FORWARD, end);
2438 compiler_use_next_block(c, cleanup);
2439 ADDOP(c, POP_TOP);
2440 if (!cond) {
2441 ADDOP_JREL(c, JUMP_FORWARD, next);
2442 }
2443 compiler_use_next_block(c, end);
2444 return 1;
2445 }
2446 /* fallback to general implementation */
2447 break;
2448 }
2449 default:
2450 /* fallback to general implementation */
2451 break;
2452 }
2453
2454 /* general implementation */
2455 VISIT(c, expr, e);
2456 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2457 return 1;
2458}
2459
2460static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002461compiler_ifexp(struct compiler *c, expr_ty e)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 basicblock *end, *next;
2464
2465 assert(e->kind == IfExp_kind);
2466 end = compiler_new_block(c);
2467 if (end == NULL)
2468 return 0;
2469 next = compiler_new_block(c);
2470 if (next == NULL)
2471 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002472 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2473 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 VISIT(c, expr, e->v.IfExp.body);
2475 ADDOP_JREL(c, JUMP_FORWARD, end);
2476 compiler_use_next_block(c, next);
2477 VISIT(c, expr, e->v.IfExp.orelse);
2478 compiler_use_next_block(c, end);
2479 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002480}
2481
2482static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483compiler_lambda(struct compiler *c, expr_ty e)
2484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002486 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002488 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 arguments_ty args = e->v.Lambda.args;
2490 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (!name) {
2493 name = PyUnicode_InternFromString("<lambda>");
2494 if (!name)
2495 return 0;
2496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002498 funcflags = compiler_default_arguments(c, args);
2499 if (funcflags == -1) {
2500 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002502
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002503 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002504 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 /* Make None the first constant, so the lambda can't have a
2508 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002509 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002513 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2515 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2516 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002517 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 }
2519 else {
2520 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002521 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002523 qualname = c->u->u_qualname;
2524 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002526 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002529 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002530 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 Py_DECREF(co);
2532
2533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534}
2535
2536static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537compiler_if(struct compiler *c, stmt_ty s)
2538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 basicblock *end, *next;
2540 int constant;
2541 assert(s->kind == If_kind);
2542 end = compiler_new_block(c);
2543 if (end == NULL)
2544 return 0;
2545
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002546 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 /* constant = 0: "if 0"
2548 * constant = 1: "if 1", "if 2", ...
2549 * constant = -1: rest */
2550 if (constant == 0) {
2551 if (s->v.If.orelse)
2552 VISIT_SEQ(c, stmt, s->v.If.orelse);
2553 } else if (constant == 1) {
2554 VISIT_SEQ(c, stmt, s->v.If.body);
2555 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002556 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 next = compiler_new_block(c);
2558 if (next == NULL)
2559 return 0;
2560 }
2561 else
2562 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002563 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2564 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002566 if (asdl_seq_LEN(s->v.If.orelse)) {
2567 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 compiler_use_next_block(c, next);
2569 VISIT_SEQ(c, stmt, s->v.If.orelse);
2570 }
2571 }
2572 compiler_use_next_block(c, end);
2573 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574}
2575
2576static int
2577compiler_for(struct compiler *c, stmt_ty s)
2578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 start = compiler_new_block(c);
2582 cleanup = compiler_new_block(c);
2583 end = compiler_new_block(c);
2584 if (start == NULL || end == NULL || cleanup == NULL)
2585 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002586
2587 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 VISIT(c, expr, s->v.For.iter);
2591 ADDOP(c, GET_ITER);
2592 compiler_use_next_block(c, start);
2593 ADDOP_JREL(c, FOR_ITER, cleanup);
2594 VISIT(c, expr, s->v.For.target);
2595 VISIT_SEQ(c, stmt, s->v.For.body);
2596 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2597 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002598
2599 compiler_pop_fblock(c, FOR_LOOP, start);
2600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 VISIT_SEQ(c, stmt, s->v.For.orelse);
2602 compiler_use_next_block(c, end);
2603 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604}
2605
Yury Selivanov75445082015-05-11 22:57:16 -04002606
2607static int
2608compiler_async_for(struct compiler *c, stmt_ty s)
2609{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002610 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002611 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2612 return compiler_error(c, "'async for' outside async function");
2613 }
2614
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002615 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002616 except = compiler_new_block(c);
2617 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002618
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002619 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002620 return 0;
2621
2622 VISIT(c, expr, s->v.AsyncFor.iter);
2623 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002624
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002625 compiler_use_next_block(c, start);
2626 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2627 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002628
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002629 /* SETUP_FINALLY to guard the __anext__ call */
2630 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002631 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002632 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002633 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002634 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002635
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002636 /* Success block for __anext__ */
2637 VISIT(c, expr, s->v.AsyncFor.target);
2638 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2639 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2640
2641 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002642
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002643 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002644 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002645 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002646
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002647 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002648 VISIT_SEQ(c, stmt, s->v.For.orelse);
2649
2650 compiler_use_next_block(c, end);
2651
2652 return 1;
2653}
2654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655static int
2656compiler_while(struct compiler *c, stmt_ty s)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002659 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (constant == 0) {
2662 if (s->v.While.orelse)
2663 VISIT_SEQ(c, stmt, s->v.While.orelse);
2664 return 1;
2665 }
2666 loop = compiler_new_block(c);
2667 end = compiler_new_block(c);
2668 if (constant == -1) {
2669 anchor = compiler_new_block(c);
2670 if (anchor == NULL)
2671 return 0;
2672 }
2673 if (loop == NULL || end == NULL)
2674 return 0;
2675 if (s->v.While.orelse) {
2676 orelse = compiler_new_block(c);
2677 if (orelse == NULL)
2678 return 0;
2679 }
2680 else
2681 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002684 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 return 0;
2686 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002687 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2688 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 }
2690 VISIT_SEQ(c, stmt, s->v.While.body);
2691 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 /* XXX should the two POP instructions be in a separate block
2694 if there is no else clause ?
2695 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002697 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002699 compiler_pop_fblock(c, WHILE_LOOP, loop);
2700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (orelse != NULL) /* what if orelse is just pass? */
2702 VISIT_SEQ(c, stmt, s->v.While.orelse);
2703 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706}
2707
2708static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002711 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002712 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002713 if (c->u->u_ste->ste_type != FunctionBlock)
2714 return compiler_error(c, "'return' outside function");
2715 if (s->v.Return.value != NULL &&
2716 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2717 {
2718 return compiler_error(
2719 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002721 if (preserve_tos) {
2722 VISIT(c, expr, s->v.Return.value);
2723 }
2724 for (int depth = c->u->u_nfblocks; depth--;) {
2725 struct fblockinfo *info = &c->u->u_fblock[depth];
2726
2727 if (!compiler_unwind_fblock(c, info, preserve_tos))
2728 return 0;
2729 }
2730 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002731 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002732 }
2733 else if (!preserve_tos) {
2734 VISIT(c, expr, s->v.Return.value);
2735 }
2736 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739}
2740
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002741static int
2742compiler_break(struct compiler *c)
2743{
2744 for (int depth = c->u->u_nfblocks; depth--;) {
2745 struct fblockinfo *info = &c->u->u_fblock[depth];
2746
2747 if (!compiler_unwind_fblock(c, info, 0))
2748 return 0;
2749 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2750 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2751 return 1;
2752 }
2753 }
2754 return compiler_error(c, "'break' outside loop");
2755}
2756
2757static int
2758compiler_continue(struct compiler *c)
2759{
2760 for (int depth = c->u->u_nfblocks; depth--;) {
2761 struct fblockinfo *info = &c->u->u_fblock[depth];
2762
2763 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2764 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2765 return 1;
2766 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002767 if (!compiler_unwind_fblock(c, info, 0))
2768 return 0;
2769 }
2770 return compiler_error(c, "'continue' not properly in loop");
2771}
2772
2773
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775
2776 SETUP_FINALLY L
2777 <code for body>
2778 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002779 BEGIN_FINALLY
2780 L:
2781 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 END_FINALLY
2783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784 The special instructions use the block stack. Each block
2785 stack entry contains the instruction that created it (here
2786 SETUP_FINALLY), the level of the value stack at the time the
2787 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 Pushes the current value stack level and the label
2791 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 Pops en entry from the block stack.
2794 BEGIN_FINALLY
2795 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002797 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2798 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 when a SETUP_FINALLY entry is found, the raised and the caught
2802 exceptions are pushed onto the value stack (and the exception
2803 condition is cleared), and the interpreter jumps to the label
2804 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805*/
2806
2807static int
2808compiler_try_finally(struct compiler *c, stmt_ty s)
2809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 body = compiler_new_block(c);
2813 end = compiler_new_block(c);
2814 if (body == NULL || end == NULL)
2815 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002816
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002817 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 ADDOP_JREL(c, SETUP_FINALLY, end);
2819 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002820 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002822 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2823 if (!compiler_try_except(c, s))
2824 return 0;
2825 }
2826 else {
2827 VISIT_SEQ(c, stmt, s->v.Try.body);
2828 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002830 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002833 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002835 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002837 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 ADDOP(c, END_FINALLY);
2839 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841}
2842
2843/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002844 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845 (The contents of the value stack is shown in [], with the top
2846 at the right; 'tb' is trace-back info, 'val' the exception's
2847 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848
2849 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002850 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 [] <code for S>
2852 [] POP_BLOCK
2853 [] JUMP_FORWARD L0
2854
2855 [tb, val, exc] L1: DUP )
2856 [tb, val, exc, exc] <evaluate E1> )
2857 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2858 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2859 [tb, val, exc] POP
2860 [tb, val] <assign to V1> (or POP if no V1)
2861 [tb] POP
2862 [] <code for S1>
2863 JUMP_FORWARD L0
2864
2865 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 .............................etc.......................
2867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2869
2870 [] L0: <next statement>
2871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 Of course, parts are not generated if Vi or Ei is not present.
2873*/
2874static int
2875compiler_try_except(struct compiler *c, stmt_ty s)
2876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002878 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 body = compiler_new_block(c);
2881 except = compiler_new_block(c);
2882 orelse = compiler_new_block(c);
2883 end = compiler_new_block(c);
2884 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2885 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002886 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002888 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002890 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 ADDOP(c, POP_BLOCK);
2892 compiler_pop_fblock(c, EXCEPT, body);
2893 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002894 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 compiler_use_next_block(c, except);
2896 for (i = 0; i < n; i++) {
2897 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002898 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 if (!handler->v.ExceptHandler.type && i < n-1)
2900 return compiler_error(c, "default 'except:' must be last");
2901 c->u->u_lineno_set = 0;
2902 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002903 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 except = compiler_new_block(c);
2905 if (except == NULL)
2906 return 0;
2907 if (handler->v.ExceptHandler.type) {
2908 ADDOP(c, DUP_TOP);
2909 VISIT(c, expr, handler->v.ExceptHandler.type);
2910 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2911 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2912 }
2913 ADDOP(c, POP_TOP);
2914 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002915 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002916
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002917 cleanup_end = compiler_new_block(c);
2918 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002919 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002920 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002921 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002922
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002923 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2924 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002926 /*
2927 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002928 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002929 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002930 try:
2931 # body
2932 finally:
2933 name = None
2934 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002935 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002937 /* second try: */
2938 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2939 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002941 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002943 /* second # body */
2944 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2945 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 ADDOP(c, BEGIN_FINALLY);
2947 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002949 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002950 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002951 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002952 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002954 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002955 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002956 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002957 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002959 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002960 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002961 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 }
2963 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002964 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002966 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002967 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969
Guido van Rossumb940e112007-01-10 16:19:56 +00002970 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002971 ADDOP(c, POP_TOP);
2972 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002973 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002974 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002976 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002977 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 }
2979 ADDOP_JREL(c, JUMP_FORWARD, end);
2980 compiler_use_next_block(c, except);
2981 }
2982 ADDOP(c, END_FINALLY);
2983 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002984 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 compiler_use_next_block(c, end);
2986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987}
2988
2989static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002990compiler_try(struct compiler *c, stmt_ty s) {
2991 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2992 return compiler_try_finally(c, s);
2993 else
2994 return compiler_try_except(c, s);
2995}
2996
2997
2998static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999compiler_import_as(struct compiler *c, identifier name, identifier asname)
3000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* The IMPORT_NAME opcode was already generated. This function
3002 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003005 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003007 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3008 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003009 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003010 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003011 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003013 while (1) {
3014 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003016 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003017 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003018 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003019 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003021 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003022 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003023 if (dot == -1) {
3024 break;
3025 }
3026 ADDOP(c, ROT_TWO);
3027 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003029 if (!compiler_nameop(c, asname, Store)) {
3030 return 0;
3031 }
3032 ADDOP(c, POP_TOP);
3033 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 }
3035 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036}
3037
3038static int
3039compiler_import(struct compiler *c, stmt_ty s)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 /* The Import node stores a module name like a.b.c as a single
3042 string. This is convenient for all cases except
3043 import a.b.c as d
3044 where we need to parse that string to extract the individual
3045 module names.
3046 XXX Perhaps change the representation to make this case simpler?
3047 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003048 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 for (i = 0; i < n; i++) {
3051 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3052 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003054 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3055 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 if (alias->asname) {
3059 r = compiler_import_as(c, alias->name, alias->asname);
3060 if (!r)
3061 return r;
3062 }
3063 else {
3064 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003065 Py_ssize_t dot = PyUnicode_FindChar(
3066 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003067 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003068 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003069 if (tmp == NULL)
3070 return 0;
3071 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003073 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 Py_DECREF(tmp);
3075 }
3076 if (!r)
3077 return r;
3078 }
3079 }
3080 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003081}
3082
3083static int
3084compiler_from_import(struct compiler *c, stmt_ty s)
3085{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003086 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003087 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 if (!empty_string) {
3091 empty_string = PyUnicode_FromString("");
3092 if (!empty_string)
3093 return 0;
3094 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003096 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003097
3098 names = PyTuple_New(n);
3099 if (!names)
3100 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 /* build up the names */
3103 for (i = 0; i < n; i++) {
3104 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3105 Py_INCREF(alias->name);
3106 PyTuple_SET_ITEM(names, i, alias->name);
3107 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003110 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 Py_DECREF(names);
3112 return compiler_error(c, "from __future__ imports must occur "
3113 "at the beginning of the file");
3114 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003115 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 if (s->v.ImportFrom.module) {
3118 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3119 }
3120 else {
3121 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3122 }
3123 for (i = 0; i < n; i++) {
3124 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3125 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003127 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 assert(n == 1);
3129 ADDOP(c, IMPORT_STAR);
3130 return 1;
3131 }
3132
3133 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3134 store_name = alias->name;
3135 if (alias->asname)
3136 store_name = alias->asname;
3137
3138 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 return 0;
3140 }
3141 }
3142 /* remove imported module */
3143 ADDOP(c, POP_TOP);
3144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145}
3146
3147static int
3148compiler_assert(struct compiler *c, stmt_ty s)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 static PyObject *assertion_error = NULL;
3151 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152
Georg Brandl8334fd92010-12-04 10:26:46 +00003153 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 return 1;
3155 if (assertion_error == NULL) {
3156 assertion_error = PyUnicode_InternFromString("AssertionError");
3157 if (assertion_error == NULL)
3158 return 0;
3159 }
3160 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003161 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3162 {
3163 if (!compiler_warn(c, "assertion is always true, "
3164 "perhaps remove parentheses?"))
3165 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003166 return 0;
3167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 end = compiler_new_block(c);
3170 if (end == NULL)
3171 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003172 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3173 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3175 if (s->v.Assert.msg) {
3176 VISIT(c, expr, s->v.Assert.msg);
3177 ADDOP_I(c, CALL_FUNCTION, 1);
3178 }
3179 ADDOP_I(c, RAISE_VARARGS, 1);
3180 compiler_use_next_block(c, end);
3181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182}
3183
3184static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003185compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3186{
3187 if (c->c_interactive && c->c_nestlevel <= 1) {
3188 VISIT(c, expr, value);
3189 ADDOP(c, PRINT_EXPR);
3190 return 1;
3191 }
3192
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003193 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003194 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003195 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003196 }
3197
3198 VISIT(c, expr, value);
3199 ADDOP(c, POP_TOP);
3200 return 1;
3201}
3202
3203static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204compiler_visit_stmt(struct compiler *c, stmt_ty s)
3205{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003206 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* Always assign a lineno to the next instruction for a stmt. */
3209 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003210 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 switch (s->kind) {
3214 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003215 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 case ClassDef_kind:
3217 return compiler_class(c, s);
3218 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003219 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 case Delete_kind:
3221 VISIT_SEQ(c, expr, s->v.Delete.targets)
3222 break;
3223 case Assign_kind:
3224 n = asdl_seq_LEN(s->v.Assign.targets);
3225 VISIT(c, expr, s->v.Assign.value);
3226 for (i = 0; i < n; i++) {
3227 if (i < n - 1)
3228 ADDOP(c, DUP_TOP);
3229 VISIT(c, expr,
3230 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3231 }
3232 break;
3233 case AugAssign_kind:
3234 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003235 case AnnAssign_kind:
3236 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 case For_kind:
3238 return compiler_for(c, s);
3239 case While_kind:
3240 return compiler_while(c, s);
3241 case If_kind:
3242 return compiler_if(c, s);
3243 case Raise_kind:
3244 n = 0;
3245 if (s->v.Raise.exc) {
3246 VISIT(c, expr, s->v.Raise.exc);
3247 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003248 if (s->v.Raise.cause) {
3249 VISIT(c, expr, s->v.Raise.cause);
3250 n++;
3251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003253 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003255 case Try_kind:
3256 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 case Assert_kind:
3258 return compiler_assert(c, s);
3259 case Import_kind:
3260 return compiler_import(c, s);
3261 case ImportFrom_kind:
3262 return compiler_from_import(c, s);
3263 case Global_kind:
3264 case Nonlocal_kind:
3265 break;
3266 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003267 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 case Pass_kind:
3269 break;
3270 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003271 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 case Continue_kind:
3273 return compiler_continue(c);
3274 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003275 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003276 case AsyncFunctionDef_kind:
3277 return compiler_function(c, s, 1);
3278 case AsyncWith_kind:
3279 return compiler_async_with(c, s, 0);
3280 case AsyncFor_kind:
3281 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 }
Yury Selivanov75445082015-05-11 22:57:16 -04003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285}
3286
3287static int
3288unaryop(unaryop_ty op)
3289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 switch (op) {
3291 case Invert:
3292 return UNARY_INVERT;
3293 case Not:
3294 return UNARY_NOT;
3295 case UAdd:
3296 return UNARY_POSITIVE;
3297 case USub:
3298 return UNARY_NEGATIVE;
3299 default:
3300 PyErr_Format(PyExc_SystemError,
3301 "unary op %d should not be possible", op);
3302 return 0;
3303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304}
3305
3306static int
3307binop(struct compiler *c, operator_ty op)
3308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 switch (op) {
3310 case Add:
3311 return BINARY_ADD;
3312 case Sub:
3313 return BINARY_SUBTRACT;
3314 case Mult:
3315 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003316 case MatMult:
3317 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 case Div:
3319 return BINARY_TRUE_DIVIDE;
3320 case Mod:
3321 return BINARY_MODULO;
3322 case Pow:
3323 return BINARY_POWER;
3324 case LShift:
3325 return BINARY_LSHIFT;
3326 case RShift:
3327 return BINARY_RSHIFT;
3328 case BitOr:
3329 return BINARY_OR;
3330 case BitXor:
3331 return BINARY_XOR;
3332 case BitAnd:
3333 return BINARY_AND;
3334 case FloorDiv:
3335 return BINARY_FLOOR_DIVIDE;
3336 default:
3337 PyErr_Format(PyExc_SystemError,
3338 "binary op %d should not be possible", op);
3339 return 0;
3340 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003341}
3342
3343static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344inplace_binop(struct compiler *c, operator_ty op)
3345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 switch (op) {
3347 case Add:
3348 return INPLACE_ADD;
3349 case Sub:
3350 return INPLACE_SUBTRACT;
3351 case Mult:
3352 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003353 case MatMult:
3354 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 case Div:
3356 return INPLACE_TRUE_DIVIDE;
3357 case Mod:
3358 return INPLACE_MODULO;
3359 case Pow:
3360 return INPLACE_POWER;
3361 case LShift:
3362 return INPLACE_LSHIFT;
3363 case RShift:
3364 return INPLACE_RSHIFT;
3365 case BitOr:
3366 return INPLACE_OR;
3367 case BitXor:
3368 return INPLACE_XOR;
3369 case BitAnd:
3370 return INPLACE_AND;
3371 case FloorDiv:
3372 return INPLACE_FLOOR_DIVIDE;
3373 default:
3374 PyErr_Format(PyExc_SystemError,
3375 "inplace binary op %d should not be possible", op);
3376 return 0;
3377 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003378}
3379
3380static int
3381compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3382{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003383 int op, scope;
3384 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 PyObject *dict = c->u->u_names;
3388 PyObject *mangled;
3389 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003391 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3392 !_PyUnicode_EqualToASCIIString(name, "True") &&
3393 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003394
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003395 mangled = _Py_Mangle(c->u->u_private, name);
3396 if (!mangled)
3397 return 0;
3398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 op = 0;
3400 optype = OP_NAME;
3401 scope = PyST_GetScope(c->u->u_ste, mangled);
3402 switch (scope) {
3403 case FREE:
3404 dict = c->u->u_freevars;
3405 optype = OP_DEREF;
3406 break;
3407 case CELL:
3408 dict = c->u->u_cellvars;
3409 optype = OP_DEREF;
3410 break;
3411 case LOCAL:
3412 if (c->u->u_ste->ste_type == FunctionBlock)
3413 optype = OP_FAST;
3414 break;
3415 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003416 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 optype = OP_GLOBAL;
3418 break;
3419 case GLOBAL_EXPLICIT:
3420 optype = OP_GLOBAL;
3421 break;
3422 default:
3423 /* scope can be 0 */
3424 break;
3425 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003428 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 switch (optype) {
3431 case OP_DEREF:
3432 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003433 case Load:
3434 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3435 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003436 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003437 op = STORE_DEREF;
3438 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 case AugLoad:
3440 case AugStore:
3441 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003442 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 case Param:
3444 default:
3445 PyErr_SetString(PyExc_SystemError,
3446 "param invalid for deref variable");
3447 return 0;
3448 }
3449 break;
3450 case OP_FAST:
3451 switch (ctx) {
3452 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003453 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003454 op = STORE_FAST;
3455 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 case Del: op = DELETE_FAST; break;
3457 case AugLoad:
3458 case AugStore:
3459 break;
3460 case Param:
3461 default:
3462 PyErr_SetString(PyExc_SystemError,
3463 "param invalid for local variable");
3464 return 0;
3465 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003466 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return 1;
3468 case OP_GLOBAL:
3469 switch (ctx) {
3470 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003471 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003472 op = STORE_GLOBAL;
3473 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 case Del: op = DELETE_GLOBAL; break;
3475 case AugLoad:
3476 case AugStore:
3477 break;
3478 case Param:
3479 default:
3480 PyErr_SetString(PyExc_SystemError,
3481 "param invalid for global variable");
3482 return 0;
3483 }
3484 break;
3485 case OP_NAME:
3486 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003487 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003488 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003489 op = STORE_NAME;
3490 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 case Del: op = DELETE_NAME; break;
3492 case AugLoad:
3493 case AugStore:
3494 break;
3495 case Param:
3496 default:
3497 PyErr_SetString(PyExc_SystemError,
3498 "param invalid for name variable");
3499 return 0;
3500 }
3501 break;
3502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 assert(op);
3505 arg = compiler_add_o(c, dict, mangled);
3506 Py_DECREF(mangled);
3507 if (arg < 0)
3508 return 0;
3509 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510}
3511
3512static int
3513compiler_boolop(struct compiler *c, expr_ty e)
3514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003516 int jumpi;
3517 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 assert(e->kind == BoolOp_kind);
3521 if (e->v.BoolOp.op == And)
3522 jumpi = JUMP_IF_FALSE_OR_POP;
3523 else
3524 jumpi = JUMP_IF_TRUE_OR_POP;
3525 end = compiler_new_block(c);
3526 if (end == NULL)
3527 return 0;
3528 s = e->v.BoolOp.values;
3529 n = asdl_seq_LEN(s) - 1;
3530 assert(n >= 0);
3531 for (i = 0; i < n; ++i) {
3532 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3533 ADDOP_JABS(c, jumpi, end);
3534 }
3535 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3536 compiler_use_next_block(c, end);
3537 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538}
3539
3540static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003541starunpack_helper(struct compiler *c, asdl_seq *elts,
3542 int single_op, int inner_op, int outer_op)
3543{
3544 Py_ssize_t n = asdl_seq_LEN(elts);
3545 Py_ssize_t i, nsubitems = 0, nseen = 0;
3546 for (i = 0; i < n; i++) {
3547 expr_ty elt = asdl_seq_GET(elts, i);
3548 if (elt->kind == Starred_kind) {
3549 if (nseen) {
3550 ADDOP_I(c, inner_op, nseen);
3551 nseen = 0;
3552 nsubitems++;
3553 }
3554 VISIT(c, expr, elt->v.Starred.value);
3555 nsubitems++;
3556 }
3557 else {
3558 VISIT(c, expr, elt);
3559 nseen++;
3560 }
3561 }
3562 if (nsubitems) {
3563 if (nseen) {
3564 ADDOP_I(c, inner_op, nseen);
3565 nsubitems++;
3566 }
3567 ADDOP_I(c, outer_op, nsubitems);
3568 }
3569 else
3570 ADDOP_I(c, single_op, nseen);
3571 return 1;
3572}
3573
3574static int
3575assignment_helper(struct compiler *c, asdl_seq *elts)
3576{
3577 Py_ssize_t n = asdl_seq_LEN(elts);
3578 Py_ssize_t i;
3579 int seen_star = 0;
3580 for (i = 0; i < n; i++) {
3581 expr_ty elt = asdl_seq_GET(elts, i);
3582 if (elt->kind == Starred_kind && !seen_star) {
3583 if ((i >= (1 << 8)) ||
3584 (n-i-1 >= (INT_MAX >> 8)))
3585 return compiler_error(c,
3586 "too many expressions in "
3587 "star-unpacking assignment");
3588 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3589 seen_star = 1;
3590 asdl_seq_SET(elts, i, elt->v.Starred.value);
3591 }
3592 else if (elt->kind == Starred_kind) {
3593 return compiler_error(c,
3594 "two starred expressions in assignment");
3595 }
3596 }
3597 if (!seen_star) {
3598 ADDOP_I(c, UNPACK_SEQUENCE, n);
3599 }
3600 VISIT_SEQ(c, expr, elts);
3601 return 1;
3602}
3603
3604static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605compiler_list(struct compiler *c, expr_ty e)
3606{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003607 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003608 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003609 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003611 else if (e->v.List.ctx == Load) {
3612 return starunpack_helper(c, elts,
3613 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003615 else
3616 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618}
3619
3620static int
3621compiler_tuple(struct compiler *c, expr_ty e)
3622{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003623 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003624 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003625 return assignment_helper(c, elts);
3626 }
3627 else if (e->v.Tuple.ctx == Load) {
3628 return starunpack_helper(c, elts,
3629 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3630 }
3631 else
3632 VISIT_SEQ(c, expr, elts);
3633 return 1;
3634}
3635
3636static int
3637compiler_set(struct compiler *c, expr_ty e)
3638{
3639 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3640 BUILD_SET, BUILD_SET_UNPACK);
3641}
3642
3643static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003644are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3645{
3646 Py_ssize_t i;
3647 for (i = begin; i < end; i++) {
3648 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003649 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003650 return 0;
3651 }
3652 return 1;
3653}
3654
3655static int
3656compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3657{
3658 Py_ssize_t i, n = end - begin;
3659 PyObject *keys, *key;
3660 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3661 for (i = begin; i < end; i++) {
3662 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3663 }
3664 keys = PyTuple_New(n);
3665 if (keys == NULL) {
3666 return 0;
3667 }
3668 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003669 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003670 Py_INCREF(key);
3671 PyTuple_SET_ITEM(keys, i - begin, key);
3672 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003673 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003674 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3675 }
3676 else {
3677 for (i = begin; i < end; i++) {
3678 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3679 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3680 }
3681 ADDOP_I(c, BUILD_MAP, n);
3682 }
3683 return 1;
3684}
3685
3686static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687compiler_dict(struct compiler *c, expr_ty e)
3688{
Victor Stinner976bb402016-03-23 11:36:19 +01003689 Py_ssize_t i, n, elements;
3690 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003691 int is_unpacking = 0;
3692 n = asdl_seq_LEN(e->v.Dict.values);
3693 containers = 0;
3694 elements = 0;
3695 for (i = 0; i < n; i++) {
3696 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3697 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003698 if (!compiler_subdict(c, e, i - elements, i))
3699 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003700 containers++;
3701 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003703 if (is_unpacking) {
3704 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3705 containers++;
3706 }
3707 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003708 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 }
3710 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003711 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003712 if (!compiler_subdict(c, e, n - elements, n))
3713 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003714 containers++;
3715 }
3716 /* If there is more than one dict, they need to be merged into a new
3717 * dict. If there is one dict and it's an unpacking, then it needs
3718 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003719 if (containers > 1 || is_unpacking) {
3720 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 }
3722 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723}
3724
3725static int
3726compiler_compare(struct compiler *c, expr_ty e)
3727{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003728 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003730 if (!check_compare(c, e)) {
3731 return 0;
3732 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003734 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3735 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3736 if (n == 0) {
3737 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3738 ADDOP_I(c, COMPARE_OP,
3739 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3740 }
3741 else {
3742 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (cleanup == NULL)
3744 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003745 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 VISIT(c, expr,
3747 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003748 ADDOP(c, DUP_TOP);
3749 ADDOP(c, ROT_THREE);
3750 ADDOP_I(c, COMPARE_OP,
3751 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3752 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3753 NEXT_BLOCK(c);
3754 }
3755 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3756 ADDOP_I(c, COMPARE_OP,
3757 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 basicblock *end = compiler_new_block(c);
3759 if (end == NULL)
3760 return 0;
3761 ADDOP_JREL(c, JUMP_FORWARD, end);
3762 compiler_use_next_block(c, cleanup);
3763 ADDOP(c, ROT_TWO);
3764 ADDOP(c, POP_TOP);
3765 compiler_use_next_block(c, end);
3766 }
3767 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768}
3769
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003770static PyTypeObject *
3771infer_type(expr_ty e)
3772{
3773 switch (e->kind) {
3774 case Tuple_kind:
3775 return &PyTuple_Type;
3776 case List_kind:
3777 case ListComp_kind:
3778 return &PyList_Type;
3779 case Dict_kind:
3780 case DictComp_kind:
3781 return &PyDict_Type;
3782 case Set_kind:
3783 case SetComp_kind:
3784 return &PySet_Type;
3785 case GeneratorExp_kind:
3786 return &PyGen_Type;
3787 case Lambda_kind:
3788 return &PyFunction_Type;
3789 case JoinedStr_kind:
3790 case FormattedValue_kind:
3791 return &PyUnicode_Type;
3792 case Constant_kind:
3793 return e->v.Constant.value->ob_type;
3794 default:
3795 return NULL;
3796 }
3797}
3798
3799static int
3800check_caller(struct compiler *c, expr_ty e)
3801{
3802 switch (e->kind) {
3803 case Constant_kind:
3804 case Tuple_kind:
3805 case List_kind:
3806 case ListComp_kind:
3807 case Dict_kind:
3808 case DictComp_kind:
3809 case Set_kind:
3810 case SetComp_kind:
3811 case GeneratorExp_kind:
3812 case JoinedStr_kind:
3813 case FormattedValue_kind:
3814 return compiler_warn(c, "'%.200s' object is not callable; "
3815 "perhaps you missed a comma?",
3816 infer_type(e)->tp_name);
3817 default:
3818 return 1;
3819 }
3820}
3821
3822static int
3823check_subscripter(struct compiler *c, expr_ty e)
3824{
3825 PyObject *v;
3826
3827 switch (e->kind) {
3828 case Constant_kind:
3829 v = e->v.Constant.value;
3830 if (!(v == Py_None || v == Py_Ellipsis ||
3831 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3832 PyAnySet_Check(v)))
3833 {
3834 return 1;
3835 }
3836 /* fall through */
3837 case Set_kind:
3838 case SetComp_kind:
3839 case GeneratorExp_kind:
3840 case Lambda_kind:
3841 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3842 "perhaps you missed a comma?",
3843 infer_type(e)->tp_name);
3844 default:
3845 return 1;
3846 }
3847}
3848
3849static int
3850check_index(struct compiler *c, expr_ty e, slice_ty s)
3851{
3852 PyObject *v;
3853
3854 if (s->kind != Index_kind) {
3855 return 1;
3856 }
3857 PyTypeObject *index_type = infer_type(s->v.Index.value);
3858 if (index_type == NULL
3859 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3860 || index_type == &PySlice_Type) {
3861 return 1;
3862 }
3863
3864 switch (e->kind) {
3865 case Constant_kind:
3866 v = e->v.Constant.value;
3867 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3868 return 1;
3869 }
3870 /* fall through */
3871 case Tuple_kind:
3872 case List_kind:
3873 case ListComp_kind:
3874 case JoinedStr_kind:
3875 case FormattedValue_kind:
3876 return compiler_warn(c, "%.200s indices must be integers or slices, "
3877 "not %.200s; "
3878 "perhaps you missed a comma?",
3879 infer_type(e)->tp_name,
3880 index_type->tp_name);
3881 default:
3882 return 1;
3883 }
3884}
3885
Zackery Spytz97f5de02019-03-22 01:30:32 -06003886// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003888maybe_optimize_method_call(struct compiler *c, expr_ty e)
3889{
3890 Py_ssize_t argsl, i;
3891 expr_ty meth = e->v.Call.func;
3892 asdl_seq *args = e->v.Call.args;
3893
3894 /* Check that the call node is an attribute access, and that
3895 the call doesn't have keyword parameters. */
3896 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3897 asdl_seq_LEN(e->v.Call.keywords))
3898 return -1;
3899
3900 /* Check that there are no *varargs types of arguments. */
3901 argsl = asdl_seq_LEN(args);
3902 for (i = 0; i < argsl; i++) {
3903 expr_ty elt = asdl_seq_GET(args, i);
3904 if (elt->kind == Starred_kind) {
3905 return -1;
3906 }
3907 }
3908
3909 /* Alright, we can optimize the code. */
3910 VISIT(c, expr, meth->v.Attribute.value);
3911 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3912 VISIT_SEQ(c, expr, e->v.Call.args);
3913 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3914 return 1;
3915}
3916
3917static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918compiler_call(struct compiler *c, expr_ty e)
3919{
Zackery Spytz97f5de02019-03-22 01:30:32 -06003920 int ret = maybe_optimize_method_call(c, e);
3921 if (ret >= 0) {
3922 return ret;
3923 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003924 if (!check_caller(c, e->v.Call.func)) {
3925 return 0;
3926 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 VISIT(c, expr, e->v.Call.func);
3928 return compiler_call_helper(c, 0,
3929 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003930 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003931}
3932
Eric V. Smith235a6f02015-09-19 14:51:32 -04003933static int
3934compiler_joined_str(struct compiler *c, expr_ty e)
3935{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003936 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003937 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3938 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003939 return 1;
3940}
3941
Eric V. Smitha78c7952015-11-03 12:45:05 -05003942/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003943static int
3944compiler_formatted_value(struct compiler *c, expr_ty e)
3945{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003946 /* Our oparg encodes 2 pieces of information: the conversion
3947 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003948
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003949 Convert the conversion char to 3 bits:
3950 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05003951 !s : 001 0x1 FVC_STR
3952 !r : 010 0x2 FVC_REPR
3953 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003954
Eric V. Smitha78c7952015-11-03 12:45:05 -05003955 next bit is whether or not we have a format spec:
3956 yes : 100 0x4
3957 no : 000 0x0
3958 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003959
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003960 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05003961 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003962
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003963 if (e->v.FormattedValue.expr_text) {
3964 /* Push the text of the expression (which already has the '=' in
3965 it. */
3966 ADDOP_LOAD_CONST(c, e->v.FormattedValue.expr_text);
3967 }
3968
3969 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003970 VISIT(c, expr, e->v.FormattedValue.value);
3971
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003972 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003973 case 's': oparg = FVC_STR; break;
3974 case 'r': oparg = FVC_REPR; break;
3975 case 'a': oparg = FVC_ASCII; break;
3976 case -1: oparg = FVC_NONE; break;
3977 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003978 PyErr_Format(PyExc_SystemError,
3979 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003980 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003981 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003982 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003983 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003984 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003985 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003986 }
3987
Eric V. Smitha78c7952015-11-03 12:45:05 -05003988 /* And push our opcode and oparg */
3989 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04003990
3991 /* If we have expr_text, join the 2 strings on the stack. */
3992 if (e->v.FormattedValue.expr_text) {
3993 ADDOP_I(c, BUILD_STRING, 2);
3994 }
3995
Eric V. Smith235a6f02015-09-19 14:51:32 -04003996 return 1;
3997}
3998
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003999static int
4000compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
4001{
4002 Py_ssize_t i, n = end - begin;
4003 keyword_ty kw;
4004 PyObject *keys, *key;
4005 assert(n > 0);
4006 if (n > 1) {
4007 for (i = begin; i < end; i++) {
4008 kw = asdl_seq_GET(keywords, i);
4009 VISIT(c, expr, kw->value);
4010 }
4011 keys = PyTuple_New(n);
4012 if (keys == NULL) {
4013 return 0;
4014 }
4015 for (i = begin; i < end; i++) {
4016 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4017 Py_INCREF(key);
4018 PyTuple_SET_ITEM(keys, i - begin, key);
4019 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004020 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004021 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4022 }
4023 else {
4024 /* a for loop only executes once */
4025 for (i = begin; i < end; i++) {
4026 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004027 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004028 VISIT(c, expr, kw->value);
4029 }
4030 ADDOP_I(c, BUILD_MAP, n);
4031 }
4032 return 1;
4033}
4034
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004035/* shared code between compiler_call and compiler_class */
4036static int
4037compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004038 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004039 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004040 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004041{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004042 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004043 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004044
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004045 /* the number of tuples and dictionaries on the stack */
4046 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4047
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004048 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004049 nkwelts = asdl_seq_LEN(keywords);
4050
4051 for (i = 0; i < nkwelts; i++) {
4052 keyword_ty kw = asdl_seq_GET(keywords, i);
4053 if (kw->arg == NULL) {
4054 mustdictunpack = 1;
4055 break;
4056 }
4057 }
4058
4059 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004060 for (i = 0; i < nelts; i++) {
4061 expr_ty elt = asdl_seq_GET(args, i);
4062 if (elt->kind == Starred_kind) {
4063 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004064 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004065 if (nseen) {
4066 ADDOP_I(c, BUILD_TUPLE, nseen);
4067 nseen = 0;
4068 nsubargs++;
4069 }
4070 VISIT(c, expr, elt->v.Starred.value);
4071 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004072 }
4073 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004074 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004075 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004078
4079 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004080 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004081 if (nseen) {
4082 /* Pack up any trailing positional arguments. */
4083 ADDOP_I(c, BUILD_TUPLE, nseen);
4084 nsubargs++;
4085 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004086 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004087 /* If we ended up with more than one stararg, we need
4088 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004089 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004090 }
4091 else if (nsubargs == 0) {
4092 ADDOP_I(c, BUILD_TUPLE, 0);
4093 }
4094 nseen = 0; /* the number of keyword arguments on the stack following */
4095 for (i = 0; i < nkwelts; i++) {
4096 keyword_ty kw = asdl_seq_GET(keywords, i);
4097 if (kw->arg == NULL) {
4098 /* A keyword argument unpacking. */
4099 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004100 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4101 return 0;
4102 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004103 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004104 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004105 VISIT(c, expr, kw->value);
4106 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004107 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004108 else {
4109 nseen++;
4110 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004111 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004112 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004113 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004114 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004115 return 0;
4116 nsubkwargs++;
4117 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004118 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004119 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004120 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004121 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004122 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004125 else if (nkwelts) {
4126 PyObject *names;
4127 VISIT_SEQ(c, keyword, keywords);
4128 names = PyTuple_New(nkwelts);
4129 if (names == NULL) {
4130 return 0;
4131 }
4132 for (i = 0; i < nkwelts; i++) {
4133 keyword_ty kw = asdl_seq_GET(keywords, i);
4134 Py_INCREF(kw->arg);
4135 PyTuple_SET_ITEM(names, i, kw->arg);
4136 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004137 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004138 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4139 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004141 else {
4142 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4143 return 1;
4144 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145}
4146
Nick Coghlan650f0d02007-04-15 12:05:43 +00004147
4148/* List and set comprehensions and generator expressions work by creating a
4149 nested function to perform the actual iteration. This means that the
4150 iteration variables don't leak into the current scope.
4151 The defined function is called immediately following its definition, with the
4152 result of that call being the result of the expression.
4153 The LC/SC version returns the populated container, while the GE version is
4154 flagged in symtable.c as a generator, so it returns the generator object
4155 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004156
4157 Possible cleanups:
4158 - iterate over the generator sequence instead of using recursion
4159*/
4160
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163compiler_comprehension_generator(struct compiler *c,
4164 asdl_seq *generators, int gen_index,
4165 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004167 comprehension_ty gen;
4168 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4169 if (gen->is_async) {
4170 return compiler_async_comprehension_generator(
4171 c, generators, gen_index, elt, val, type);
4172 } else {
4173 return compiler_sync_comprehension_generator(
4174 c, generators, gen_index, elt, val, type);
4175 }
4176}
4177
4178static int
4179compiler_sync_comprehension_generator(struct compiler *c,
4180 asdl_seq *generators, int gen_index,
4181 expr_ty elt, expr_ty val, int type)
4182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 /* generate code for the iterator, then each of the ifs,
4184 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 comprehension_ty gen;
4187 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004188 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 start = compiler_new_block(c);
4191 skip = compiler_new_block(c);
4192 if_cleanup = compiler_new_block(c);
4193 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4196 anchor == NULL)
4197 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 if (gen_index == 0) {
4202 /* Receive outermost iter as an implicit argument */
4203 c->u->u_argcount = 1;
4204 ADDOP_I(c, LOAD_FAST, 0);
4205 }
4206 else {
4207 /* Sub-iter - calculate on the fly */
4208 VISIT(c, expr, gen->iter);
4209 ADDOP(c, GET_ITER);
4210 }
4211 compiler_use_next_block(c, start);
4212 ADDOP_JREL(c, FOR_ITER, anchor);
4213 NEXT_BLOCK(c);
4214 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 /* XXX this needs to be cleaned up...a lot! */
4217 n = asdl_seq_LEN(gen->ifs);
4218 for (i = 0; i < n; i++) {
4219 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004220 if (!compiler_jump_if(c, e, if_cleanup, 0))
4221 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 NEXT_BLOCK(c);
4223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 if (++gen_index < asdl_seq_LEN(generators))
4226 if (!compiler_comprehension_generator(c,
4227 generators, gen_index,
4228 elt, val, type))
4229 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 /* only append after the last for generator */
4232 if (gen_index >= asdl_seq_LEN(generators)) {
4233 /* comprehension specific code */
4234 switch (type) {
4235 case COMP_GENEXP:
4236 VISIT(c, expr, elt);
4237 ADDOP(c, YIELD_VALUE);
4238 ADDOP(c, POP_TOP);
4239 break;
4240 case COMP_LISTCOMP:
4241 VISIT(c, expr, elt);
4242 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4243 break;
4244 case COMP_SETCOMP:
4245 VISIT(c, expr, elt);
4246 ADDOP_I(c, SET_ADD, gen_index + 1);
4247 break;
4248 case COMP_DICTCOMP:
4249 /* With 'd[k] = v', v is evaluated before k, so we do
4250 the same. */
4251 VISIT(c, expr, val);
4252 VISIT(c, expr, elt);
4253 ADDOP_I(c, MAP_ADD, gen_index + 1);
4254 break;
4255 default:
4256 return 0;
4257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 compiler_use_next_block(c, skip);
4260 }
4261 compiler_use_next_block(c, if_cleanup);
4262 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4263 compiler_use_next_block(c, anchor);
4264
4265 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004266}
4267
4268static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004269compiler_async_comprehension_generator(struct compiler *c,
4270 asdl_seq *generators, int gen_index,
4271 expr_ty elt, expr_ty val, int type)
4272{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004273 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004274 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004275 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004276 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004277 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004278 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004279
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004280 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004281 return 0;
4282 }
4283
4284 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4285
4286 if (gen_index == 0) {
4287 /* Receive outermost iter as an implicit argument */
4288 c->u->u_argcount = 1;
4289 ADDOP_I(c, LOAD_FAST, 0);
4290 }
4291 else {
4292 /* Sub-iter - calculate on the fly */
4293 VISIT(c, expr, gen->iter);
4294 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004295 }
4296
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004297 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004298
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004299 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004300 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004301 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004302 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004303 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004304 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004305
4306 n = asdl_seq_LEN(gen->ifs);
4307 for (i = 0; i < n; i++) {
4308 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004309 if (!compiler_jump_if(c, e, if_cleanup, 0))
4310 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004311 NEXT_BLOCK(c);
4312 }
4313
4314 if (++gen_index < asdl_seq_LEN(generators))
4315 if (!compiler_comprehension_generator(c,
4316 generators, gen_index,
4317 elt, val, type))
4318 return 0;
4319
4320 /* only append after the last for generator */
4321 if (gen_index >= asdl_seq_LEN(generators)) {
4322 /* comprehension specific code */
4323 switch (type) {
4324 case COMP_GENEXP:
4325 VISIT(c, expr, elt);
4326 ADDOP(c, YIELD_VALUE);
4327 ADDOP(c, POP_TOP);
4328 break;
4329 case COMP_LISTCOMP:
4330 VISIT(c, expr, elt);
4331 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4332 break;
4333 case COMP_SETCOMP:
4334 VISIT(c, expr, elt);
4335 ADDOP_I(c, SET_ADD, gen_index + 1);
4336 break;
4337 case COMP_DICTCOMP:
4338 /* With 'd[k] = v', v is evaluated before k, so we do
4339 the same. */
4340 VISIT(c, expr, val);
4341 VISIT(c, expr, elt);
4342 ADDOP_I(c, MAP_ADD, gen_index + 1);
4343 break;
4344 default:
4345 return 0;
4346 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004347 }
4348 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004349 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4350
4351 compiler_use_next_block(c, except);
4352 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004353
4354 return 1;
4355}
4356
4357static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004358compiler_comprehension(struct compiler *c, expr_ty e, int type,
4359 identifier name, asdl_seq *generators, expr_ty elt,
4360 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004363 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004364 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004365 int is_async_function = c->u->u_ste->ste_coroutine;
4366 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004367
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004369
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004370 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4371 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004374 }
4375
4376 is_async_generator = c->u->u_ste->ste_coroutine;
4377
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004378 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004379 compiler_error(c, "asynchronous comprehension outside of "
4380 "an asynchronous function");
4381 goto error_in_scope;
4382 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 if (type != COMP_GENEXP) {
4385 int op;
4386 switch (type) {
4387 case COMP_LISTCOMP:
4388 op = BUILD_LIST;
4389 break;
4390 case COMP_SETCOMP:
4391 op = BUILD_SET;
4392 break;
4393 case COMP_DICTCOMP:
4394 op = BUILD_MAP;
4395 break;
4396 default:
4397 PyErr_Format(PyExc_SystemError,
4398 "unknown comprehension type %d", type);
4399 goto error_in_scope;
4400 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 ADDOP_I(c, op, 0);
4403 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 if (!compiler_comprehension_generator(c, generators, 0, elt,
4406 val, type))
4407 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 if (type != COMP_GENEXP) {
4410 ADDOP(c, RETURN_VALUE);
4411 }
4412
4413 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004414 qualname = c->u->u_qualname;
4415 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004417 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 goto error;
4419
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004420 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004422 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 Py_DECREF(co);
4424
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425 VISIT(c, expr, outermost->iter);
4426
4427 if (outermost->is_async) {
4428 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004429 } else {
4430 ADDOP(c, GET_ITER);
4431 }
4432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004434
4435 if (is_async_generator && type != COMP_GENEXP) {
4436 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004437 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004438 ADDOP(c, YIELD_FROM);
4439 }
4440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004442error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004444error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004445 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 Py_XDECREF(co);
4447 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004448}
4449
4450static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004451compiler_genexp(struct compiler *c, expr_ty e)
4452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 static identifier name;
4454 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004455 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 if (!name)
4457 return 0;
4458 }
4459 assert(e->kind == GeneratorExp_kind);
4460 return compiler_comprehension(c, e, COMP_GENEXP, name,
4461 e->v.GeneratorExp.generators,
4462 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004463}
4464
4465static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004466compiler_listcomp(struct compiler *c, expr_ty e)
4467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 static identifier name;
4469 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004470 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 if (!name)
4472 return 0;
4473 }
4474 assert(e->kind == ListComp_kind);
4475 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4476 e->v.ListComp.generators,
4477 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004478}
4479
4480static int
4481compiler_setcomp(struct compiler *c, expr_ty e)
4482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 static identifier name;
4484 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004485 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 if (!name)
4487 return 0;
4488 }
4489 assert(e->kind == SetComp_kind);
4490 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4491 e->v.SetComp.generators,
4492 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004493}
4494
4495
4496static int
4497compiler_dictcomp(struct compiler *c, expr_ty e)
4498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 static identifier name;
4500 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004501 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 if (!name)
4503 return 0;
4504 }
4505 assert(e->kind == DictComp_kind);
4506 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4507 e->v.DictComp.generators,
4508 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004509}
4510
4511
4512static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004513compiler_visit_keyword(struct compiler *c, keyword_ty k)
4514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 VISIT(c, expr, k->value);
4516 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004517}
4518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004520 whether they are true or false.
4521
4522 Return values: 1 for true, 0 for false, -1 for non-constant.
4523 */
4524
4525static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004526expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004527{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004528 if (e->kind == Constant_kind) {
4529 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004530 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004531 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004532}
4533
Yury Selivanov75445082015-05-11 22:57:16 -04004534
4535/*
4536 Implements the async with statement.
4537
4538 The semantics outlined in that PEP are as follows:
4539
4540 async with EXPR as VAR:
4541 BLOCK
4542
4543 It is implemented roughly as:
4544
4545 context = EXPR
4546 exit = context.__aexit__ # not calling it
4547 value = await context.__aenter__()
4548 try:
4549 VAR = value # if VAR present in the syntax
4550 BLOCK
4551 finally:
4552 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004553 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004554 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004555 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004556 if not (await exit(*exc)):
4557 raise
4558 */
4559static int
4560compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4561{
4562 basicblock *block, *finally;
4563 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4564
4565 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004566 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4567 return compiler_error(c, "'async with' outside async function");
4568 }
Yury Selivanov75445082015-05-11 22:57:16 -04004569
4570 block = compiler_new_block(c);
4571 finally = compiler_new_block(c);
4572 if (!block || !finally)
4573 return 0;
4574
4575 /* Evaluate EXPR */
4576 VISIT(c, expr, item->context_expr);
4577
4578 ADDOP(c, BEFORE_ASYNC_WITH);
4579 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004580 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004581 ADDOP(c, YIELD_FROM);
4582
4583 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4584
4585 /* SETUP_ASYNC_WITH pushes a finally block. */
4586 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004587 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004588 return 0;
4589 }
4590
4591 if (item->optional_vars) {
4592 VISIT(c, expr, item->optional_vars);
4593 }
4594 else {
4595 /* Discard result from context.__aenter__() */
4596 ADDOP(c, POP_TOP);
4597 }
4598
4599 pos++;
4600 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4601 /* BLOCK code */
4602 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4603 else if (!compiler_async_with(c, s, pos))
4604 return 0;
4605
4606 /* End of try block; start the finally block */
4607 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004608 ADDOP(c, BEGIN_FINALLY);
4609 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004610
Yury Selivanov75445082015-05-11 22:57:16 -04004611 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004612 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004613 return 0;
4614
4615 /* Finally block starts; context.__exit__ is on the stack under
4616 the exception or return information. Just issue our magic
4617 opcode. */
4618 ADDOP(c, WITH_CLEANUP_START);
4619
4620 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004621 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004622 ADDOP(c, YIELD_FROM);
4623
4624 ADDOP(c, WITH_CLEANUP_FINISH);
4625
4626 /* Finally block ends. */
4627 ADDOP(c, END_FINALLY);
4628 compiler_pop_fblock(c, FINALLY_END, finally);
4629 return 1;
4630}
4631
4632
Guido van Rossumc2e20742006-02-27 22:32:47 +00004633/*
4634 Implements the with statement from PEP 343.
4635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004637
4638 with EXPR as VAR:
4639 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640
Guido van Rossumc2e20742006-02-27 22:32:47 +00004641 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642
Thomas Wouters477c8d52006-05-27 19:21:47 +00004643 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004644 exit = context.__exit__ # not calling it
4645 value = context.__enter__()
4646 try:
4647 VAR = value # if VAR present in the syntax
4648 BLOCK
4649 finally:
4650 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004651 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004652 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004653 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004654 exit(*exc)
4655 */
4656static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004657compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004658{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004659 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004660 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004661
4662 assert(s->kind == With_kind);
4663
Guido van Rossumc2e20742006-02-27 22:32:47 +00004664 block = compiler_new_block(c);
4665 finally = compiler_new_block(c);
4666 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004667 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004668
Thomas Wouters477c8d52006-05-27 19:21:47 +00004669 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004670 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004671 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004672
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004673 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004674 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004675 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004676 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004677 }
4678
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004679 if (item->optional_vars) {
4680 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004681 }
4682 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004684 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004685 }
4686
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004687 pos++;
4688 if (pos == asdl_seq_LEN(s->v.With.items))
4689 /* BLOCK code */
4690 VISIT_SEQ(c, stmt, s->v.With.body)
4691 else if (!compiler_with(c, s, pos))
4692 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004693
4694 /* End of try block; start the finally block */
4695 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004696 ADDOP(c, BEGIN_FINALLY);
4697 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004698
Guido van Rossumc2e20742006-02-27 22:32:47 +00004699 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004700 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004701 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004702
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004703 /* Finally block starts; context.__exit__ is on the stack under
4704 the exception or return information. Just issue our magic
4705 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004706 ADDOP(c, WITH_CLEANUP_START);
4707 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004708
4709 /* Finally block ends. */
4710 ADDOP(c, END_FINALLY);
4711 compiler_pop_fblock(c, FINALLY_END, finally);
4712 return 1;
4713}
4714
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004715static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004716compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004719 case NamedExpr_kind:
4720 VISIT(c, expr, e->v.NamedExpr.value);
4721 ADDOP(c, DUP_TOP);
4722 VISIT(c, expr, e->v.NamedExpr.target);
4723 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 case BoolOp_kind:
4725 return compiler_boolop(c, e);
4726 case BinOp_kind:
4727 VISIT(c, expr, e->v.BinOp.left);
4728 VISIT(c, expr, e->v.BinOp.right);
4729 ADDOP(c, binop(c, e->v.BinOp.op));
4730 break;
4731 case UnaryOp_kind:
4732 VISIT(c, expr, e->v.UnaryOp.operand);
4733 ADDOP(c, unaryop(e->v.UnaryOp.op));
4734 break;
4735 case Lambda_kind:
4736 return compiler_lambda(c, e);
4737 case IfExp_kind:
4738 return compiler_ifexp(c, e);
4739 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004740 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004742 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 case GeneratorExp_kind:
4744 return compiler_genexp(c, e);
4745 case ListComp_kind:
4746 return compiler_listcomp(c, e);
4747 case SetComp_kind:
4748 return compiler_setcomp(c, e);
4749 case DictComp_kind:
4750 return compiler_dictcomp(c, e);
4751 case Yield_kind:
4752 if (c->u->u_ste->ste_type != FunctionBlock)
4753 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004754 if (e->v.Yield.value) {
4755 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 }
4757 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004758 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004760 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004762 case YieldFrom_kind:
4763 if (c->u->u_ste->ste_type != FunctionBlock)
4764 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004765
4766 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4767 return compiler_error(c, "'yield from' inside async function");
4768
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004769 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004770 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004771 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004772 ADDOP(c, YIELD_FROM);
4773 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004774 case Await_kind:
4775 if (c->u->u_ste->ste_type != FunctionBlock)
4776 return compiler_error(c, "'await' outside function");
4777
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004778 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4779 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004780 return compiler_error(c, "'await' outside async function");
4781
4782 VISIT(c, expr, e->v.Await.value);
4783 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004784 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004785 ADDOP(c, YIELD_FROM);
4786 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 case Compare_kind:
4788 return compiler_compare(c, e);
4789 case Call_kind:
4790 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004791 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004792 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004793 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004794 case JoinedStr_kind:
4795 return compiler_joined_str(c, e);
4796 case FormattedValue_kind:
4797 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 /* The following exprs can be assignment targets. */
4799 case Attribute_kind:
4800 if (e->v.Attribute.ctx != AugStore)
4801 VISIT(c, expr, e->v.Attribute.value);
4802 switch (e->v.Attribute.ctx) {
4803 case AugLoad:
4804 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004805 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 case Load:
4807 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4808 break;
4809 case AugStore:
4810 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004811 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 case Store:
4813 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4814 break;
4815 case Del:
4816 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4817 break;
4818 case Param:
4819 default:
4820 PyErr_SetString(PyExc_SystemError,
4821 "param invalid in attribute expression");
4822 return 0;
4823 }
4824 break;
4825 case Subscript_kind:
4826 switch (e->v.Subscript.ctx) {
4827 case AugLoad:
4828 VISIT(c, expr, e->v.Subscript.value);
4829 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4830 break;
4831 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004832 if (!check_subscripter(c, e->v.Subscript.value)) {
4833 return 0;
4834 }
4835 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4836 return 0;
4837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 VISIT(c, expr, e->v.Subscript.value);
4839 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4840 break;
4841 case AugStore:
4842 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4843 break;
4844 case Store:
4845 VISIT(c, expr, e->v.Subscript.value);
4846 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4847 break;
4848 case Del:
4849 VISIT(c, expr, e->v.Subscript.value);
4850 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4851 break;
4852 case Param:
4853 default:
4854 PyErr_SetString(PyExc_SystemError,
4855 "param invalid in subscript expression");
4856 return 0;
4857 }
4858 break;
4859 case Starred_kind:
4860 switch (e->v.Starred.ctx) {
4861 case Store:
4862 /* In all legitimate cases, the Starred node was already replaced
4863 * by compiler_list/compiler_tuple. XXX: is that okay? */
4864 return compiler_error(c,
4865 "starred assignment target must be in a list or tuple");
4866 default:
4867 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004868 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 }
4870 break;
4871 case Name_kind:
4872 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4873 /* child nodes of List and Tuple will have expr_context set */
4874 case List_kind:
4875 return compiler_list(c, e);
4876 case Tuple_kind:
4877 return compiler_tuple(c, e);
4878 }
4879 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004880}
4881
4882static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004883compiler_visit_expr(struct compiler *c, expr_ty e)
4884{
4885 /* If expr e has a different line number than the last expr/stmt,
4886 set a new line number for the next instruction.
4887 */
4888 int old_lineno = c->u->u_lineno;
4889 int old_col_offset = c->u->u_col_offset;
4890 if (e->lineno != c->u->u_lineno) {
4891 c->u->u_lineno = e->lineno;
4892 c->u->u_lineno_set = 0;
4893 }
4894 /* Updating the column offset is always harmless. */
4895 c->u->u_col_offset = e->col_offset;
4896
4897 int res = compiler_visit_expr1(c, e);
4898
4899 if (old_lineno != c->u->u_lineno) {
4900 c->u->u_lineno = old_lineno;
4901 c->u->u_lineno_set = 0;
4902 }
4903 c->u->u_col_offset = old_col_offset;
4904 return res;
4905}
4906
4907static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004908compiler_augassign(struct compiler *c, stmt_ty s)
4909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 expr_ty e = s->v.AugAssign.target;
4911 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 switch (e->kind) {
4916 case Attribute_kind:
4917 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004918 AugLoad, e->lineno, e->col_offset,
4919 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 if (auge == NULL)
4921 return 0;
4922 VISIT(c, expr, auge);
4923 VISIT(c, expr, s->v.AugAssign.value);
4924 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4925 auge->v.Attribute.ctx = AugStore;
4926 VISIT(c, expr, auge);
4927 break;
4928 case Subscript_kind:
4929 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004930 AugLoad, e->lineno, e->col_offset,
4931 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004932 if (auge == NULL)
4933 return 0;
4934 VISIT(c, expr, auge);
4935 VISIT(c, expr, s->v.AugAssign.value);
4936 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4937 auge->v.Subscript.ctx = AugStore;
4938 VISIT(c, expr, auge);
4939 break;
4940 case Name_kind:
4941 if (!compiler_nameop(c, e->v.Name.id, Load))
4942 return 0;
4943 VISIT(c, expr, s->v.AugAssign.value);
4944 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4945 return compiler_nameop(c, e->v.Name.id, Store);
4946 default:
4947 PyErr_Format(PyExc_SystemError,
4948 "invalid node type (%d) for augmented assignment",
4949 e->kind);
4950 return 0;
4951 }
4952 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953}
4954
4955static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004956check_ann_expr(struct compiler *c, expr_ty e)
4957{
4958 VISIT(c, expr, e);
4959 ADDOP(c, POP_TOP);
4960 return 1;
4961}
4962
4963static int
4964check_annotation(struct compiler *c, stmt_ty s)
4965{
4966 /* Annotations are only evaluated in a module or class. */
4967 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4968 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4969 return check_ann_expr(c, s->v.AnnAssign.annotation);
4970 }
4971 return 1;
4972}
4973
4974static int
4975check_ann_slice(struct compiler *c, slice_ty sl)
4976{
4977 switch(sl->kind) {
4978 case Index_kind:
4979 return check_ann_expr(c, sl->v.Index.value);
4980 case Slice_kind:
4981 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4982 return 0;
4983 }
4984 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4985 return 0;
4986 }
4987 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4988 return 0;
4989 }
4990 break;
4991 default:
4992 PyErr_SetString(PyExc_SystemError,
4993 "unexpected slice kind");
4994 return 0;
4995 }
4996 return 1;
4997}
4998
4999static int
5000check_ann_subscr(struct compiler *c, slice_ty sl)
5001{
5002 /* We check that everything in a subscript is defined at runtime. */
5003 Py_ssize_t i, n;
5004
5005 switch (sl->kind) {
5006 case Index_kind:
5007 case Slice_kind:
5008 if (!check_ann_slice(c, sl)) {
5009 return 0;
5010 }
5011 break;
5012 case ExtSlice_kind:
5013 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
5014 for (i = 0; i < n; i++) {
5015 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
5016 switch (subsl->kind) {
5017 case Index_kind:
5018 case Slice_kind:
5019 if (!check_ann_slice(c, subsl)) {
5020 return 0;
5021 }
5022 break;
5023 case ExtSlice_kind:
5024 default:
5025 PyErr_SetString(PyExc_SystemError,
5026 "extended slice invalid in nested slice");
5027 return 0;
5028 }
5029 }
5030 break;
5031 default:
5032 PyErr_Format(PyExc_SystemError,
5033 "invalid subscript kind %d", sl->kind);
5034 return 0;
5035 }
5036 return 1;
5037}
5038
5039static int
5040compiler_annassign(struct compiler *c, stmt_ty s)
5041{
5042 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005043 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005044
5045 assert(s->kind == AnnAssign_kind);
5046
5047 /* We perform the actual assignment first. */
5048 if (s->v.AnnAssign.value) {
5049 VISIT(c, expr, s->v.AnnAssign.value);
5050 VISIT(c, expr, targ);
5051 }
5052 switch (targ->kind) {
5053 case Name_kind:
5054 /* If we have a simple name in a module or class, store annotation. */
5055 if (s->v.AnnAssign.simple &&
5056 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5057 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005058 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5059 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5060 }
5061 else {
5062 VISIT(c, expr, s->v.AnnAssign.annotation);
5063 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005064 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005065 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005066 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005067 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005068 }
5069 break;
5070 case Attribute_kind:
5071 if (!s->v.AnnAssign.value &&
5072 !check_ann_expr(c, targ->v.Attribute.value)) {
5073 return 0;
5074 }
5075 break;
5076 case Subscript_kind:
5077 if (!s->v.AnnAssign.value &&
5078 (!check_ann_expr(c, targ->v.Subscript.value) ||
5079 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5080 return 0;
5081 }
5082 break;
5083 default:
5084 PyErr_Format(PyExc_SystemError,
5085 "invalid node type (%d) for annotated assignment",
5086 targ->kind);
5087 return 0;
5088 }
5089 /* Annotation is evaluated last. */
5090 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5091 return 0;
5092 }
5093 return 1;
5094}
5095
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005096/* Raises a SyntaxError and returns 0.
5097 If something goes wrong, a different exception may be raised.
5098*/
5099
5100static int
5101compiler_error(struct compiler *c, const char *errstr)
5102{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005103 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005105
Victor Stinner14e461d2013-08-26 22:28:21 +02005106 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 if (!loc) {
5108 Py_INCREF(Py_None);
5109 loc = Py_None;
5110 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005111 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005112 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 if (!u)
5114 goto exit;
5115 v = Py_BuildValue("(zO)", errstr, u);
5116 if (!v)
5117 goto exit;
5118 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005119 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 Py_DECREF(loc);
5121 Py_XDECREF(u);
5122 Py_XDECREF(v);
5123 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005124}
5125
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005126/* Emits a SyntaxWarning and returns 1 on success.
5127 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5128 and returns 0.
5129*/
5130static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005131compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005132{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005133 va_list vargs;
5134#ifdef HAVE_STDARG_PROTOTYPES
5135 va_start(vargs, format);
5136#else
5137 va_start(vargs);
5138#endif
5139 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5140 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005141 if (msg == NULL) {
5142 return 0;
5143 }
5144 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5145 c->u->u_lineno, NULL, NULL) < 0)
5146 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005147 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005148 /* Replace the SyntaxWarning exception with a SyntaxError
5149 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005150 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005151 assert(PyUnicode_AsUTF8(msg) != NULL);
5152 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005153 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005154 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005155 return 0;
5156 }
5157 Py_DECREF(msg);
5158 return 1;
5159}
5160
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005161static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162compiler_handle_subscr(struct compiler *c, const char *kind,
5163 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 /* XXX this code is duplicated */
5168 switch (ctx) {
5169 case AugLoad: /* fall through to Load */
5170 case Load: op = BINARY_SUBSCR; break;
5171 case AugStore:/* fall through to Store */
5172 case Store: op = STORE_SUBSCR; break;
5173 case Del: op = DELETE_SUBSCR; break;
5174 case Param:
5175 PyErr_Format(PyExc_SystemError,
5176 "invalid %s kind %d in subscript\n",
5177 kind, ctx);
5178 return 0;
5179 }
5180 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005181 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 }
5183 else if (ctx == AugStore) {
5184 ADDOP(c, ROT_THREE);
5185 }
5186 ADDOP(c, op);
5187 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005188}
5189
5190static int
5191compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 int n = 2;
5194 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 /* only handles the cases where BUILD_SLICE is emitted */
5197 if (s->v.Slice.lower) {
5198 VISIT(c, expr, s->v.Slice.lower);
5199 }
5200 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005201 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 if (s->v.Slice.upper) {
5205 VISIT(c, expr, s->v.Slice.upper);
5206 }
5207 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005208 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 }
5210
5211 if (s->v.Slice.step) {
5212 n++;
5213 VISIT(c, expr, s->v.Slice.step);
5214 }
5215 ADDOP_I(c, BUILD_SLICE, n);
5216 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005217}
5218
5219static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5221 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 switch (s->kind) {
5224 case Slice_kind:
5225 return compiler_slice(c, s, ctx);
5226 case Index_kind:
5227 VISIT(c, expr, s->v.Index.value);
5228 break;
5229 case ExtSlice_kind:
5230 default:
5231 PyErr_SetString(PyExc_SystemError,
5232 "extended slice invalid in nested slice");
5233 return 0;
5234 }
5235 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005236}
5237
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005238static int
5239compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5240{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005241 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005242 switch (s->kind) {
5243 case Index_kind:
5244 kindname = "index";
5245 if (ctx != AugStore) {
5246 VISIT(c, expr, s->v.Index.value);
5247 }
5248 break;
5249 case Slice_kind:
5250 kindname = "slice";
5251 if (ctx != AugStore) {
5252 if (!compiler_slice(c, s, ctx))
5253 return 0;
5254 }
5255 break;
5256 case ExtSlice_kind:
5257 kindname = "extended slice";
5258 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005259 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005260 for (i = 0; i < n; i++) {
5261 slice_ty sub = (slice_ty)asdl_seq_GET(
5262 s->v.ExtSlice.dims, i);
5263 if (!compiler_visit_nested_slice(c, sub, ctx))
5264 return 0;
5265 }
5266 ADDOP_I(c, BUILD_TUPLE, n);
5267 }
5268 break;
5269 default:
5270 PyErr_Format(PyExc_SystemError,
5271 "invalid subscript kind %d", s->kind);
5272 return 0;
5273 }
5274 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005275}
5276
Thomas Wouters89f507f2006-12-13 04:49:30 +00005277/* End of the compiler section, beginning of the assembler section */
5278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279/* do depth-first search of basic block graph, starting with block.
5280 post records the block indices in post-order.
5281
5282 XXX must handle implicit jumps from one block to next
5283*/
5284
Thomas Wouters89f507f2006-12-13 04:49:30 +00005285struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 PyObject *a_bytecode; /* string containing bytecode */
5287 int a_offset; /* offset into bytecode */
5288 int a_nblocks; /* number of reachable blocks */
5289 basicblock **a_postorder; /* list of blocks in dfs postorder */
5290 PyObject *a_lnotab; /* string containing lnotab */
5291 int a_lnotab_off; /* offset into lnotab */
5292 int a_lineno; /* last lineno of emitted instruction */
5293 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005294};
5295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005296static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005297dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005298{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005299 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005300
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005301 /* Get rid of recursion for normal control flow.
5302 Since the number of blocks is limited, unused space in a_postorder
5303 (from a_nblocks to end) can be used as a stack for still not ordered
5304 blocks. */
5305 for (j = end; b && !b->b_seen; b = b->b_next) {
5306 b->b_seen = 1;
5307 assert(a->a_nblocks < j);
5308 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005310 while (j < end) {
5311 b = a->a_postorder[j++];
5312 for (i = 0; i < b->b_iused; i++) {
5313 struct instr *instr = &b->b_instr[i];
5314 if (instr->i_jrel || instr->i_jabs)
5315 dfs(c, instr->i_target, a, j);
5316 }
5317 assert(a->a_nblocks < j);
5318 a->a_postorder[a->a_nblocks++] = b;
5319 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005320}
5321
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005322Py_LOCAL_INLINE(void)
5323stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005325 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005326 if (b->b_startdepth < depth) {
5327 assert(b->b_startdepth < 0);
5328 b->b_startdepth = depth;
5329 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005331}
5332
5333/* Find the flow path that needs the largest stack. We assume that
5334 * cycles in the flow graph have no net effect on the stack depth.
5335 */
5336static int
5337stackdepth(struct compiler *c)
5338{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005339 basicblock *b, *entryblock = NULL;
5340 basicblock **stack, **sp;
5341 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 b->b_startdepth = INT_MIN;
5344 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005345 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 }
5347 if (!entryblock)
5348 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005349 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5350 if (!stack) {
5351 PyErr_NoMemory();
5352 return -1;
5353 }
5354
5355 sp = stack;
5356 stackdepth_push(&sp, entryblock, 0);
5357 while (sp != stack) {
5358 b = *--sp;
5359 int depth = b->b_startdepth;
5360 assert(depth >= 0);
5361 basicblock *next = b->b_next;
5362 for (int i = 0; i < b->b_iused; i++) {
5363 struct instr *instr = &b->b_instr[i];
5364 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5365 if (effect == PY_INVALID_STACK_EFFECT) {
5366 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5367 Py_FatalError("PyCompile_OpcodeStackEffect()");
5368 }
5369 int new_depth = depth + effect;
5370 if (new_depth > maxdepth) {
5371 maxdepth = new_depth;
5372 }
5373 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5374 if (instr->i_jrel || instr->i_jabs) {
5375 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5376 assert(effect != PY_INVALID_STACK_EFFECT);
5377 int target_depth = depth + effect;
5378 if (target_depth > maxdepth) {
5379 maxdepth = target_depth;
5380 }
5381 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005382 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005383 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005384 assert(instr->i_target->b_startdepth >= target_depth);
5385 depth = new_depth;
5386 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005387 }
5388 stackdepth_push(&sp, instr->i_target, target_depth);
5389 }
5390 depth = new_depth;
5391 if (instr->i_opcode == JUMP_ABSOLUTE ||
5392 instr->i_opcode == JUMP_FORWARD ||
5393 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005394 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005395 {
5396 /* remaining code is dead */
5397 next = NULL;
5398 break;
5399 }
5400 }
5401 if (next != NULL) {
5402 stackdepth_push(&sp, next, depth);
5403 }
5404 }
5405 PyObject_Free(stack);
5406 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005407}
5408
5409static int
5410assemble_init(struct assembler *a, int nblocks, int firstlineno)
5411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 memset(a, 0, sizeof(struct assembler));
5413 a->a_lineno = firstlineno;
5414 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5415 if (!a->a_bytecode)
5416 return 0;
5417 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5418 if (!a->a_lnotab)
5419 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005420 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 PyErr_NoMemory();
5422 return 0;
5423 }
5424 a->a_postorder = (basicblock **)PyObject_Malloc(
5425 sizeof(basicblock *) * nblocks);
5426 if (!a->a_postorder) {
5427 PyErr_NoMemory();
5428 return 0;
5429 }
5430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431}
5432
5433static void
5434assemble_free(struct assembler *a)
5435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 Py_XDECREF(a->a_bytecode);
5437 Py_XDECREF(a->a_lnotab);
5438 if (a->a_postorder)
5439 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005440}
5441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005442static int
5443blocksize(basicblock *b)
5444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 int i;
5446 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005449 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451}
5452
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005453/* Appends a pair to the end of the line number table, a_lnotab, representing
5454 the instruction's bytecode offset and line number. See
5455 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005456
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005457static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005460 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005461 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005463
Serhiy Storchakaab874002016-09-11 13:48:15 +03005464 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 if(d_bytecode == 0 && d_lineno == 0)
5470 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005472 if (d_bytecode > 255) {
5473 int j, nbytes, ncodes = d_bytecode / 255;
5474 nbytes = a->a_lnotab_off + 2 * ncodes;
5475 len = PyBytes_GET_SIZE(a->a_lnotab);
5476 if (nbytes >= len) {
5477 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5478 len = nbytes;
5479 else if (len <= INT_MAX / 2)
5480 len *= 2;
5481 else {
5482 PyErr_NoMemory();
5483 return 0;
5484 }
5485 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5486 return 0;
5487 }
5488 lnotab = (unsigned char *)
5489 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5490 for (j = 0; j < ncodes; j++) {
5491 *lnotab++ = 255;
5492 *lnotab++ = 0;
5493 }
5494 d_bytecode -= ncodes * 255;
5495 a->a_lnotab_off += ncodes * 2;
5496 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005497 assert(0 <= d_bytecode && d_bytecode <= 255);
5498
5499 if (d_lineno < -128 || 127 < d_lineno) {
5500 int j, nbytes, ncodes, k;
5501 if (d_lineno < 0) {
5502 k = -128;
5503 /* use division on positive numbers */
5504 ncodes = (-d_lineno) / 128;
5505 }
5506 else {
5507 k = 127;
5508 ncodes = d_lineno / 127;
5509 }
5510 d_lineno -= ncodes * k;
5511 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 nbytes = a->a_lnotab_off + 2 * ncodes;
5513 len = PyBytes_GET_SIZE(a->a_lnotab);
5514 if (nbytes >= len) {
5515 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5516 len = nbytes;
5517 else if (len <= INT_MAX / 2)
5518 len *= 2;
5519 else {
5520 PyErr_NoMemory();
5521 return 0;
5522 }
5523 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5524 return 0;
5525 }
5526 lnotab = (unsigned char *)
5527 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5528 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005529 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 d_bytecode = 0;
5531 for (j = 1; j < ncodes; j++) {
5532 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005533 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 a->a_lnotab_off += ncodes * 2;
5536 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005537 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 len = PyBytes_GET_SIZE(a->a_lnotab);
5540 if (a->a_lnotab_off + 2 >= len) {
5541 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5542 return 0;
5543 }
5544 lnotab = (unsigned char *)
5545 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 a->a_lnotab_off += 2;
5548 if (d_bytecode) {
5549 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005550 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 }
5552 else { /* First line of a block; def stmt, etc. */
5553 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005554 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 }
5556 a->a_lineno = i->i_lineno;
5557 a->a_lineno_off = a->a_offset;
5558 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005559}
5560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005561/* assemble_emit()
5562 Extend the bytecode with a new instruction.
5563 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005564*/
5565
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005566static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005567assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005568{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005569 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005571 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005572
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005573 arg = i->i_oparg;
5574 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 if (i->i_lineno && !assemble_lnotab(a, i))
5576 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005577 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 if (len > PY_SSIZE_T_MAX / 2)
5579 return 0;
5580 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5581 return 0;
5582 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005583 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005585 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005586 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005587}
5588
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005589static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005590assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005593 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 /* Compute the size of each block and fixup jump args.
5597 Replace block pointer with position in bytecode. */
5598 do {
5599 totsize = 0;
5600 for (i = a->a_nblocks - 1; i >= 0; i--) {
5601 b = a->a_postorder[i];
5602 bsize = blocksize(b);
5603 b->b_offset = totsize;
5604 totsize += bsize;
5605 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005606 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005607 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5608 bsize = b->b_offset;
5609 for (i = 0; i < b->b_iused; i++) {
5610 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005611 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 /* Relative jumps are computed relative to
5613 the instruction pointer after fetching
5614 the jump instruction.
5615 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005616 bsize += isize;
5617 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005619 if (instr->i_jrel) {
5620 instr->i_oparg -= bsize;
5621 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005622 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005623 if (instrsize(instr->i_oparg) != isize) {
5624 extended_arg_recompile = 1;
5625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 }
5628 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005630 /* XXX: This is an awful hack that could hurt performance, but
5631 on the bright side it should work until we come up
5632 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 The issue is that in the first loop blocksize() is called
5635 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005636 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 So we loop until we stop seeing new EXTENDED_ARGs.
5640 The only EXTENDED_ARGs that could be popping up are
5641 ones in jump instructions. So this should converge
5642 fairly quickly.
5643 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005644 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005645}
5646
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005647static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005648dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005651 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 tuple = PyTuple_New(size);
5654 if (tuple == NULL)
5655 return NULL;
5656 while (PyDict_Next(dict, &pos, &k, &v)) {
5657 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005658 Py_INCREF(k);
5659 assert((i - offset) < size);
5660 assert((i - offset) >= 0);
5661 PyTuple_SET_ITEM(tuple, i - offset, k);
5662 }
5663 return tuple;
5664}
5665
5666static PyObject *
5667consts_dict_keys_inorder(PyObject *dict)
5668{
5669 PyObject *consts, *k, *v;
5670 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5671
5672 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5673 if (consts == NULL)
5674 return NULL;
5675 while (PyDict_Next(dict, &pos, &k, &v)) {
5676 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005677 /* The keys of the dictionary can be tuples wrapping a contant.
5678 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5679 * the object we want is always second. */
5680 if (PyTuple_CheckExact(k)) {
5681 k = PyTuple_GET_ITEM(k, 1);
5682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005684 assert(i < size);
5685 assert(i >= 0);
5686 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005687 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005688 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005689}
5690
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005692compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005695 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005697 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 if (ste->ste_nested)
5699 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005700 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005702 if (!ste->ste_generator && ste->ste_coroutine)
5703 flags |= CO_COROUTINE;
5704 if (ste->ste_generator && ste->ste_coroutine)
5705 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 if (ste->ste_varargs)
5707 flags |= CO_VARARGS;
5708 if (ste->ste_varkeywords)
5709 flags |= CO_VARKEYWORDS;
5710 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 /* (Only) inherit compilerflags in PyCF_MASK */
5713 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005716}
5717
INADA Naokic2e16072018-11-26 21:23:22 +09005718// Merge *tuple* with constant cache.
5719// Unlike merge_consts_recursive(), this function doesn't work recursively.
5720static int
5721merge_const_tuple(struct compiler *c, PyObject **tuple)
5722{
5723 assert(PyTuple_CheckExact(*tuple));
5724
5725 PyObject *key = _PyCode_ConstantKey(*tuple);
5726 if (key == NULL) {
5727 return 0;
5728 }
5729
5730 // t is borrowed reference
5731 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5732 Py_DECREF(key);
5733 if (t == NULL) {
5734 return 0;
5735 }
5736 if (t == key) { // tuple is new constant.
5737 return 1;
5738 }
5739
5740 PyObject *u = PyTuple_GET_ITEM(t, 1);
5741 Py_INCREF(u);
5742 Py_DECREF(*tuple);
5743 *tuple = u;
5744 return 1;
5745}
5746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005747static PyCodeObject *
5748makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 PyObject *tmp;
5751 PyCodeObject *co = NULL;
5752 PyObject *consts = NULL;
5753 PyObject *names = NULL;
5754 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 PyObject *name = NULL;
5756 PyObject *freevars = NULL;
5757 PyObject *cellvars = NULL;
5758 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005759 Py_ssize_t nlocals;
5760 int nlocals_int;
5761 int flags;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005762 int argcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005763
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005764 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 names = dict_keys_inorder(c->u->u_names, 0);
5766 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5767 if (!consts || !names || !varnames)
5768 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5771 if (!cellvars)
5772 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005773 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 if (!freevars)
5775 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005776
INADA Naokic2e16072018-11-26 21:23:22 +09005777 if (!merge_const_tuple(c, &names) ||
5778 !merge_const_tuple(c, &varnames) ||
5779 !merge_const_tuple(c, &cellvars) ||
5780 !merge_const_tuple(c, &freevars))
5781 {
5782 goto error;
5783 }
5784
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005785 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005786 assert(nlocals < INT_MAX);
5787 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 flags = compute_code_flags(c);
5790 if (flags < 0)
5791 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5794 if (!bytecode)
5795 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5798 if (!tmp)
5799 goto error;
5800 Py_DECREF(consts);
5801 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005802 if (!merge_const_tuple(c, &consts)) {
5803 goto error;
5804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805
Victor Stinnerf8e32212013-11-19 23:56:34 +01005806 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005807 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005808 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005809 maxdepth = stackdepth(c);
5810 if (maxdepth < 0) {
5811 goto error;
5812 }
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005813 co = PyCode_New(argcount, posonlyargcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005814 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 bytecode, consts, names, varnames,
5816 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005817 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 c->u->u_firstlineno,
5819 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005820 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 Py_XDECREF(consts);
5822 Py_XDECREF(names);
5823 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 Py_XDECREF(name);
5825 Py_XDECREF(freevars);
5826 Py_XDECREF(cellvars);
5827 Py_XDECREF(bytecode);
5828 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005829}
5830
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005831
5832/* For debugging purposes only */
5833#if 0
5834static void
5835dump_instr(const struct instr *i)
5836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 const char *jrel = i->i_jrel ? "jrel " : "";
5838 const char *jabs = i->i_jabs ? "jabs " : "";
5839 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005842 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5846 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005847}
5848
5849static void
5850dump_basicblock(const basicblock *b)
5851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 const char *seen = b->b_seen ? "seen " : "";
5853 const char *b_return = b->b_return ? "return " : "";
5854 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5855 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5856 if (b->b_instr) {
5857 int i;
5858 for (i = 0; i < b->b_iused; i++) {
5859 fprintf(stderr, " [%02d] ", i);
5860 dump_instr(b->b_instr + i);
5861 }
5862 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005863}
5864#endif
5865
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005866static PyCodeObject *
5867assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005869 basicblock *b, *entryblock;
5870 struct assembler a;
5871 int i, j, nblocks;
5872 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 /* Make sure every block that falls off the end returns None.
5875 XXX NEXT_BLOCK() isn't quite right, because if the last
5876 block ends with a jump or return b_next shouldn't set.
5877 */
5878 if (!c->u->u_curblock->b_return) {
5879 NEXT_BLOCK(c);
5880 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005881 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005882 ADDOP(c, RETURN_VALUE);
5883 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 nblocks = 0;
5886 entryblock = NULL;
5887 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5888 nblocks++;
5889 entryblock = b;
5890 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 /* Set firstlineno if it wasn't explicitly set. */
5893 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005894 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5896 else
5897 c->u->u_firstlineno = 1;
5898 }
5899 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5900 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005901 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 /* Can't modify the bytecode after computing jump offsets. */
5904 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 /* Emit code in reverse postorder from dfs. */
5907 for (i = a.a_nblocks - 1; i >= 0; i--) {
5908 b = a.a_postorder[i];
5909 for (j = 0; j < b->b_iused; j++)
5910 if (!assemble_emit(&a, &b->b_instr[j]))
5911 goto error;
5912 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5915 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005916 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005920 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005921 assemble_free(&a);
5922 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005923}
Georg Brandl8334fd92010-12-04 10:26:46 +00005924
5925#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005926PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005927PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5928 PyArena *arena)
5929{
5930 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5931}