blob: ecf7d357c856459f60bde9b73b4320f146e63525 [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 */
125 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 /* Pointer to the most recently allocated block. By following b_list
127 members, you can reach all early allocated blocks. */
128 basicblock *u_blocks;
129 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int u_nfblocks;
132 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 int u_firstlineno; /* the first lineno of the block */
135 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000136 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 int u_lineno_set; /* boolean to indicate whether instr
138 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139};
140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000146
147Note that we don't track recursion levels during compilation - the
148task of detecting and rejecting excessive levels of nesting is
149handled by the symbol analysis pass.
150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151*/
152
153struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200154 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 struct symtable *c_st;
156 PyFutureFeatures *c_future; /* pointer to module's __future__ */
157 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Georg Brandl8334fd92010-12-04 10:26:46 +0000159 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 int c_interactive; /* true if in interactive mode */
161 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000162
INADA Naokic2e16072018-11-26 21:23:22 +0900163 PyObject *c_const_cache; /* Python dict holding all constants,
164 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 struct compiler_unit *u; /* compiler state for current block */
166 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
167 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168};
169
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100170static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static void compiler_free(struct compiler *);
172static basicblock *compiler_new_block(struct compiler *);
173static int compiler_next_instr(struct compiler *, basicblock *);
174static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100175static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200178static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
180
181static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
182static int compiler_visit_stmt(struct compiler *, stmt_ty);
183static int compiler_visit_keyword(struct compiler *, keyword_ty);
184static int compiler_visit_expr(struct compiler *, expr_ty);
185static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700186static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190static int inplace_binop(struct compiler *, operator_ty);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200191static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500193static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400194static int compiler_async_with(struct compiler *, stmt_ty, int);
195static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100196static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400198 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500199static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400200static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000201
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700202static int compiler_sync_comprehension_generator(
203 struct compiler *c,
204 asdl_seq *generators, int gen_index,
205 expr_ty elt, expr_ty val, int type);
206
207static int compiler_async_comprehension_generator(
208 struct compiler *c,
209 asdl_seq *generators, int gen_index,
210 expr_ty elt, expr_ty val, int type);
211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000213static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400215#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000217PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Name mangling: __private becomes _classname__private.
221 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200222 PyObject *result;
223 size_t nlen, plen, ipriv;
224 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200226 PyUnicode_READ_CHAR(ident, 0) != '_' ||
227 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_INCREF(ident);
229 return ident;
230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200231 nlen = PyUnicode_GET_LENGTH(ident);
232 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 The only time a name with a dot can occur is when
236 we are compiling an import statement that has a
237 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 TODO(jhylton): Decide whether we want to support
240 mangling of the module name, e.g. __M.X.
241 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200242 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
243 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
244 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle __whatever__ */
247 }
248 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200249 ipriv = 0;
250 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
251 ipriv++;
252 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_INCREF(ident);
254 return ident; /* Don't mangle if class is just underscores */
255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Antoine Pitrou55bff892013-04-06 21:21:04 +0200258 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
259 PyErr_SetString(PyExc_OverflowError,
260 "private identifier too large to be mangled");
261 return NULL;
262 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
265 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
266 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
267
268 result = PyUnicode_New(1 + nlen + plen, maxchar);
269 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
272 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200273 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
274 Py_DECREF(result);
275 return NULL;
276 }
277 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
278 Py_DECREF(result);
279 return NULL;
280 }
Victor Stinner8f825062012-04-27 13:55:39 +0200281 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200282 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000283}
284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285static int
286compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000289
INADA Naokic2e16072018-11-26 21:23:22 +0900290 c->c_const_cache = PyDict_New();
291 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900293 }
294
295 c->c_stack = PyList_New(0);
296 if (!c->c_stack) {
297 Py_CLEAR(c->c_const_cache);
298 return 0;
299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302}
303
304PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200305PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
306 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 struct compiler c;
309 PyCodeObject *co = NULL;
310 PyCompilerFlags local_flags;
311 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!__doc__) {
314 __doc__ = PyUnicode_InternFromString("__doc__");
315 if (!__doc__)
316 return NULL;
317 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000318 if (!__annotations__) {
319 __annotations__ = PyUnicode_InternFromString("__annotations__");
320 if (!__annotations__)
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!compiler_init(&c))
324 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 c.c_filename = filename;
327 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200328 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (c.c_future == NULL)
330 goto finally;
331 if (!flags) {
332 local_flags.cf_flags = 0;
Guido van Rossum495da292019-03-07 12:38:08 -0800333 local_flags.cf_feature_version = PY_MINOR_VERSION;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 flags = &local_flags;
335 }
336 merged = c.c_future->ff_features | flags->cf_flags;
337 c.c_future->ff_features = merged;
338 flags->cf_flags = merged;
339 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000340 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200343 if (!_PyAST_Optimize(mod, arena, c.c_optimize)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900344 goto finally;
345 }
346
Victor Stinner14e461d2013-08-26 22:28:21 +0200347 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (c.c_st == NULL) {
349 if (!PyErr_Occurred())
350 PyErr_SetString(PyExc_SystemError, "no symtable");
351 goto finally;
352 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355
Thomas Wouters1175c432006-02-27 22:49:54 +0000356 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 compiler_free(&c);
358 assert(co || PyErr_Occurred());
359 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360}
361
362PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200363PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
364 int optimize, PyArena *arena)
365{
366 PyObject *filename;
367 PyCodeObject *co;
368 filename = PyUnicode_DecodeFSDefault(filename_str);
369 if (filename == NULL)
370 return NULL;
371 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
372 Py_DECREF(filename);
373 return co;
374
375}
376
377PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378PyNode_Compile(struct _node *n, const char *filename)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyCodeObject *co = NULL;
381 mod_ty mod;
382 PyArena *arena = PyArena_New();
383 if (!arena)
384 return NULL;
385 mod = PyAST_FromNode(n, NULL, filename, arena);
386 if (mod)
387 co = PyAST_Compile(mod, filename, NULL, arena);
388 PyArena_Free(arena);
389 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000390}
391
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000392static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (c->c_st)
396 PySymtable_Free(c->c_st);
397 if (c->c_future)
398 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200399 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900400 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000402}
403
Guido van Rossum79f25d91997-04-29 20:08:16 +0000404static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ssize_t i, n;
408 PyObject *v, *k;
409 PyObject *dict = PyDict_New();
410 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 n = PyList_Size(list);
413 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100414 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (!v) {
416 Py_DECREF(dict);
417 return NULL;
418 }
419 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300420 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 Py_DECREF(v);
422 Py_DECREF(dict);
423 return NULL;
424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_DECREF(v);
426 }
427 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428}
429
430/* Return new dict containing names from src that match scope(s).
431
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000432src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000434values are integers, starting at offset and increasing by one for
435each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436*/
437
438static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100439dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000440{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700441 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500443 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 assert(offset >= 0);
446 if (dest == NULL)
447 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448
Meador Inge2ca63152012-07-18 14:20:11 -0500449 /* Sort the keys so that we have a deterministic order on the indexes
450 saved in the returned dictionary. These indexes are used as indexes
451 into the free and cell var storage. Therefore if they aren't
452 deterministic, then the generated bytecode is not deterministic.
453 */
454 sorted_keys = PyDict_Keys(src);
455 if (sorted_keys == NULL)
456 return NULL;
457 if (PyList_Sort(sorted_keys) != 0) {
458 Py_DECREF(sorted_keys);
459 return NULL;
460 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500461 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500462
463 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* XXX this should probably be a macro in symtable.h */
465 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500466 k = PyList_GET_ITEM(sorted_keys, key_i);
467 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 assert(PyLong_Check(v));
469 vi = PyLong_AS_LONG(v);
470 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300473 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500475 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_DECREF(dest);
477 return NULL;
478 }
479 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300480 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_DECREF(item);
483 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return NULL;
485 }
486 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 }
488 }
Meador Inge2ca63152012-07-18 14:20:11 -0500489 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000491}
492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493static void
494compiler_unit_check(struct compiler_unit *u)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 basicblock *block;
497 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700498 assert((uintptr_t)block != 0xcbcbcbcbU);
499 assert((uintptr_t)block != 0xfbfbfbfbU);
500 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (block->b_instr != NULL) {
502 assert(block->b_ialloc > 0);
503 assert(block->b_iused > 0);
504 assert(block->b_ialloc >= block->b_iused);
505 }
506 else {
507 assert (block->b_iused == 0);
508 assert (block->b_ialloc == 0);
509 }
510 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511}
512
513static void
514compiler_unit_free(struct compiler_unit *u)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 compiler_unit_check(u);
519 b = u->u_blocks;
520 while (b != NULL) {
521 if (b->b_instr)
522 PyObject_Free((void *)b->b_instr);
523 next = b->b_list;
524 PyObject_Free((void *)b);
525 b = next;
526 }
527 Py_CLEAR(u->u_ste);
528 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400529 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_CLEAR(u->u_consts);
531 Py_CLEAR(u->u_names);
532 Py_CLEAR(u->u_varnames);
533 Py_CLEAR(u->u_freevars);
534 Py_CLEAR(u->u_cellvars);
535 Py_CLEAR(u->u_private);
536 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537}
538
539static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100540compiler_enter_scope(struct compiler *c, identifier name,
541 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100544 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
547 struct compiler_unit));
548 if (!u) {
549 PyErr_NoMemory();
550 return 0;
551 }
552 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100553 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 u->u_argcount = 0;
555 u->u_kwonlyargcount = 0;
556 u->u_ste = PySymtable_Lookup(c->c_st, key);
557 if (!u->u_ste) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 Py_INCREF(name);
562 u->u_name = name;
563 u->u_varnames = list2dict(u->u_ste->ste_varnames);
564 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
565 if (!u->u_varnames || !u->u_cellvars) {
566 compiler_unit_free(u);
567 return 0;
568 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500569 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000570 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500571 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300572 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500573 int res;
574 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200575 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500576 name = _PyUnicode_FromId(&PyId___class__);
577 if (!name) {
578 compiler_unit_free(u);
579 return 0;
580 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300581 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_Zero);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500582 if (res < 0) {
583 compiler_unit_free(u);
584 return 0;
585 }
586 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200589 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (!u->u_freevars) {
591 compiler_unit_free(u);
592 return 0;
593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_blocks = NULL;
596 u->u_nfblocks = 0;
597 u->u_firstlineno = lineno;
598 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000599 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_lineno_set = 0;
601 u->u_consts = PyDict_New();
602 if (!u->u_consts) {
603 compiler_unit_free(u);
604 return 0;
605 }
606 u->u_names = PyDict_New();
607 if (!u->u_names) {
608 compiler_unit_free(u);
609 return 0;
610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Push the old compiler_unit on the stack. */
615 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400616 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
618 Py_XDECREF(capsule);
619 compiler_unit_free(u);
620 return 0;
621 }
622 Py_DECREF(capsule);
623 u->u_private = c->u->u_private;
624 Py_XINCREF(u->u_private);
625 }
626 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100629
630 block = compiler_new_block(c);
631 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100633 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400635 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
636 if (!compiler_set_qualname(c))
637 return 0;
638 }
639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641}
642
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000643static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000644compiler_exit_scope(struct compiler *c)
645{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100646 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 c->c_nestlevel--;
650 compiler_unit_free(c->u);
651 /* Restore c->u to the parent unit. */
652 n = PyList_GET_SIZE(c->c_stack) - 1;
653 if (n >= 0) {
654 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400655 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 assert(c->u);
657 /* we are deleting from a list so this really shouldn't fail */
658 if (PySequence_DelItem(c->c_stack, n) < 0)
659 Py_FatalError("compiler_exit_scope()");
660 compiler_unit_check(c->u);
661 }
662 else
663 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665}
666
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400667static int
668compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100670 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 _Py_static_string(dot_locals, ".<locals>");
672 Py_ssize_t stack_size;
673 struct compiler_unit *u = c->u;
674 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100677 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400678 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400679 if (stack_size > 1) {
680 int scope, force_global = 0;
681 struct compiler_unit *parent;
682 PyObject *mangled, *capsule;
683
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400684 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400685 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400686 assert(parent);
687
Yury Selivanov75445082015-05-11 22:57:16 -0400688 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
689 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
690 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 assert(u->u_name);
692 mangled = _Py_Mangle(parent->u_private, u->u_name);
693 if (!mangled)
694 return 0;
695 scope = PyST_GetScope(parent->u_ste, mangled);
696 Py_DECREF(mangled);
697 assert(scope != GLOBAL_IMPLICIT);
698 if (scope == GLOBAL_EXPLICIT)
699 force_global = 1;
700 }
701
702 if (!force_global) {
703 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400704 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
706 dot_locals_str = _PyUnicode_FromId(&dot_locals);
707 if (dot_locals_str == NULL)
708 return 0;
709 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
710 if (base == NULL)
711 return 0;
712 }
713 else {
714 Py_INCREF(parent->u_qualname);
715 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400716 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100717 }
718 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400719
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 if (base != NULL) {
721 dot_str = _PyUnicode_FromId(&dot);
722 if (dot_str == NULL) {
723 Py_DECREF(base);
724 return 0;
725 }
726 name = PyUnicode_Concat(base, dot_str);
727 Py_DECREF(base);
728 if (name == NULL)
729 return 0;
730 PyUnicode_Append(&name, u->u_name);
731 if (name == NULL)
732 return 0;
733 }
734 else {
735 Py_INCREF(u->u_name);
736 name = u->u_name;
737 }
738 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100739
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400740 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741}
742
Eric V. Smith235a6f02015-09-19 14:51:32 -0400743
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000744/* Allocate a new block and return a pointer to it.
745 Returns NULL on error.
746*/
747
748static basicblock *
749compiler_new_block(struct compiler *c)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 basicblock *b;
752 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 u = c->u;
755 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
756 if (b == NULL) {
757 PyErr_NoMemory();
758 return NULL;
759 }
760 memset((void *)b, 0, sizeof(basicblock));
761 /* Extend the singly linked list of blocks with new block. */
762 b->b_list = u->u_blocks;
763 u->u_blocks = b;
764 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765}
766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768compiler_next_block(struct compiler *c)
769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 basicblock *block = compiler_new_block(c);
771 if (block == NULL)
772 return NULL;
773 c->u->u_curblock->b_next = block;
774 c->u->u_curblock = block;
775 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776}
777
778static basicblock *
779compiler_use_next_block(struct compiler *c, basicblock *block)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 assert(block != NULL);
782 c->u->u_curblock->b_next = block;
783 c->u->u_curblock = block;
784 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785}
786
787/* Returns the offset of the next instruction in the current block's
788 b_instr array. Resizes the b_instr as necessary.
789 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000790*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791
792static int
793compiler_next_instr(struct compiler *c, basicblock *b)
794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(b != NULL);
796 if (b->b_instr == NULL) {
797 b->b_instr = (struct instr *)PyObject_Malloc(
798 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
799 if (b->b_instr == NULL) {
800 PyErr_NoMemory();
801 return -1;
802 }
803 b->b_ialloc = DEFAULT_BLOCK_SIZE;
804 memset((char *)b->b_instr, 0,
805 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
806 }
807 else if (b->b_iused == b->b_ialloc) {
808 struct instr *tmp;
809 size_t oldsize, newsize;
810 oldsize = b->b_ialloc * sizeof(struct instr);
811 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000812
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700813 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyErr_NoMemory();
815 return -1;
816 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (newsize == 0) {
819 PyErr_NoMemory();
820 return -1;
821 }
822 b->b_ialloc <<= 1;
823 tmp = (struct instr *)PyObject_Realloc(
824 (void *)b->b_instr, newsize);
825 if (tmp == NULL) {
826 PyErr_NoMemory();
827 return -1;
828 }
829 b->b_instr = tmp;
830 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
831 }
832 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833}
834
Christian Heimes2202f872008-02-06 14:31:34 +0000835/* Set the i_lineno member of the instruction at offset off if the
836 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 already been set. If it has been set, the call has no effect.
838
Christian Heimes2202f872008-02-06 14:31:34 +0000839 The line number is reset in the following cases:
840 - when entering a new scope
841 - on each statement
842 - on each expression that start a new line
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200843 - before the "except" and "finally" clauses
Christian Heimes2202f872008-02-06 14:31:34 +0000844 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847static void
848compiler_set_lineno(struct compiler *c, int off)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 basicblock *b;
851 if (c->u->u_lineno_set)
852 return;
853 c->u->u_lineno_set = 1;
854 b = c->u->u_curblock;
855 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856}
857
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200858/* Return the stack effect of opcode with argument oparg.
859
860 Some opcodes have different stack effect when jump to the target and
861 when not jump. The 'jump' parameter specifies the case:
862
863 * 0 -- when not jump
864 * 1 -- when jump
865 * -1 -- maximal
866 */
867/* XXX Make the stack effect of WITH_CLEANUP_START and
868 WITH_CLEANUP_FINISH deterministic. */
869static int
870stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300873 case NOP:
874 case EXTENDED_ARG:
875 return 0;
876
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200877 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 case POP_TOP:
879 return -1;
880 case ROT_TWO:
881 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200882 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return 0;
884 case DUP_TOP:
885 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000886 case DUP_TOP_TWO:
887 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200889 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 case UNARY_POSITIVE:
891 case UNARY_NEGATIVE:
892 case UNARY_NOT:
893 case UNARY_INVERT:
894 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 case SET_ADD:
897 case LIST_APPEND:
898 return -1;
899 case MAP_ADD:
900 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000901
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200902 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case BINARY_POWER:
904 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400905 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case BINARY_MODULO:
907 case BINARY_ADD:
908 case BINARY_SUBTRACT:
909 case BINARY_SUBSCR:
910 case BINARY_FLOOR_DIVIDE:
911 case BINARY_TRUE_DIVIDE:
912 return -1;
913 case INPLACE_FLOOR_DIVIDE:
914 case INPLACE_TRUE_DIVIDE:
915 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 case INPLACE_ADD:
918 case INPLACE_SUBTRACT:
919 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400920 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case INPLACE_MODULO:
922 return -1;
923 case STORE_SUBSCR:
924 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case DELETE_SUBSCR:
926 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case BINARY_LSHIFT:
929 case BINARY_RSHIFT:
930 case BINARY_AND:
931 case BINARY_XOR:
932 case BINARY_OR:
933 return -1;
934 case INPLACE_POWER:
935 return -1;
936 case GET_ITER:
937 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case PRINT_EXPR:
940 return -1;
941 case LOAD_BUILD_CLASS:
942 return 1;
943 case INPLACE_LSHIFT:
944 case INPLACE_RSHIFT:
945 case INPLACE_AND:
946 case INPLACE_XOR:
947 case INPLACE_OR:
948 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200951 /* 1 in the normal flow.
952 * Restore the stack position and push 6 values before jumping to
953 * the handler if an exception be raised. */
954 return jump ? 6 : 1;
Yury Selivanov75445082015-05-11 22:57:16 -0400955 case WITH_CLEANUP_START:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200956 return 2; /* or 1, depending on TOS */
Yury Selivanov75445082015-05-11 22:57:16 -0400957 case WITH_CLEANUP_FINISH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200958 /* Pop a variable number of values pushed by WITH_CLEANUP_START
959 * + __exit__ or __aexit__. */
960 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case RETURN_VALUE:
962 return -1;
963 case IMPORT_STAR:
964 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700965 case SETUP_ANNOTATIONS:
966 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 case YIELD_VALUE:
968 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500969 case YIELD_FROM:
970 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case POP_BLOCK:
972 return 0;
973 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200974 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200976 case POP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200977 /* Pop 6 values when an exception was raised. */
978 return -6;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 case STORE_NAME:
981 return -1;
982 case DELETE_NAME:
983 return 0;
984 case UNPACK_SEQUENCE:
985 return oparg-1;
986 case UNPACK_EX:
987 return (oparg&0xFF) + (oparg>>8);
988 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* -1 at end of iterator, 1 if continue iterating. */
990 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case STORE_ATTR:
993 return -2;
994 case DELETE_ATTR:
995 return -1;
996 case STORE_GLOBAL:
997 return -1;
998 case DELETE_GLOBAL:
999 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case LOAD_CONST:
1001 return 1;
1002 case LOAD_NAME:
1003 return 1;
1004 case BUILD_TUPLE:
1005 case BUILD_LIST:
1006 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001007 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001009 case BUILD_LIST_UNPACK:
1010 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +03001011 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001012 case BUILD_SET_UNPACK:
1013 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04001014 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001015 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001017 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001018 case BUILD_CONST_KEY_MAP:
1019 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case LOAD_ATTR:
1021 return 0;
1022 case COMPARE_OP:
1023 return -1;
1024 case IMPORT_NAME:
1025 return -1;
1026 case IMPORT_FROM:
1027 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001029 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case JUMP_ABSOLUTE:
1032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001034 case JUMP_IF_TRUE_OR_POP:
1035 case JUMP_IF_FALSE_OR_POP:
1036 return jump ? 0 : -1;
1037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 case POP_JUMP_IF_FALSE:
1039 case POP_JUMP_IF_TRUE:
1040 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case LOAD_GLOBAL:
1043 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001044
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001045 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001047 /* 0 in the normal flow.
1048 * Restore the stack position and push 6 values before jumping to
1049 * the handler if an exception be raised. */
1050 return jump ? 6 : 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001051 case BEGIN_FINALLY:
1052 /* Actually pushes 1 value, but count 6 for balancing with
1053 * END_FINALLY and POP_FINALLY.
1054 * This is the main reason of using this opcode instead of
1055 * "LOAD_CONST None". */
1056 return 6;
1057 case CALL_FINALLY:
1058 return jump ? 1 : 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_FAST:
1061 return 1;
1062 case STORE_FAST:
1063 return -1;
1064 case DELETE_FAST:
1065 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case RAISE_VARARGS:
1068 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001069
1070 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001072 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001073 case CALL_METHOD:
1074 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001076 return -oparg-1;
1077 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001078 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001079 case MAKE_FUNCTION:
1080 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1081 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case BUILD_SLICE:
1083 if (oparg == 3)
1084 return -2;
1085 else
1086 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case LOAD_CLOSURE:
1090 return 1;
1091 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001092 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 return 1;
1094 case STORE_DEREF:
1095 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001096 case DELETE_DEREF:
1097 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098
1099 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001100 case GET_AWAITABLE:
1101 return 0;
1102 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 /* 0 in the normal flow.
1104 * Restore the stack position to the position before the result
1105 * of __aenter__ and push 6 values before jumping to the handler
1106 * if an exception be raised. */
1107 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case BEFORE_ASYNC_WITH:
1109 return 1;
1110 case GET_AITER:
1111 return 0;
1112 case GET_ANEXT:
1113 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001114 case GET_YIELD_FROM_ITER:
1115 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001116 case END_ASYNC_FOR:
1117 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001118 case FORMAT_VALUE:
1119 /* If there's a fmt_spec on the stack, we go from 2->1,
1120 else 1->1. */
1121 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001122 case LOAD_METHOD:
1123 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001125 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
Larry Hastings3a907972013-11-23 14:49:22 -08001127 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128}
1129
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001130int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001131PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1132{
1133 return stack_effect(opcode, oparg, jump);
1134}
1135
1136int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001137PyCompile_OpcodeStackEffect(int opcode, int oparg)
1138{
1139 return stack_effect(opcode, oparg, -1);
1140}
1141
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142/* Add an opcode with no argument.
1143 Returns 0 on failure, 1 on success.
1144*/
1145
1146static int
1147compiler_addop(struct compiler *c, int opcode)
1148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 basicblock *b;
1150 struct instr *i;
1151 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001152 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 off = compiler_next_instr(c, c->u->u_curblock);
1154 if (off < 0)
1155 return 0;
1156 b = c->u->u_curblock;
1157 i = &b->b_instr[off];
1158 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001159 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (opcode == RETURN_VALUE)
1161 b->b_return = 1;
1162 compiler_set_lineno(c, off);
1163 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Victor Stinnerf8e32212013-11-19 23:56:34 +01001166static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1168{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001169 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001172 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001174 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001176 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001177 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001178 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return -1;
1181 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001182 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(v);
1184 return -1;
1185 }
1186 Py_DECREF(v);
1187 }
1188 else
1189 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001190 return arg;
1191}
1192
INADA Naokic2e16072018-11-26 21:23:22 +09001193// Merge const *o* recursively and return constant key object.
1194static PyObject*
1195merge_consts_recursive(struct compiler *c, PyObject *o)
1196{
1197 // None and Ellipsis are singleton, and key is the singleton.
1198 // No need to merge object and key.
1199 if (o == Py_None || o == Py_Ellipsis) {
1200 Py_INCREF(o);
1201 return o;
1202 }
1203
1204 PyObject *key = _PyCode_ConstantKey(o);
1205 if (key == NULL) {
1206 return NULL;
1207 }
1208
1209 // t is borrowed reference
1210 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1211 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001212 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001213 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001214 Py_DECREF(key);
1215 return t;
1216 }
1217
INADA Naokif7e4d362018-11-29 00:58:46 +09001218 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001219 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001220 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001221 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001222 Py_ssize_t len = PyTuple_GET_SIZE(o);
1223 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001224 PyObject *item = PyTuple_GET_ITEM(o, i);
1225 PyObject *u = merge_consts_recursive(c, item);
1226 if (u == NULL) {
1227 Py_DECREF(key);
1228 return NULL;
1229 }
1230
1231 // See _PyCode_ConstantKey()
1232 PyObject *v; // borrowed
1233 if (PyTuple_CheckExact(u)) {
1234 v = PyTuple_GET_ITEM(u, 1);
1235 }
1236 else {
1237 v = u;
1238 }
1239 if (v != item) {
1240 Py_INCREF(v);
1241 PyTuple_SET_ITEM(o, i, v);
1242 Py_DECREF(item);
1243 }
1244
1245 Py_DECREF(u);
1246 }
1247 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001248 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001249 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001250 // constant keys.
1251 // See _PyCode_ConstantKey() for detail.
1252 assert(PyTuple_CheckExact(key));
1253 assert(PyTuple_GET_SIZE(key) == 2);
1254
1255 Py_ssize_t len = PySet_GET_SIZE(o);
1256 if (len == 0) { // empty frozenset should not be re-created.
1257 return key;
1258 }
1259 PyObject *tuple = PyTuple_New(len);
1260 if (tuple == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264 Py_ssize_t i = 0, pos = 0;
1265 PyObject *item;
1266 Py_hash_t hash;
1267 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1268 PyObject *k = merge_consts_recursive(c, item);
1269 if (k == NULL) {
1270 Py_DECREF(tuple);
1271 Py_DECREF(key);
1272 return NULL;
1273 }
1274 PyObject *u;
1275 if (PyTuple_CheckExact(k)) {
1276 u = PyTuple_GET_ITEM(k, 1);
1277 Py_INCREF(u);
1278 Py_DECREF(k);
1279 }
1280 else {
1281 u = k;
1282 }
1283 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1284 i++;
1285 }
1286
1287 // Instead of rewriting o, we create new frozenset and embed in the
1288 // key tuple. Caller should get merged frozenset from the key tuple.
1289 PyObject *new = PyFrozenSet_New(tuple);
1290 Py_DECREF(tuple);
1291 if (new == NULL) {
1292 Py_DECREF(key);
1293 return NULL;
1294 }
1295 assert(PyTuple_GET_ITEM(key, 1) == o);
1296 Py_DECREF(o);
1297 PyTuple_SET_ITEM(key, 1, new);
1298 }
INADA Naokic2e16072018-11-26 21:23:22 +09001299
1300 return key;
1301}
1302
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001303static Py_ssize_t
1304compiler_add_const(struct compiler *c, PyObject *o)
1305{
INADA Naokic2e16072018-11-26 21:23:22 +09001306 PyObject *key = merge_consts_recursive(c, o);
1307 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001308 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001309 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001310
INADA Naokic2e16072018-11-26 21:23:22 +09001311 Py_ssize_t arg = compiler_add_o(c, c->u->u_consts, key);
1312 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314}
1315
1316static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001317compiler_addop_load_const(struct compiler *c, PyObject *o)
1318{
1319 Py_ssize_t arg = compiler_add_const(c, o);
1320 if (arg < 0)
1321 return 0;
1322 return compiler_addop_i(c, LOAD_CONST, arg);
1323}
1324
1325static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001329 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001331 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 return compiler_addop_i(c, opcode, arg);
1333}
1334
1335static int
1336compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001339 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001340 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1341 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001342 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001343 arg = compiler_add_o(c, dict, mangled);
1344 Py_DECREF(mangled);
1345 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 return compiler_addop_i(c, opcode, arg);
1348}
1349
1350/* Add an opcode with an integer argument.
1351 Returns 0 on failure, 1 on success.
1352*/
1353
1354static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001355compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 struct instr *i;
1358 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001359
Victor Stinner2ad474b2016-03-01 23:34:47 +01001360 /* oparg value is unsigned, but a signed C int is usually used to store
1361 it in the C code (like Python/ceval.c).
1362
1363 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1364
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001365 The argument of a concrete bytecode instruction is limited to 8-bit.
1366 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1367 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001368 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 off = compiler_next_instr(c, c->u->u_curblock);
1371 if (off < 0)
1372 return 0;
1373 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001374 i->i_opcode = opcode;
1375 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 compiler_set_lineno(c, off);
1377 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378}
1379
1380static int
1381compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 struct instr *i;
1384 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001386 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 assert(b != NULL);
1388 off = compiler_next_instr(c, c->u->u_curblock);
1389 if (off < 0)
1390 return 0;
1391 i = &c->u->u_curblock->b_instr[off];
1392 i->i_opcode = opcode;
1393 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (absolute)
1395 i->i_jabs = 1;
1396 else
1397 i->i_jrel = 1;
1398 compiler_set_lineno(c, off);
1399 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400}
1401
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001402/* NEXT_BLOCK() creates an implicit jump from the current block
1403 to the new block.
1404
1405 The returns inside this macro make it impossible to decref objects
1406 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001408#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (compiler_next_block((C)) == NULL) \
1410 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411}
1412
1413#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (!compiler_addop((C), (OP))) \
1415 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416}
1417
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001418#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (!compiler_addop((C), (OP))) { \
1420 compiler_exit_scope(c); \
1421 return 0; \
1422 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001423}
1424
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001425#define ADDOP_LOAD_CONST(C, O) { \
1426 if (!compiler_addop_load_const((C), (O))) \
1427 return 0; \
1428}
1429
1430/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1431#define ADDOP_LOAD_CONST_NEW(C, O) { \
1432 PyObject *__new_const = (O); \
1433 if (__new_const == NULL) { \
1434 return 0; \
1435 } \
1436 if (!compiler_addop_load_const((C), __new_const)) { \
1437 Py_DECREF(__new_const); \
1438 return 0; \
1439 } \
1440 Py_DECREF(__new_const); \
1441}
1442
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1445 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446}
1447
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001448/* Same as ADDOP_O, but steals a reference. */
1449#define ADDOP_N(C, OP, O, TYPE) { \
1450 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1451 Py_DECREF((O)); \
1452 return 0; \
1453 } \
1454 Py_DECREF((O)); \
1455}
1456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1459 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460}
1461
1462#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (!compiler_addop_i((C), (OP), (O))) \
1464 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465}
1466
1467#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (!compiler_addop_j((C), (OP), (O), 1)) \
1469 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470}
1471
1472#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!compiler_addop_j((C), (OP), (O), 0)) \
1474 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475}
1476
1477/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1478 the ASDL name to synthesize the name of the C type and the visit function.
1479*/
1480
1481#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_visit_ ## TYPE((C), (V))) \
1483 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484}
1485
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001486#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (!compiler_visit_ ## TYPE((C), (V))) { \
1488 compiler_exit_scope(c); \
1489 return 0; \
1490 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001491}
1492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!compiler_visit_slice((C), (V), (CTX))) \
1495 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496}
1497
1498#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int _i; \
1500 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1501 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1502 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1503 if (!compiler_visit_ ## TYPE((C), elt)) \
1504 return 0; \
1505 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506}
1507
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001508#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 int _i; \
1510 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1511 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1512 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1513 if (!compiler_visit_ ## TYPE((C), elt)) { \
1514 compiler_exit_scope(c); \
1515 return 0; \
1516 } \
1517 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001518}
1519
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001520/* Search if variable annotations are present statically in a block. */
1521
1522static int
1523find_ann(asdl_seq *stmts)
1524{
1525 int i, j, res = 0;
1526 stmt_ty st;
1527
1528 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1529 st = (stmt_ty)asdl_seq_GET(stmts, i);
1530 switch (st->kind) {
1531 case AnnAssign_kind:
1532 return 1;
1533 case For_kind:
1534 res = find_ann(st->v.For.body) ||
1535 find_ann(st->v.For.orelse);
1536 break;
1537 case AsyncFor_kind:
1538 res = find_ann(st->v.AsyncFor.body) ||
1539 find_ann(st->v.AsyncFor.orelse);
1540 break;
1541 case While_kind:
1542 res = find_ann(st->v.While.body) ||
1543 find_ann(st->v.While.orelse);
1544 break;
1545 case If_kind:
1546 res = find_ann(st->v.If.body) ||
1547 find_ann(st->v.If.orelse);
1548 break;
1549 case With_kind:
1550 res = find_ann(st->v.With.body);
1551 break;
1552 case AsyncWith_kind:
1553 res = find_ann(st->v.AsyncWith.body);
1554 break;
1555 case Try_kind:
1556 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1557 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1558 st->v.Try.handlers, j);
1559 if (find_ann(handler->v.ExceptHandler.body)) {
1560 return 1;
1561 }
1562 }
1563 res = find_ann(st->v.Try.body) ||
1564 find_ann(st->v.Try.finalbody) ||
1565 find_ann(st->v.Try.orelse);
1566 break;
1567 default:
1568 res = 0;
1569 }
1570 if (res) {
1571 break;
1572 }
1573 }
1574 return res;
1575}
1576
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001577/*
1578 * Frame block handling functions
1579 */
1580
1581static int
1582compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
1583 basicblock *exit)
1584{
1585 struct fblockinfo *f;
1586 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
1587 PyErr_SetString(PyExc_SyntaxError,
1588 "too many statically nested blocks");
1589 return 0;
1590 }
1591 f = &c->u->u_fblock[c->u->u_nfblocks++];
1592 f->fb_type = t;
1593 f->fb_block = b;
1594 f->fb_exit = exit;
1595 return 1;
1596}
1597
1598static void
1599compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1600{
1601 struct compiler_unit *u = c->u;
1602 assert(u->u_nfblocks > 0);
1603 u->u_nfblocks--;
1604 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1605 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1606}
1607
1608/* Unwind a frame block. If preserve_tos is true, the TOS before
1609 * popping the blocks will be restored afterwards.
1610 */
1611static int
1612compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1613 int preserve_tos)
1614{
1615 switch (info->fb_type) {
1616 case WHILE_LOOP:
1617 return 1;
1618
1619 case FINALLY_END:
1620 ADDOP_I(c, POP_FINALLY, preserve_tos);
1621 return 1;
1622
1623 case FOR_LOOP:
1624 /* Pop the iterator */
1625 if (preserve_tos) {
1626 ADDOP(c, ROT_TWO);
1627 }
1628 ADDOP(c, POP_TOP);
1629 return 1;
1630
1631 case EXCEPT:
1632 ADDOP(c, POP_BLOCK);
1633 return 1;
1634
1635 case FINALLY_TRY:
1636 ADDOP(c, POP_BLOCK);
1637 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1638 return 1;
1639
1640 case WITH:
1641 case ASYNC_WITH:
1642 ADDOP(c, POP_BLOCK);
1643 if (preserve_tos) {
1644 ADDOP(c, ROT_TWO);
1645 }
1646 ADDOP(c, BEGIN_FINALLY);
1647 ADDOP(c, WITH_CLEANUP_START);
1648 if (info->fb_type == ASYNC_WITH) {
1649 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001650 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001651 ADDOP(c, YIELD_FROM);
1652 }
1653 ADDOP(c, WITH_CLEANUP_FINISH);
1654 ADDOP_I(c, POP_FINALLY, 0);
1655 return 1;
1656
1657 case HANDLER_CLEANUP:
1658 if (preserve_tos) {
1659 ADDOP(c, ROT_FOUR);
1660 }
1661 if (info->fb_exit) {
1662 ADDOP(c, POP_BLOCK);
1663 ADDOP(c, POP_EXCEPT);
1664 ADDOP_JREL(c, CALL_FINALLY, info->fb_exit);
1665 }
1666 else {
1667 ADDOP(c, POP_EXCEPT);
1668 }
1669 return 1;
1670 }
1671 Py_UNREACHABLE();
1672}
1673
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001674/* Compile a sequence of statements, checking for a docstring
1675 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001676
1677static int
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001678compiler_body(struct compiler *c, asdl_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001680 int i = 0;
1681 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001682 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001683
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001684 /* Set current line number to the line number of first statement.
1685 This way line number for SETUP_ANNOTATIONS will always
1686 coincide with the line number of first "real" statement in module.
1687 If body is empy, then lineno will be set later in assemble. */
1688 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1689 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001690 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001691 c->u->u_lineno = st->lineno;
1692 }
1693 /* Every annotated class and module should have __annotations__. */
1694 if (find_ann(stmts)) {
1695 ADDOP(c, SETUP_ANNOTATIONS);
1696 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001697 if (!asdl_seq_LEN(stmts))
1698 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001699 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001700 if (c->c_optimize < 2) {
1701 docstring = _PyAST_GetDocString(stmts);
1702 if (docstring) {
1703 i = 1;
1704 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1705 assert(st->kind == Expr_kind);
1706 VISIT(c, expr, st->v.Expr.value);
1707 if (!compiler_nameop(c, __doc__, Store))
1708 return 0;
1709 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001711 for (; i < asdl_seq_LEN(stmts); i++)
1712 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714}
1715
1716static PyCodeObject *
1717compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyCodeObject *co;
1720 int addNone = 1;
1721 static PyObject *module;
1722 if (!module) {
1723 module = PyUnicode_InternFromString("<module>");
1724 if (!module)
1725 return NULL;
1726 }
1727 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001728 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return NULL;
1730 switch (mod->kind) {
1731 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001732 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 compiler_exit_scope(c);
1734 return 0;
1735 }
1736 break;
1737 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001738 if (find_ann(mod->v.Interactive.body)) {
1739 ADDOP(c, SETUP_ANNOTATIONS);
1740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 c->c_interactive = 1;
1742 VISIT_SEQ_IN_SCOPE(c, stmt,
1743 mod->v.Interactive.body);
1744 break;
1745 case Expression_kind:
1746 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1747 addNone = 0;
1748 break;
1749 case Suite_kind:
1750 PyErr_SetString(PyExc_SystemError,
1751 "suite should not be possible");
1752 return 0;
1753 default:
1754 PyErr_Format(PyExc_SystemError,
1755 "module kind %d should not be possible",
1756 mod->kind);
1757 return 0;
1758 }
1759 co = assemble(c, addNone);
1760 compiler_exit_scope(c);
1761 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001762}
1763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764/* The test for LOCAL must come before the test for FREE in order to
1765 handle classes where name is both local and free. The local var is
1766 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001767*/
1768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769static int
1770get_ref_type(struct compiler *c, PyObject *name)
1771{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001772 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001773 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001774 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001775 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001776 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (scope == 0) {
1778 char buf[350];
1779 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001780 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001782 PyUnicode_AsUTF8(name),
1783 PyUnicode_AsUTF8(c->u->u_name),
1784 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1785 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1786 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1787 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 );
1789 Py_FatalError(buf);
1790 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793}
1794
1795static int
1796compiler_lookup_arg(PyObject *dict, PyObject *name)
1797{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001798 PyObject *v;
1799 v = PyDict_GetItem(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001801 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001802 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803}
1804
1805static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001806compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001808 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001809 if (qualname == NULL)
1810 qualname = co->co_name;
1811
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001812 if (free) {
1813 for (i = 0; i < free; ++i) {
1814 /* Bypass com_addop_varname because it will generate
1815 LOAD_DEREF but LOAD_CLOSURE is needed.
1816 */
1817 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1818 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001820 /* Special case: If a class contains a method with a
1821 free variable that has the same name as a method,
1822 the name will be considered free *and* local in the
1823 class. It should be handled by the closure, as
1824 well as by the normal name loookup logic.
1825 */
1826 reftype = get_ref_type(c, name);
1827 if (reftype == CELL)
1828 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1829 else /* (reftype == FREE) */
1830 arg = compiler_lookup_arg(c->u->u_freevars, name);
1831 if (arg == -1) {
1832 fprintf(stderr,
1833 "lookup %s in %s %d %d\n"
1834 "freevars of %s: %s\n",
1835 PyUnicode_AsUTF8(PyObject_Repr(name)),
1836 PyUnicode_AsUTF8(c->u->u_name),
1837 reftype, arg,
1838 PyUnicode_AsUTF8(co->co_name),
1839 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1840 Py_FatalError("compiler_make_closure()");
1841 }
1842 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001844 flags |= 0x08;
1845 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001847 ADDOP_LOAD_CONST(c, (PyObject*)co);
1848 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001849 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853static int
1854compiler_decorators(struct compiler *c, asdl_seq* decos)
1855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (!decos)
1859 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1862 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1863 }
1864 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865}
1866
1867static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001868compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001870{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001871 /* Push a dict of keyword-only default values.
1872
1873 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1874 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001875 int i;
1876 PyObject *keys = NULL;
1877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1879 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1880 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1881 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001882 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001883 if (!mangled) {
1884 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001886 if (keys == NULL) {
1887 keys = PyList_New(1);
1888 if (keys == NULL) {
1889 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001890 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001891 }
1892 PyList_SET_ITEM(keys, 0, mangled);
1893 }
1894 else {
1895 int res = PyList_Append(keys, mangled);
1896 Py_DECREF(mangled);
1897 if (res == -1) {
1898 goto error;
1899 }
1900 }
1901 if (!compiler_visit_expr(c, default_)) {
1902 goto error;
1903 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 }
1905 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001906 if (keys != NULL) {
1907 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1908 PyObject *keys_tuple = PyList_AsTuple(keys);
1909 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001910 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001911 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001912 assert(default_count > 0);
1913 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001914 }
1915 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001916 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001917 }
1918
1919error:
1920 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001921 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001922}
1923
1924static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08001925compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
1926{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03001927 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08001928 return 1;
1929}
1930
1931static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001932compiler_visit_argannotation(struct compiler *c, identifier id,
1933 expr_ty annotation, PyObject *names)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001936 PyObject *mangled;
Guido van Rossum95e4d582018-01-26 08:20:18 -08001937 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
1938 VISIT(c, annexpr, annotation)
1939 }
1940 else {
1941 VISIT(c, expr, annotation);
1942 }
Victor Stinner065efc32014-02-18 22:07:56 +01001943 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001944 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001945 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001946 if (PyList_Append(names, mangled) < 0) {
1947 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001948 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001949 }
1950 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001952 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001953}
1954
1955static int
1956compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1957 PyObject *names)
1958{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001959 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 for (i = 0; i < asdl_seq_LEN(args); i++) {
1961 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001962 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 c,
1964 arg->arg,
1965 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001966 names))
1967 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001969 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001970}
1971
1972static int
1973compiler_visit_annotations(struct compiler *c, arguments_ty args,
1974 expr_ty returns)
1975{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001976 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001977 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001978
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001979 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 */
1981 static identifier return_str;
1982 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001983 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 names = PyList_New(0);
1985 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001986 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001987
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001988 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001990 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001991 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001992 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001994 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001996 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001997 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001998 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (!return_str) {
2002 return_str = PyUnicode_InternFromString("return");
2003 if (!return_str)
2004 goto error;
2005 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002006 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 goto error;
2008 }
2009
2010 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002012 PyObject *keytuple = PyList_AsTuple(names);
2013 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002014 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002016 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002018 else {
2019 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002020 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002022
2023error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002025 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002026}
2027
2028static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002029compiler_visit_defaults(struct compiler *c, arguments_ty args)
2030{
2031 VISIT_SEQ(c, expr, args->defaults);
2032 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002036static Py_ssize_t
2037compiler_default_arguments(struct compiler *c, arguments_ty args)
2038{
2039 Py_ssize_t funcflags = 0;
2040 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002041 if (!compiler_visit_defaults(c, args))
2042 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002043 funcflags |= 0x01;
2044 }
2045 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002046 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002047 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002048 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 return -1;
2050 }
2051 else if (res > 0) {
2052 funcflags |= 0x02;
2053 }
2054 }
2055 return funcflags;
2056}
2057
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058static int
Yury Selivanov75445082015-05-11 22:57:16 -04002059compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002062 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002063 arguments_ty args;
2064 expr_ty returns;
2065 identifier name;
2066 asdl_seq* decos;
2067 asdl_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002068 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002069 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002070 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002071 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Yury Selivanov75445082015-05-11 22:57:16 -04002073 if (is_async) {
2074 assert(s->kind == AsyncFunctionDef_kind);
2075
2076 args = s->v.AsyncFunctionDef.args;
2077 returns = s->v.AsyncFunctionDef.returns;
2078 decos = s->v.AsyncFunctionDef.decorator_list;
2079 name = s->v.AsyncFunctionDef.name;
2080 body = s->v.AsyncFunctionDef.body;
2081
2082 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2083 } else {
2084 assert(s->kind == FunctionDef_kind);
2085
2086 args = s->v.FunctionDef.args;
2087 returns = s->v.FunctionDef.returns;
2088 decos = s->v.FunctionDef.decorator_list;
2089 name = s->v.FunctionDef.name;
2090 body = s->v.FunctionDef.body;
2091
2092 scope_type = COMPILER_SCOPE_FUNCTION;
2093 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (!compiler_decorators(c, decos))
2096 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002097
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002098 firstlineno = s->lineno;
2099 if (asdl_seq_LEN(decos)) {
2100 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2101 }
2102
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002103 funcflags = compiler_default_arguments(c, args);
2104 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002106 }
2107
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002108 annotations = compiler_visit_annotations(c, args, returns);
2109 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002110 return 0;
2111 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002112 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002113 funcflags |= 0x04;
2114 }
2115
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002116 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002117 return 0;
2118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119
INADA Naokicb41b272017-02-23 00:31:59 +09002120 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002121 if (c->c_optimize < 2) {
2122 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002123 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002124 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 compiler_exit_scope(c);
2126 return 0;
2127 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 c->u->u_argcount = asdl_seq_LEN(args->args);
2130 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
INADA Naokicb41b272017-02-23 00:31:59 +09002131 VISIT_SEQ_IN_SCOPE(c, stmt, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002133 qualname = c->u->u_qualname;
2134 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002136 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002137 Py_XDECREF(qualname);
2138 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002142 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002143 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* decorators */
2147 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2148 ADDOP_I(c, CALL_FUNCTION, 1);
2149 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150
Yury Selivanov75445082015-05-11 22:57:16 -04002151 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152}
2153
2154static int
2155compiler_class(struct compiler *c, stmt_ty s)
2156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyCodeObject *co;
2158 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002159 int i, firstlineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (!compiler_decorators(c, decos))
2163 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002164
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002165 firstlineno = s->lineno;
2166 if (asdl_seq_LEN(decos)) {
2167 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2168 }
2169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* ultimately generate code for:
2171 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2172 where:
2173 <func> is a function/closure created from the class body;
2174 it has a single argument (__locals__) where the dict
2175 (or MutableSequence) representing the locals is passed
2176 <name> is the class name
2177 <bases> is the positional arguments and *varargs argument
2178 <keywords> is the keyword arguments and **kwds argument
2179 This borrows from compiler_call.
2180 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002183 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002184 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 return 0;
2186 /* this block represents what we do in the new scope */
2187 {
2188 /* use the class name for name mangling */
2189 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002190 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* load (global) __name__ ... */
2192 str = PyUnicode_InternFromString("__name__");
2193 if (!str || !compiler_nameop(c, str, Load)) {
2194 Py_XDECREF(str);
2195 compiler_exit_scope(c);
2196 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 Py_DECREF(str);
2199 /* ... and store it as __module__ */
2200 str = PyUnicode_InternFromString("__module__");
2201 if (!str || !compiler_nameop(c, str, Store)) {
2202 Py_XDECREF(str);
2203 compiler_exit_scope(c);
2204 return 0;
2205 }
2206 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002207 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002208 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002209 str = PyUnicode_InternFromString("__qualname__");
2210 if (!str || !compiler_nameop(c, str, Store)) {
2211 Py_XDECREF(str);
2212 compiler_exit_scope(c);
2213 return 0;
2214 }
2215 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002217 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 compiler_exit_scope(c);
2219 return 0;
2220 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002221 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002222 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002223 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002224 str = PyUnicode_InternFromString("__class__");
2225 if (str == NULL) {
2226 compiler_exit_scope(c);
2227 return 0;
2228 }
2229 i = compiler_lookup_arg(c->u->u_cellvars, str);
2230 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002231 if (i < 0) {
2232 compiler_exit_scope(c);
2233 return 0;
2234 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002235 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002238 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002239 str = PyUnicode_InternFromString("__classcell__");
2240 if (!str || !compiler_nameop(c, str, Store)) {
2241 Py_XDECREF(str);
2242 compiler_exit_scope(c);
2243 return 0;
2244 }
2245 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002247 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002248 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002249 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002250 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002251 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002252 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 /* create the code object */
2254 co = assemble(c, 1);
2255 }
2256 /* leave the new scope */
2257 compiler_exit_scope(c);
2258 if (co == NULL)
2259 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 /* 2. load the 'build_class' function */
2262 ADDOP(c, LOAD_BUILD_CLASS);
2263
2264 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002265 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 Py_DECREF(co);
2267
2268 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002269 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270
2271 /* 5. generate the rest of the code for the call */
2272 if (!compiler_call_helper(c, 2,
2273 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002274 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 return 0;
2276
2277 /* 6. apply decorators */
2278 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2279 ADDOP_I(c, CALL_FUNCTION, 1);
2280 }
2281
2282 /* 7. store into <name> */
2283 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2284 return 0;
2285 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286}
2287
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002288/* Return 0 if the expression is a constant value except named singletons.
2289 Return 1 otherwise. */
2290static int
2291check_is_arg(expr_ty e)
2292{
2293 if (e->kind != Constant_kind) {
2294 return 1;
2295 }
2296 PyObject *value = e->v.Constant.value;
2297 return (value == Py_None
2298 || value == Py_False
2299 || value == Py_True
2300 || value == Py_Ellipsis);
2301}
2302
2303/* Check operands of identity chacks ("is" and "is not").
2304 Emit a warning if any operand is a constant except named singletons.
2305 Return 0 on error.
2306 */
2307static int
2308check_compare(struct compiler *c, expr_ty e)
2309{
2310 Py_ssize_t i, n;
2311 int left = check_is_arg(e->v.Compare.left);
2312 n = asdl_seq_LEN(e->v.Compare.ops);
2313 for (i = 0; i < n; i++) {
2314 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2315 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2316 if (op == Is || op == IsNot) {
2317 if (!right || !left) {
2318 const char *msg = (op == Is)
2319 ? "\"is\" with a literal. Did you mean \"==\"?"
2320 : "\"is not\" with a literal. Did you mean \"!=\"?";
2321 return compiler_warn(c, msg);
2322 }
2323 }
2324 left = right;
2325 }
2326 return 1;
2327}
2328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002329static int
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002330cmpop(cmpop_ty op)
2331{
2332 switch (op) {
2333 case Eq:
2334 return PyCmp_EQ;
2335 case NotEq:
2336 return PyCmp_NE;
2337 case Lt:
2338 return PyCmp_LT;
2339 case LtE:
2340 return PyCmp_LE;
2341 case Gt:
2342 return PyCmp_GT;
2343 case GtE:
2344 return PyCmp_GE;
2345 case Is:
2346 return PyCmp_IS;
2347 case IsNot:
2348 return PyCmp_IS_NOT;
2349 case In:
2350 return PyCmp_IN;
2351 case NotIn:
2352 return PyCmp_NOT_IN;
2353 default:
2354 return PyCmp_BAD;
2355 }
2356}
2357
2358static int
2359compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2360{
2361 switch (e->kind) {
2362 case UnaryOp_kind:
2363 if (e->v.UnaryOp.op == Not)
2364 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2365 /* fallback to general implementation */
2366 break;
2367 case BoolOp_kind: {
2368 asdl_seq *s = e->v.BoolOp.values;
2369 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2370 assert(n >= 0);
2371 int cond2 = e->v.BoolOp.op == Or;
2372 basicblock *next2 = next;
2373 if (!cond2 != !cond) {
2374 next2 = compiler_new_block(c);
2375 if (next2 == NULL)
2376 return 0;
2377 }
2378 for (i = 0; i < n; ++i) {
2379 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2380 return 0;
2381 }
2382 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2383 return 0;
2384 if (next2 != next)
2385 compiler_use_next_block(c, next2);
2386 return 1;
2387 }
2388 case IfExp_kind: {
2389 basicblock *end, *next2;
2390 end = compiler_new_block(c);
2391 if (end == NULL)
2392 return 0;
2393 next2 = compiler_new_block(c);
2394 if (next2 == NULL)
2395 return 0;
2396 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2397 return 0;
2398 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2399 return 0;
2400 ADDOP_JREL(c, JUMP_FORWARD, end);
2401 compiler_use_next_block(c, next2);
2402 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2403 return 0;
2404 compiler_use_next_block(c, end);
2405 return 1;
2406 }
2407 case Compare_kind: {
2408 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2409 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002410 if (!check_compare(c, e)) {
2411 return 0;
2412 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002413 basicblock *cleanup = compiler_new_block(c);
2414 if (cleanup == NULL)
2415 return 0;
2416 VISIT(c, expr, e->v.Compare.left);
2417 for (i = 0; i < n; i++) {
2418 VISIT(c, expr,
2419 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2420 ADDOP(c, DUP_TOP);
2421 ADDOP(c, ROT_THREE);
2422 ADDOP_I(c, COMPARE_OP,
2423 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
2424 ADDOP_JABS(c, POP_JUMP_IF_FALSE, cleanup);
2425 NEXT_BLOCK(c);
2426 }
2427 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2428 ADDOP_I(c, COMPARE_OP,
2429 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
2430 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2431 basicblock *end = compiler_new_block(c);
2432 if (end == NULL)
2433 return 0;
2434 ADDOP_JREL(c, JUMP_FORWARD, end);
2435 compiler_use_next_block(c, cleanup);
2436 ADDOP(c, POP_TOP);
2437 if (!cond) {
2438 ADDOP_JREL(c, JUMP_FORWARD, next);
2439 }
2440 compiler_use_next_block(c, end);
2441 return 1;
2442 }
2443 /* fallback to general implementation */
2444 break;
2445 }
2446 default:
2447 /* fallback to general implementation */
2448 break;
2449 }
2450
2451 /* general implementation */
2452 VISIT(c, expr, e);
2453 ADDOP_JABS(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2454 return 1;
2455}
2456
2457static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002458compiler_ifexp(struct compiler *c, expr_ty e)
2459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 basicblock *end, *next;
2461
2462 assert(e->kind == IfExp_kind);
2463 end = compiler_new_block(c);
2464 if (end == NULL)
2465 return 0;
2466 next = compiler_new_block(c);
2467 if (next == NULL)
2468 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002469 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2470 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 VISIT(c, expr, e->v.IfExp.body);
2472 ADDOP_JREL(c, JUMP_FORWARD, end);
2473 compiler_use_next_block(c, next);
2474 VISIT(c, expr, e->v.IfExp.orelse);
2475 compiler_use_next_block(c, end);
2476 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002477}
2478
2479static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480compiler_lambda(struct compiler *c, expr_ty e)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002483 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002485 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 arguments_ty args = e->v.Lambda.args;
2487 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (!name) {
2490 name = PyUnicode_InternFromString("<lambda>");
2491 if (!name)
2492 return 0;
2493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002495 funcflags = compiler_default_arguments(c, args);
2496 if (funcflags == -1) {
2497 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002499
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002500 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002501 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* Make None the first constant, so the lambda can't have a
2505 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002506 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 c->u->u_argcount = asdl_seq_LEN(args->args);
2510 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2511 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2512 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002513 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 }
2515 else {
2516 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002517 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002519 qualname = c->u->u_qualname;
2520 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002522 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002525 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002526 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 Py_DECREF(co);
2528
2529 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530}
2531
2532static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533compiler_if(struct compiler *c, stmt_ty s)
2534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 basicblock *end, *next;
2536 int constant;
2537 assert(s->kind == If_kind);
2538 end = compiler_new_block(c);
2539 if (end == NULL)
2540 return 0;
2541
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002542 constant = expr_constant(s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* constant = 0: "if 0"
2544 * constant = 1: "if 1", "if 2", ...
2545 * constant = -1: rest */
2546 if (constant == 0) {
2547 if (s->v.If.orelse)
2548 VISIT_SEQ(c, stmt, s->v.If.orelse);
2549 } else if (constant == 1) {
2550 VISIT_SEQ(c, stmt, s->v.If.body);
2551 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002552 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 next = compiler_new_block(c);
2554 if (next == NULL)
2555 return 0;
2556 }
2557 else
2558 next = end;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002559 if (!compiler_jump_if(c, s->v.If.test, next, 0))
2560 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002562 if (asdl_seq_LEN(s->v.If.orelse)) {
2563 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 compiler_use_next_block(c, next);
2565 VISIT_SEQ(c, stmt, s->v.If.orelse);
2566 }
2567 }
2568 compiler_use_next_block(c, end);
2569 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570}
2571
2572static int
2573compiler_for(struct compiler *c, stmt_ty s)
2574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 start = compiler_new_block(c);
2578 cleanup = compiler_new_block(c);
2579 end = compiler_new_block(c);
2580 if (start == NULL || end == NULL || cleanup == NULL)
2581 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002582
2583 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 VISIT(c, expr, s->v.For.iter);
2587 ADDOP(c, GET_ITER);
2588 compiler_use_next_block(c, start);
2589 ADDOP_JREL(c, FOR_ITER, cleanup);
2590 VISIT(c, expr, s->v.For.target);
2591 VISIT_SEQ(c, stmt, s->v.For.body);
2592 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2593 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002594
2595 compiler_pop_fblock(c, FOR_LOOP, start);
2596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 VISIT_SEQ(c, stmt, s->v.For.orelse);
2598 compiler_use_next_block(c, end);
2599 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600}
2601
Yury Selivanov75445082015-05-11 22:57:16 -04002602
2603static int
2604compiler_async_for(struct compiler *c, stmt_ty s)
2605{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002606 basicblock *start, *except, *end;
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002607 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2608 return compiler_error(c, "'async for' outside async function");
2609 }
2610
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002611 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002612 except = compiler_new_block(c);
2613 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002614
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002615 if (start == NULL || except == NULL || end == NULL)
Yury Selivanov75445082015-05-11 22:57:16 -04002616 return 0;
2617
2618 VISIT(c, expr, s->v.AsyncFor.iter);
2619 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002620
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002621 compiler_use_next_block(c, start);
2622 if (!compiler_push_fblock(c, FOR_LOOP, start, end))
2623 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002624
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002625 /* SETUP_FINALLY to guard the __anext__ call */
2626 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002627 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002628 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002629 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002630 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002631
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002632 /* Success block for __anext__ */
2633 VISIT(c, expr, s->v.AsyncFor.target);
2634 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2635 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2636
2637 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002638
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002639 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002640 compiler_use_next_block(c, except);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002641 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002642
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002643 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002644 VISIT_SEQ(c, stmt, s->v.For.orelse);
2645
2646 compiler_use_next_block(c, end);
2647
2648 return 1;
2649}
2650
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651static int
2652compiler_while(struct compiler *c, stmt_ty s)
2653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002655 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (constant == 0) {
2658 if (s->v.While.orelse)
2659 VISIT_SEQ(c, stmt, s->v.While.orelse);
2660 return 1;
2661 }
2662 loop = compiler_new_block(c);
2663 end = compiler_new_block(c);
2664 if (constant == -1) {
2665 anchor = compiler_new_block(c);
2666 if (anchor == NULL)
2667 return 0;
2668 }
2669 if (loop == NULL || end == NULL)
2670 return 0;
2671 if (s->v.While.orelse) {
2672 orelse = compiler_new_block(c);
2673 if (orelse == NULL)
2674 return 0;
2675 }
2676 else
2677 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 compiler_use_next_block(c, loop);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002680 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 return 0;
2682 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002683 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2684 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
2686 VISIT_SEQ(c, stmt, s->v.While.body);
2687 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 /* XXX should the two POP instructions be in a separate block
2690 if there is no else clause ?
2691 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002693 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002695 compiler_pop_fblock(c, WHILE_LOOP, loop);
2696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (orelse != NULL) /* what if orelse is just pass? */
2698 VISIT_SEQ(c, stmt, s->v.While.orelse);
2699 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702}
2703
2704static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002705compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002707 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002708 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002709 if (c->u->u_ste->ste_type != FunctionBlock)
2710 return compiler_error(c, "'return' outside function");
2711 if (s->v.Return.value != NULL &&
2712 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2713 {
2714 return compiler_error(
2715 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002717 if (preserve_tos) {
2718 VISIT(c, expr, s->v.Return.value);
2719 }
2720 for (int depth = c->u->u_nfblocks; depth--;) {
2721 struct fblockinfo *info = &c->u->u_fblock[depth];
2722
2723 if (!compiler_unwind_fblock(c, info, preserve_tos))
2724 return 0;
2725 }
2726 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002727 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002728 }
2729 else if (!preserve_tos) {
2730 VISIT(c, expr, s->v.Return.value);
2731 }
2732 ADDOP(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735}
2736
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002737static int
2738compiler_break(struct compiler *c)
2739{
2740 for (int depth = c->u->u_nfblocks; depth--;) {
2741 struct fblockinfo *info = &c->u->u_fblock[depth];
2742
2743 if (!compiler_unwind_fblock(c, info, 0))
2744 return 0;
2745 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2746 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_exit);
2747 return 1;
2748 }
2749 }
2750 return compiler_error(c, "'break' outside loop");
2751}
2752
2753static int
2754compiler_continue(struct compiler *c)
2755{
2756 for (int depth = c->u->u_nfblocks; depth--;) {
2757 struct fblockinfo *info = &c->u->u_fblock[depth];
2758
2759 if (info->fb_type == WHILE_LOOP || info->fb_type == FOR_LOOP) {
2760 ADDOP_JABS(c, JUMP_ABSOLUTE, info->fb_block);
2761 return 1;
2762 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002763 if (!compiler_unwind_fblock(c, info, 0))
2764 return 0;
2765 }
2766 return compiler_error(c, "'continue' not properly in loop");
2767}
2768
2769
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771
2772 SETUP_FINALLY L
2773 <code for body>
2774 POP_BLOCK
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002775 BEGIN_FINALLY
2776 L:
2777 <code for finalbody>
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 END_FINALLY
2779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002780 The special instructions use the block stack. Each block
2781 stack entry contains the instruction that created it (here
2782 SETUP_FINALLY), the level of the value stack at the time the
2783 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 Pushes the current value stack level and the label
2787 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 Pops en entry from the block stack.
2790 BEGIN_FINALLY
2791 Pushes NULL onto the value stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 END_FINALLY:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002793 Pops 1 (NULL or int) or 6 entries from the *value* stack and restore
2794 the raised and the caught exceptions they specify.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002797 when a SETUP_FINALLY entry is found, the raised and the caught
2798 exceptions are pushed onto the value stack (and the exception
2799 condition is cleared), and the interpreter jumps to the label
2800 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002801*/
2802
2803static int
2804compiler_try_finally(struct compiler *c, stmt_ty s)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 basicblock *body, *end;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 body = compiler_new_block(c);
2809 end = compiler_new_block(c);
2810 if (body == NULL || end == NULL)
2811 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002812
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002813 /* `try` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 ADDOP_JREL(c, SETUP_FINALLY, end);
2815 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002816 if (!compiler_push_fblock(c, FINALLY_TRY, body, end))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002818 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2819 if (!compiler_try_except(c, s))
2820 return 0;
2821 }
2822 else {
2823 VISIT_SEQ(c, stmt, s->v.Try.body);
2824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002826 ADDOP(c, BEGIN_FINALLY);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002829 /* `finally` block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 compiler_use_next_block(c, end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002831 if (!compiler_push_fblock(c, FINALLY_END, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002833 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 ADDOP(c, END_FINALLY);
2835 compiler_pop_fblock(c, FINALLY_END, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837}
2838
2839/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002840 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841 (The contents of the value stack is shown in [], with the top
2842 at the right; 'tb' is trace-back info, 'val' the exception's
2843 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844
2845 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002846 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 [] <code for S>
2848 [] POP_BLOCK
2849 [] JUMP_FORWARD L0
2850
2851 [tb, val, exc] L1: DUP )
2852 [tb, val, exc, exc] <evaluate E1> )
2853 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2854 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2855 [tb, val, exc] POP
2856 [tb, val] <assign to V1> (or POP if no V1)
2857 [tb] POP
2858 [] <code for S1>
2859 JUMP_FORWARD L0
2860
2861 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 .............................etc.......................
2863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2865
2866 [] L0: <next statement>
2867
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868 Of course, parts are not generated if Vi or Ei is not present.
2869*/
2870static int
2871compiler_try_except(struct compiler *c, stmt_ty s)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002874 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 body = compiler_new_block(c);
2877 except = compiler_new_block(c);
2878 orelse = compiler_new_block(c);
2879 end = compiler_new_block(c);
2880 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2881 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002882 ADDOP_JREL(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 compiler_use_next_block(c, body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884 if (!compiler_push_fblock(c, EXCEPT, body, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002886 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 ADDOP(c, POP_BLOCK);
2888 compiler_pop_fblock(c, EXCEPT, body);
2889 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002890 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 compiler_use_next_block(c, except);
2892 for (i = 0; i < n; i++) {
2893 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002894 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if (!handler->v.ExceptHandler.type && i < n-1)
2896 return compiler_error(c, "default 'except:' must be last");
2897 c->u->u_lineno_set = 0;
2898 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002899 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 except = compiler_new_block(c);
2901 if (except == NULL)
2902 return 0;
2903 if (handler->v.ExceptHandler.type) {
2904 ADDOP(c, DUP_TOP);
2905 VISIT(c, expr, handler->v.ExceptHandler.type);
2906 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2907 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2908 }
2909 ADDOP(c, POP_TOP);
2910 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002911 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002912
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002913 cleanup_end = compiler_new_block(c);
2914 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002915 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002916 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06002917 }
Guido van Rossumb940e112007-01-10 16:19:56 +00002918
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002919 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2920 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002922 /*
2923 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002924 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002925 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002926 try:
2927 # body
2928 finally:
2929 name = None
2930 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002931 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002933 /* second try: */
2934 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2935 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002936 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, cleanup_end))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002937 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002939 /* second # body */
2940 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2941 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942 ADDOP(c, BEGIN_FINALLY);
2943 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002945 /* finally: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002946 compiler_use_next_block(c, cleanup_end);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002948 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 /* name = None; del name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002951 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002952 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002953 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002955 ADDOP(c, END_FINALLY);
Serhiy Storchakad4864c62018-01-09 21:54:52 +02002956 ADDOP(c, POP_EXCEPT);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002957 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 }
2959 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002960 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002962 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002963 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002964 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
Guido van Rossumb940e112007-01-10 16:19:56 +00002966 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002967 ADDOP(c, POP_TOP);
2968 compiler_use_next_block(c, cleanup_body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002969 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002970 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002972 ADDOP(c, POP_EXCEPT);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002973 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 }
2975 ADDOP_JREL(c, JUMP_FORWARD, end);
2976 compiler_use_next_block(c, except);
2977 }
2978 ADDOP(c, END_FINALLY);
2979 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002980 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 compiler_use_next_block(c, end);
2982 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002986compiler_try(struct compiler *c, stmt_ty s) {
2987 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2988 return compiler_try_finally(c, s);
2989 else
2990 return compiler_try_except(c, s);
2991}
2992
2993
2994static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995compiler_import_as(struct compiler *c, identifier name, identifier asname)
2996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* The IMPORT_NAME opcode was already generated. This function
2998 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003001 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003003 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3004 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003005 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003006 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003007 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003009 while (1) {
3010 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003012 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003014 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003015 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003017 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003018 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003019 if (dot == -1) {
3020 break;
3021 }
3022 ADDOP(c, ROT_TWO);
3023 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003025 if (!compiler_nameop(c, asname, Store)) {
3026 return 0;
3027 }
3028 ADDOP(c, POP_TOP);
3029 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 }
3031 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032}
3033
3034static int
3035compiler_import(struct compiler *c, stmt_ty s)
3036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* The Import node stores a module name like a.b.c as a single
3038 string. This is convenient for all cases except
3039 import a.b.c as d
3040 where we need to parse that string to extract the individual
3041 module names.
3042 XXX Perhaps change the representation to make this case simpler?
3043 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003044 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 for (i = 0; i < n; i++) {
3047 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3048 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003050 ADDOP_LOAD_CONST(c, _PyLong_Zero);
3051 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (alias->asname) {
3055 r = compiler_import_as(c, alias->name, alias->asname);
3056 if (!r)
3057 return r;
3058 }
3059 else {
3060 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 Py_ssize_t dot = PyUnicode_FindChar(
3062 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003063 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003064 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003065 if (tmp == NULL)
3066 return 0;
3067 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003069 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 Py_DECREF(tmp);
3071 }
3072 if (!r)
3073 return r;
3074 }
3075 }
3076 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077}
3078
3079static int
3080compiler_from_import(struct compiler *c, stmt_ty s)
3081{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003082 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003083 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 if (!empty_string) {
3087 empty_string = PyUnicode_FromString("");
3088 if (!empty_string)
3089 return 0;
3090 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003092 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003093
3094 names = PyTuple_New(n);
3095 if (!names)
3096 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 /* build up the names */
3099 for (i = 0; i < n; i++) {
3100 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3101 Py_INCREF(alias->name);
3102 PyTuple_SET_ITEM(names, i, alias->name);
3103 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003106 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 Py_DECREF(names);
3108 return compiler_error(c, "from __future__ imports must occur "
3109 "at the beginning of the file");
3110 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003111 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 if (s->v.ImportFrom.module) {
3114 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3115 }
3116 else {
3117 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3118 }
3119 for (i = 0; i < n; i++) {
3120 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3121 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003123 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 assert(n == 1);
3125 ADDOP(c, IMPORT_STAR);
3126 return 1;
3127 }
3128
3129 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3130 store_name = alias->name;
3131 if (alias->asname)
3132 store_name = alias->asname;
3133
3134 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 return 0;
3136 }
3137 }
3138 /* remove imported module */
3139 ADDOP(c, POP_TOP);
3140 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141}
3142
3143static int
3144compiler_assert(struct compiler *c, stmt_ty s)
3145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 static PyObject *assertion_error = NULL;
3147 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
Georg Brandl8334fd92010-12-04 10:26:46 +00003149 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 return 1;
3151 if (assertion_error == NULL) {
3152 assertion_error = PyUnicode_InternFromString("AssertionError");
3153 if (assertion_error == NULL)
3154 return 0;
3155 }
3156 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003157 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3158 {
3159 if (!compiler_warn(c, "assertion is always true, "
3160 "perhaps remove parentheses?"))
3161 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003162 return 0;
3163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 end = compiler_new_block(c);
3166 if (end == NULL)
3167 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003168 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3169 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
3171 if (s->v.Assert.msg) {
3172 VISIT(c, expr, s->v.Assert.msg);
3173 ADDOP_I(c, CALL_FUNCTION, 1);
3174 }
3175 ADDOP_I(c, RAISE_VARARGS, 1);
3176 compiler_use_next_block(c, end);
3177 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178}
3179
3180static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003181compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3182{
3183 if (c->c_interactive && c->c_nestlevel <= 1) {
3184 VISIT(c, expr, value);
3185 ADDOP(c, PRINT_EXPR);
3186 return 1;
3187 }
3188
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003189 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003190 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003191 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003192 }
3193
3194 VISIT(c, expr, value);
3195 ADDOP(c, POP_TOP);
3196 return 1;
3197}
3198
3199static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200compiler_visit_stmt(struct compiler *c, stmt_ty s)
3201{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003202 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* Always assign a lineno to the next instruction for a stmt. */
3205 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003206 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 switch (s->kind) {
3210 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003211 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 case ClassDef_kind:
3213 return compiler_class(c, s);
3214 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003215 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 case Delete_kind:
3217 VISIT_SEQ(c, expr, s->v.Delete.targets)
3218 break;
3219 case Assign_kind:
3220 n = asdl_seq_LEN(s->v.Assign.targets);
3221 VISIT(c, expr, s->v.Assign.value);
3222 for (i = 0; i < n; i++) {
3223 if (i < n - 1)
3224 ADDOP(c, DUP_TOP);
3225 VISIT(c, expr,
3226 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3227 }
3228 break;
3229 case AugAssign_kind:
3230 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003231 case AnnAssign_kind:
3232 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 case For_kind:
3234 return compiler_for(c, s);
3235 case While_kind:
3236 return compiler_while(c, s);
3237 case If_kind:
3238 return compiler_if(c, s);
3239 case Raise_kind:
3240 n = 0;
3241 if (s->v.Raise.exc) {
3242 VISIT(c, expr, s->v.Raise.exc);
3243 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003244 if (s->v.Raise.cause) {
3245 VISIT(c, expr, s->v.Raise.cause);
3246 n++;
3247 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003249 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003251 case Try_kind:
3252 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 case Assert_kind:
3254 return compiler_assert(c, s);
3255 case Import_kind:
3256 return compiler_import(c, s);
3257 case ImportFrom_kind:
3258 return compiler_from_import(c, s);
3259 case Global_kind:
3260 case Nonlocal_kind:
3261 break;
3262 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003263 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 case Pass_kind:
3265 break;
3266 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003267 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 case Continue_kind:
3269 return compiler_continue(c);
3270 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003271 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003272 case AsyncFunctionDef_kind:
3273 return compiler_function(c, s, 1);
3274 case AsyncWith_kind:
3275 return compiler_async_with(c, s, 0);
3276 case AsyncFor_kind:
3277 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 }
Yury Selivanov75445082015-05-11 22:57:16 -04003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281}
3282
3283static int
3284unaryop(unaryop_ty op)
3285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 switch (op) {
3287 case Invert:
3288 return UNARY_INVERT;
3289 case Not:
3290 return UNARY_NOT;
3291 case UAdd:
3292 return UNARY_POSITIVE;
3293 case USub:
3294 return UNARY_NEGATIVE;
3295 default:
3296 PyErr_Format(PyExc_SystemError,
3297 "unary op %d should not be possible", op);
3298 return 0;
3299 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300}
3301
3302static int
3303binop(struct compiler *c, operator_ty op)
3304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 switch (op) {
3306 case Add:
3307 return BINARY_ADD;
3308 case Sub:
3309 return BINARY_SUBTRACT;
3310 case Mult:
3311 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003312 case MatMult:
3313 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 case Div:
3315 return BINARY_TRUE_DIVIDE;
3316 case Mod:
3317 return BINARY_MODULO;
3318 case Pow:
3319 return BINARY_POWER;
3320 case LShift:
3321 return BINARY_LSHIFT;
3322 case RShift:
3323 return BINARY_RSHIFT;
3324 case BitOr:
3325 return BINARY_OR;
3326 case BitXor:
3327 return BINARY_XOR;
3328 case BitAnd:
3329 return BINARY_AND;
3330 case FloorDiv:
3331 return BINARY_FLOOR_DIVIDE;
3332 default:
3333 PyErr_Format(PyExc_SystemError,
3334 "binary op %d should not be possible", op);
3335 return 0;
3336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337}
3338
3339static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340inplace_binop(struct compiler *c, operator_ty op)
3341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 switch (op) {
3343 case Add:
3344 return INPLACE_ADD;
3345 case Sub:
3346 return INPLACE_SUBTRACT;
3347 case Mult:
3348 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003349 case MatMult:
3350 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 case Div:
3352 return INPLACE_TRUE_DIVIDE;
3353 case Mod:
3354 return INPLACE_MODULO;
3355 case Pow:
3356 return INPLACE_POWER;
3357 case LShift:
3358 return INPLACE_LSHIFT;
3359 case RShift:
3360 return INPLACE_RSHIFT;
3361 case BitOr:
3362 return INPLACE_OR;
3363 case BitXor:
3364 return INPLACE_XOR;
3365 case BitAnd:
3366 return INPLACE_AND;
3367 case FloorDiv:
3368 return INPLACE_FLOOR_DIVIDE;
3369 default:
3370 PyErr_Format(PyExc_SystemError,
3371 "inplace binary op %d should not be possible", op);
3372 return 0;
3373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374}
3375
3376static int
3377compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3378{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003379 int op, scope;
3380 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 PyObject *dict = c->u->u_names;
3384 PyObject *mangled;
3385 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003387 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3388 !_PyUnicode_EqualToASCIIString(name, "True") &&
3389 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003390
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003391 mangled = _Py_Mangle(c->u->u_private, name);
3392 if (!mangled)
3393 return 0;
3394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 op = 0;
3396 optype = OP_NAME;
3397 scope = PyST_GetScope(c->u->u_ste, mangled);
3398 switch (scope) {
3399 case FREE:
3400 dict = c->u->u_freevars;
3401 optype = OP_DEREF;
3402 break;
3403 case CELL:
3404 dict = c->u->u_cellvars;
3405 optype = OP_DEREF;
3406 break;
3407 case LOCAL:
3408 if (c->u->u_ste->ste_type == FunctionBlock)
3409 optype = OP_FAST;
3410 break;
3411 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003412 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 optype = OP_GLOBAL;
3414 break;
3415 case GLOBAL_EXPLICIT:
3416 optype = OP_GLOBAL;
3417 break;
3418 default:
3419 /* scope can be 0 */
3420 break;
3421 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 switch (optype) {
3427 case OP_DEREF:
3428 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003429 case Load:
3430 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3431 break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003432 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003433 op = STORE_DEREF;
3434 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 case AugLoad:
3436 case AugStore:
3437 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003438 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 case Param:
3440 default:
3441 PyErr_SetString(PyExc_SystemError,
3442 "param invalid for deref variable");
3443 return 0;
3444 }
3445 break;
3446 case OP_FAST:
3447 switch (ctx) {
3448 case Load: op = LOAD_FAST; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003449 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003450 op = STORE_FAST;
3451 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 case Del: op = DELETE_FAST; break;
3453 case AugLoad:
3454 case AugStore:
3455 break;
3456 case Param:
3457 default:
3458 PyErr_SetString(PyExc_SystemError,
3459 "param invalid for local variable");
3460 return 0;
3461 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003462 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return 1;
3464 case OP_GLOBAL:
3465 switch (ctx) {
3466 case Load: op = LOAD_GLOBAL; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003467 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003468 op = STORE_GLOBAL;
3469 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 case Del: op = DELETE_GLOBAL; break;
3471 case AugLoad:
3472 case AugStore:
3473 break;
3474 case Param:
3475 default:
3476 PyErr_SetString(PyExc_SystemError,
3477 "param invalid for global variable");
3478 return 0;
3479 }
3480 break;
3481 case OP_NAME:
3482 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003483 case Load: op = LOAD_NAME; break;
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003484 case Store:
Emily Morehouse8f59ee02019-01-24 16:49:56 -07003485 op = STORE_NAME;
3486 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 case Del: op = DELETE_NAME; break;
3488 case AugLoad:
3489 case AugStore:
3490 break;
3491 case Param:
3492 default:
3493 PyErr_SetString(PyExc_SystemError,
3494 "param invalid for name variable");
3495 return 0;
3496 }
3497 break;
3498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 assert(op);
3501 arg = compiler_add_o(c, dict, mangled);
3502 Py_DECREF(mangled);
3503 if (arg < 0)
3504 return 0;
3505 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506}
3507
3508static int
3509compiler_boolop(struct compiler *c, expr_ty e)
3510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003512 int jumpi;
3513 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 assert(e->kind == BoolOp_kind);
3517 if (e->v.BoolOp.op == And)
3518 jumpi = JUMP_IF_FALSE_OR_POP;
3519 else
3520 jumpi = JUMP_IF_TRUE_OR_POP;
3521 end = compiler_new_block(c);
3522 if (end == NULL)
3523 return 0;
3524 s = e->v.BoolOp.values;
3525 n = asdl_seq_LEN(s) - 1;
3526 assert(n >= 0);
3527 for (i = 0; i < n; ++i) {
3528 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3529 ADDOP_JABS(c, jumpi, end);
3530 }
3531 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3532 compiler_use_next_block(c, end);
3533 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534}
3535
3536static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003537starunpack_helper(struct compiler *c, asdl_seq *elts,
3538 int single_op, int inner_op, int outer_op)
3539{
3540 Py_ssize_t n = asdl_seq_LEN(elts);
3541 Py_ssize_t i, nsubitems = 0, nseen = 0;
3542 for (i = 0; i < n; i++) {
3543 expr_ty elt = asdl_seq_GET(elts, i);
3544 if (elt->kind == Starred_kind) {
3545 if (nseen) {
3546 ADDOP_I(c, inner_op, nseen);
3547 nseen = 0;
3548 nsubitems++;
3549 }
3550 VISIT(c, expr, elt->v.Starred.value);
3551 nsubitems++;
3552 }
3553 else {
3554 VISIT(c, expr, elt);
3555 nseen++;
3556 }
3557 }
3558 if (nsubitems) {
3559 if (nseen) {
3560 ADDOP_I(c, inner_op, nseen);
3561 nsubitems++;
3562 }
3563 ADDOP_I(c, outer_op, nsubitems);
3564 }
3565 else
3566 ADDOP_I(c, single_op, nseen);
3567 return 1;
3568}
3569
3570static int
3571assignment_helper(struct compiler *c, asdl_seq *elts)
3572{
3573 Py_ssize_t n = asdl_seq_LEN(elts);
3574 Py_ssize_t i;
3575 int seen_star = 0;
3576 for (i = 0; i < n; i++) {
3577 expr_ty elt = asdl_seq_GET(elts, i);
3578 if (elt->kind == Starred_kind && !seen_star) {
3579 if ((i >= (1 << 8)) ||
3580 (n-i-1 >= (INT_MAX >> 8)))
3581 return compiler_error(c,
3582 "too many expressions in "
3583 "star-unpacking assignment");
3584 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3585 seen_star = 1;
3586 asdl_seq_SET(elts, i, elt->v.Starred.value);
3587 }
3588 else if (elt->kind == Starred_kind) {
3589 return compiler_error(c,
3590 "two starred expressions in assignment");
3591 }
3592 }
3593 if (!seen_star) {
3594 ADDOP_I(c, UNPACK_SEQUENCE, n);
3595 }
3596 VISIT_SEQ(c, expr, elts);
3597 return 1;
3598}
3599
3600static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601compiler_list(struct compiler *c, expr_ty e)
3602{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003603 asdl_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003604 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003605 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003607 else if (e->v.List.ctx == Load) {
3608 return starunpack_helper(c, elts,
3609 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003611 else
3612 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614}
3615
3616static int
3617compiler_tuple(struct compiler *c, expr_ty e)
3618{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003619 asdl_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003620 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003621 return assignment_helper(c, elts);
3622 }
3623 else if (e->v.Tuple.ctx == Load) {
3624 return starunpack_helper(c, elts,
3625 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3626 }
3627 else
3628 VISIT_SEQ(c, expr, elts);
3629 return 1;
3630}
3631
3632static int
3633compiler_set(struct compiler *c, expr_ty e)
3634{
3635 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3636 BUILD_SET, BUILD_SET_UNPACK);
3637}
3638
3639static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003640are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3641{
3642 Py_ssize_t i;
3643 for (i = begin; i < end; i++) {
3644 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003645 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003646 return 0;
3647 }
3648 return 1;
3649}
3650
3651static int
3652compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3653{
3654 Py_ssize_t i, n = end - begin;
3655 PyObject *keys, *key;
3656 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3657 for (i = begin; i < end; i++) {
3658 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3659 }
3660 keys = PyTuple_New(n);
3661 if (keys == NULL) {
3662 return 0;
3663 }
3664 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003665 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003666 Py_INCREF(key);
3667 PyTuple_SET_ITEM(keys, i - begin, key);
3668 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003669 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003670 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3671 }
3672 else {
3673 for (i = begin; i < end; i++) {
3674 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3675 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3676 }
3677 ADDOP_I(c, BUILD_MAP, n);
3678 }
3679 return 1;
3680}
3681
3682static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003683compiler_dict(struct compiler *c, expr_ty e)
3684{
Victor Stinner976bb402016-03-23 11:36:19 +01003685 Py_ssize_t i, n, elements;
3686 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687 int is_unpacking = 0;
3688 n = asdl_seq_LEN(e->v.Dict.values);
3689 containers = 0;
3690 elements = 0;
3691 for (i = 0; i < n; i++) {
3692 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3693 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003694 if (!compiler_subdict(c, e, i - elements, i))
3695 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003696 containers++;
3697 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003699 if (is_unpacking) {
3700 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3701 containers++;
3702 }
3703 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003704 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 }
3706 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003707 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003708 if (!compiler_subdict(c, e, n - elements, n))
3709 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003710 containers++;
3711 }
3712 /* If there is more than one dict, they need to be merged into a new
3713 * dict. If there is one dict and it's an unpacking, then it needs
3714 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003715 if (containers > 1 || is_unpacking) {
3716 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 }
3718 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719}
3720
3721static int
3722compiler_compare(struct compiler *c, expr_ty e)
3723{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003724 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003726 if (!check_compare(c, e)) {
3727 return 0;
3728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003730 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3731 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3732 if (n == 0) {
3733 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3734 ADDOP_I(c, COMPARE_OP,
3735 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, 0))));
3736 }
3737 else {
3738 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 if (cleanup == NULL)
3740 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003741 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 VISIT(c, expr,
3743 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003744 ADDOP(c, DUP_TOP);
3745 ADDOP(c, ROT_THREE);
3746 ADDOP_I(c, COMPARE_OP,
3747 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, i))));
3748 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3749 NEXT_BLOCK(c);
3750 }
3751 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3752 ADDOP_I(c, COMPARE_OP,
3753 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n))));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 basicblock *end = compiler_new_block(c);
3755 if (end == NULL)
3756 return 0;
3757 ADDOP_JREL(c, JUMP_FORWARD, end);
3758 compiler_use_next_block(c, cleanup);
3759 ADDOP(c, ROT_TWO);
3760 ADDOP(c, POP_TOP);
3761 compiler_use_next_block(c, end);
3762 }
3763 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764}
3765
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003766static PyTypeObject *
3767infer_type(expr_ty e)
3768{
3769 switch (e->kind) {
3770 case Tuple_kind:
3771 return &PyTuple_Type;
3772 case List_kind:
3773 case ListComp_kind:
3774 return &PyList_Type;
3775 case Dict_kind:
3776 case DictComp_kind:
3777 return &PyDict_Type;
3778 case Set_kind:
3779 case SetComp_kind:
3780 return &PySet_Type;
3781 case GeneratorExp_kind:
3782 return &PyGen_Type;
3783 case Lambda_kind:
3784 return &PyFunction_Type;
3785 case JoinedStr_kind:
3786 case FormattedValue_kind:
3787 return &PyUnicode_Type;
3788 case Constant_kind:
3789 return e->v.Constant.value->ob_type;
3790 default:
3791 return NULL;
3792 }
3793}
3794
3795static int
3796check_caller(struct compiler *c, expr_ty e)
3797{
3798 switch (e->kind) {
3799 case Constant_kind:
3800 case Tuple_kind:
3801 case List_kind:
3802 case ListComp_kind:
3803 case Dict_kind:
3804 case DictComp_kind:
3805 case Set_kind:
3806 case SetComp_kind:
3807 case GeneratorExp_kind:
3808 case JoinedStr_kind:
3809 case FormattedValue_kind:
3810 return compiler_warn(c, "'%.200s' object is not callable; "
3811 "perhaps you missed a comma?",
3812 infer_type(e)->tp_name);
3813 default:
3814 return 1;
3815 }
3816}
3817
3818static int
3819check_subscripter(struct compiler *c, expr_ty e)
3820{
3821 PyObject *v;
3822
3823 switch (e->kind) {
3824 case Constant_kind:
3825 v = e->v.Constant.value;
3826 if (!(v == Py_None || v == Py_Ellipsis ||
3827 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3828 PyAnySet_Check(v)))
3829 {
3830 return 1;
3831 }
3832 /* fall through */
3833 case Set_kind:
3834 case SetComp_kind:
3835 case GeneratorExp_kind:
3836 case Lambda_kind:
3837 return compiler_warn(c, "'%.200s' object is not subscriptable; "
3838 "perhaps you missed a comma?",
3839 infer_type(e)->tp_name);
3840 default:
3841 return 1;
3842 }
3843}
3844
3845static int
3846check_index(struct compiler *c, expr_ty e, slice_ty s)
3847{
3848 PyObject *v;
3849
3850 if (s->kind != Index_kind) {
3851 return 1;
3852 }
3853 PyTypeObject *index_type = infer_type(s->v.Index.value);
3854 if (index_type == NULL
3855 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3856 || index_type == &PySlice_Type) {
3857 return 1;
3858 }
3859
3860 switch (e->kind) {
3861 case Constant_kind:
3862 v = e->v.Constant.value;
3863 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3864 return 1;
3865 }
3866 /* fall through */
3867 case Tuple_kind:
3868 case List_kind:
3869 case ListComp_kind:
3870 case JoinedStr_kind:
3871 case FormattedValue_kind:
3872 return compiler_warn(c, "%.200s indices must be integers or slices, "
3873 "not %.200s; "
3874 "perhaps you missed a comma?",
3875 infer_type(e)->tp_name,
3876 index_type->tp_name);
3877 default:
3878 return 1;
3879 }
3880}
3881
Zackery Spytz97f5de02019-03-22 01:30:32 -06003882// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003884maybe_optimize_method_call(struct compiler *c, expr_ty e)
3885{
3886 Py_ssize_t argsl, i;
3887 expr_ty meth = e->v.Call.func;
3888 asdl_seq *args = e->v.Call.args;
3889
3890 /* Check that the call node is an attribute access, and that
3891 the call doesn't have keyword parameters. */
3892 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3893 asdl_seq_LEN(e->v.Call.keywords))
3894 return -1;
3895
3896 /* Check that there are no *varargs types of arguments. */
3897 argsl = asdl_seq_LEN(args);
3898 for (i = 0; i < argsl; i++) {
3899 expr_ty elt = asdl_seq_GET(args, i);
3900 if (elt->kind == Starred_kind) {
3901 return -1;
3902 }
3903 }
3904
3905 /* Alright, we can optimize the code. */
3906 VISIT(c, expr, meth->v.Attribute.value);
3907 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3908 VISIT_SEQ(c, expr, e->v.Call.args);
3909 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3910 return 1;
3911}
3912
3913static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914compiler_call(struct compiler *c, expr_ty e)
3915{
Zackery Spytz97f5de02019-03-22 01:30:32 -06003916 int ret = maybe_optimize_method_call(c, e);
3917 if (ret >= 0) {
3918 return ret;
3919 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003920 if (!check_caller(c, e->v.Call.func)) {
3921 return 0;
3922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 VISIT(c, expr, e->v.Call.func);
3924 return compiler_call_helper(c, 0,
3925 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003926 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003927}
3928
Eric V. Smith235a6f02015-09-19 14:51:32 -04003929static int
3930compiler_joined_str(struct compiler *c, expr_ty e)
3931{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003932 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003933 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3934 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003935 return 1;
3936}
3937
Eric V. Smitha78c7952015-11-03 12:45:05 -05003938/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003939static int
3940compiler_formatted_value(struct compiler *c, expr_ty e)
3941{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003942 /* Our oparg encodes 2 pieces of information: the conversion
3943 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003944
Eric V. Smitha78c7952015-11-03 12:45:05 -05003945 Convert the conversion char to 2 bits:
3946 None: 000 0x0 FVC_NONE
3947 !s : 001 0x1 FVC_STR
3948 !r : 010 0x2 FVC_REPR
3949 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003950
Eric V. Smitha78c7952015-11-03 12:45:05 -05003951 next bit is whether or not we have a format spec:
3952 yes : 100 0x4
3953 no : 000 0x0
3954 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003955
Eric V. Smitha78c7952015-11-03 12:45:05 -05003956 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003957
Eric V. Smitha78c7952015-11-03 12:45:05 -05003958 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003959 VISIT(c, expr, e->v.FormattedValue.value);
3960
Eric V. Smitha78c7952015-11-03 12:45:05 -05003961 switch (e->v.FormattedValue.conversion) {
3962 case 's': oparg = FVC_STR; break;
3963 case 'r': oparg = FVC_REPR; break;
3964 case 'a': oparg = FVC_ASCII; break;
3965 case -1: oparg = FVC_NONE; break;
3966 default:
3967 PyErr_SetString(PyExc_SystemError,
3968 "Unrecognized conversion character");
3969 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003970 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003971 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003972 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003973 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003974 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003975 }
3976
Eric V. Smitha78c7952015-11-03 12:45:05 -05003977 /* And push our opcode and oparg */
3978 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003979 return 1;
3980}
3981
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003982static int
3983compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3984{
3985 Py_ssize_t i, n = end - begin;
3986 keyword_ty kw;
3987 PyObject *keys, *key;
3988 assert(n > 0);
3989 if (n > 1) {
3990 for (i = begin; i < end; i++) {
3991 kw = asdl_seq_GET(keywords, i);
3992 VISIT(c, expr, kw->value);
3993 }
3994 keys = PyTuple_New(n);
3995 if (keys == NULL) {
3996 return 0;
3997 }
3998 for (i = begin; i < end; i++) {
3999 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4000 Py_INCREF(key);
4001 PyTuple_SET_ITEM(keys, i - begin, key);
4002 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004003 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004004 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4005 }
4006 else {
4007 /* a for loop only executes once */
4008 for (i = begin; i < end; i++) {
4009 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004010 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004011 VISIT(c, expr, kw->value);
4012 }
4013 ADDOP_I(c, BUILD_MAP, n);
4014 }
4015 return 1;
4016}
4017
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004018/* shared code between compiler_call and compiler_class */
4019static int
4020compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004021 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01004022 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004023 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004024{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004025 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03004026 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004027
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004028 /* the number of tuples and dictionaries on the stack */
4029 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
4030
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004031 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004032 nkwelts = asdl_seq_LEN(keywords);
4033
4034 for (i = 0; i < nkwelts; i++) {
4035 keyword_ty kw = asdl_seq_GET(keywords, i);
4036 if (kw->arg == NULL) {
4037 mustdictunpack = 1;
4038 break;
4039 }
4040 }
4041
4042 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004043 for (i = 0; i < nelts; i++) {
4044 expr_ty elt = asdl_seq_GET(args, i);
4045 if (elt->kind == Starred_kind) {
4046 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004047 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004048 if (nseen) {
4049 ADDOP_I(c, BUILD_TUPLE, nseen);
4050 nseen = 0;
4051 nsubargs++;
4052 }
4053 VISIT(c, expr, elt->v.Starred.value);
4054 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004055 }
4056 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004057 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004058 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004059 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004061
4062 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03004063 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004064 if (nseen) {
4065 /* Pack up any trailing positional arguments. */
4066 ADDOP_I(c, BUILD_TUPLE, nseen);
4067 nsubargs++;
4068 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004069 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004070 /* If we ended up with more than one stararg, we need
4071 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03004072 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004073 }
4074 else if (nsubargs == 0) {
4075 ADDOP_I(c, BUILD_TUPLE, 0);
4076 }
4077 nseen = 0; /* the number of keyword arguments on the stack following */
4078 for (i = 0; i < nkwelts; i++) {
4079 keyword_ty kw = asdl_seq_GET(keywords, i);
4080 if (kw->arg == NULL) {
4081 /* A keyword argument unpacking. */
4082 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004083 if (!compiler_subkwargs(c, keywords, i - nseen, i))
4084 return 0;
4085 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004086 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004087 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004088 VISIT(c, expr, kw->value);
4089 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004090 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004091 else {
4092 nseen++;
4093 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004094 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004095 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004096 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004097 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004098 return 0;
4099 nsubkwargs++;
4100 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03004101 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004102 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004103 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004104 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004105 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
4106 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004108 else if (nkwelts) {
4109 PyObject *names;
4110 VISIT_SEQ(c, keyword, keywords);
4111 names = PyTuple_New(nkwelts);
4112 if (names == NULL) {
4113 return 0;
4114 }
4115 for (i = 0; i < nkwelts; i++) {
4116 keyword_ty kw = asdl_seq_GET(keywords, i);
4117 Py_INCREF(kw->arg);
4118 PyTuple_SET_ITEM(names, i, kw->arg);
4119 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004120 ADDOP_LOAD_CONST_NEW(c, names);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004121 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004124 else {
4125 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4126 return 1;
4127 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128}
4129
Nick Coghlan650f0d02007-04-15 12:05:43 +00004130
4131/* List and set comprehensions and generator expressions work by creating a
4132 nested function to perform the actual iteration. This means that the
4133 iteration variables don't leak into the current scope.
4134 The defined function is called immediately following its definition, with the
4135 result of that call being the result of the expression.
4136 The LC/SC version returns the populated container, while the GE version is
4137 flagged in symtable.c as a generator, so it returns the generator object
4138 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004139
4140 Possible cleanups:
4141 - iterate over the generator sequence instead of using recursion
4142*/
4143
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146compiler_comprehension_generator(struct compiler *c,
4147 asdl_seq *generators, int gen_index,
4148 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004149{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004150 comprehension_ty gen;
4151 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4152 if (gen->is_async) {
4153 return compiler_async_comprehension_generator(
4154 c, generators, gen_index, elt, val, type);
4155 } else {
4156 return compiler_sync_comprehension_generator(
4157 c, generators, gen_index, elt, val, type);
4158 }
4159}
4160
4161static int
4162compiler_sync_comprehension_generator(struct compiler *c,
4163 asdl_seq *generators, int gen_index,
4164 expr_ty elt, expr_ty val, int type)
4165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* generate code for the iterator, then each of the ifs,
4167 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 comprehension_ty gen;
4170 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004171 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 start = compiler_new_block(c);
4174 skip = compiler_new_block(c);
4175 if_cleanup = compiler_new_block(c);
4176 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4179 anchor == NULL)
4180 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 if (gen_index == 0) {
4185 /* Receive outermost iter as an implicit argument */
4186 c->u->u_argcount = 1;
4187 ADDOP_I(c, LOAD_FAST, 0);
4188 }
4189 else {
4190 /* Sub-iter - calculate on the fly */
4191 VISIT(c, expr, gen->iter);
4192 ADDOP(c, GET_ITER);
4193 }
4194 compiler_use_next_block(c, start);
4195 ADDOP_JREL(c, FOR_ITER, anchor);
4196 NEXT_BLOCK(c);
4197 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 /* XXX this needs to be cleaned up...a lot! */
4200 n = asdl_seq_LEN(gen->ifs);
4201 for (i = 0; i < n; i++) {
4202 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004203 if (!compiler_jump_if(c, e, if_cleanup, 0))
4204 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 NEXT_BLOCK(c);
4206 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 if (++gen_index < asdl_seq_LEN(generators))
4209 if (!compiler_comprehension_generator(c,
4210 generators, gen_index,
4211 elt, val, type))
4212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 /* only append after the last for generator */
4215 if (gen_index >= asdl_seq_LEN(generators)) {
4216 /* comprehension specific code */
4217 switch (type) {
4218 case COMP_GENEXP:
4219 VISIT(c, expr, elt);
4220 ADDOP(c, YIELD_VALUE);
4221 ADDOP(c, POP_TOP);
4222 break;
4223 case COMP_LISTCOMP:
4224 VISIT(c, expr, elt);
4225 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4226 break;
4227 case COMP_SETCOMP:
4228 VISIT(c, expr, elt);
4229 ADDOP_I(c, SET_ADD, gen_index + 1);
4230 break;
4231 case COMP_DICTCOMP:
4232 /* With 'd[k] = v', v is evaluated before k, so we do
4233 the same. */
4234 VISIT(c, expr, val);
4235 VISIT(c, expr, elt);
4236 ADDOP_I(c, MAP_ADD, gen_index + 1);
4237 break;
4238 default:
4239 return 0;
4240 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 compiler_use_next_block(c, skip);
4243 }
4244 compiler_use_next_block(c, if_cleanup);
4245 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4246 compiler_use_next_block(c, anchor);
4247
4248 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249}
4250
4251static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004252compiler_async_comprehension_generator(struct compiler *c,
4253 asdl_seq *generators, int gen_index,
4254 expr_ty elt, expr_ty val, int type)
4255{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004256 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004257 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004258 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004259 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004260 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004261 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004262
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004263 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004264 return 0;
4265 }
4266
4267 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4268
4269 if (gen_index == 0) {
4270 /* Receive outermost iter as an implicit argument */
4271 c->u->u_argcount = 1;
4272 ADDOP_I(c, LOAD_FAST, 0);
4273 }
4274 else {
4275 /* Sub-iter - calculate on the fly */
4276 VISIT(c, expr, gen->iter);
4277 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004278 }
4279
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004280 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004281
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004282 ADDOP_JREL(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004283 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004284 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004285 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004286 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004287 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004288
4289 n = asdl_seq_LEN(gen->ifs);
4290 for (i = 0; i < n; i++) {
4291 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004292 if (!compiler_jump_if(c, e, if_cleanup, 0))
4293 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004294 NEXT_BLOCK(c);
4295 }
4296
4297 if (++gen_index < asdl_seq_LEN(generators))
4298 if (!compiler_comprehension_generator(c,
4299 generators, gen_index,
4300 elt, val, type))
4301 return 0;
4302
4303 /* only append after the last for generator */
4304 if (gen_index >= asdl_seq_LEN(generators)) {
4305 /* comprehension specific code */
4306 switch (type) {
4307 case COMP_GENEXP:
4308 VISIT(c, expr, elt);
4309 ADDOP(c, YIELD_VALUE);
4310 ADDOP(c, POP_TOP);
4311 break;
4312 case COMP_LISTCOMP:
4313 VISIT(c, expr, elt);
4314 ADDOP_I(c, LIST_APPEND, gen_index + 1);
4315 break;
4316 case COMP_SETCOMP:
4317 VISIT(c, expr, elt);
4318 ADDOP_I(c, SET_ADD, gen_index + 1);
4319 break;
4320 case COMP_DICTCOMP:
4321 /* With 'd[k] = v', v is evaluated before k, so we do
4322 the same. */
4323 VISIT(c, expr, val);
4324 VISIT(c, expr, elt);
4325 ADDOP_I(c, MAP_ADD, gen_index + 1);
4326 break;
4327 default:
4328 return 0;
4329 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004330 }
4331 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004332 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
4333
4334 compiler_use_next_block(c, except);
4335 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004336
4337 return 1;
4338}
4339
4340static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004341compiler_comprehension(struct compiler *c, expr_ty e, int type,
4342 identifier name, asdl_seq *generators, expr_ty elt,
4343 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004346 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004347 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004348 int is_async_function = c->u->u_ste->ste_coroutine;
4349 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004350
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004351 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004352
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004353 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4354 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004357 }
4358
4359 is_async_generator = c->u->u_ste->ste_coroutine;
4360
Yury Selivanovb8ab9d32017-10-06 02:58:28 -04004361 if (is_async_generator && !is_async_function && type != COMP_GENEXP) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 compiler_error(c, "asynchronous comprehension outside of "
4363 "an asynchronous function");
4364 goto error_in_scope;
4365 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 if (type != COMP_GENEXP) {
4368 int op;
4369 switch (type) {
4370 case COMP_LISTCOMP:
4371 op = BUILD_LIST;
4372 break;
4373 case COMP_SETCOMP:
4374 op = BUILD_SET;
4375 break;
4376 case COMP_DICTCOMP:
4377 op = BUILD_MAP;
4378 break;
4379 default:
4380 PyErr_Format(PyExc_SystemError,
4381 "unknown comprehension type %d", type);
4382 goto error_in_scope;
4383 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 ADDOP_I(c, op, 0);
4386 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 if (!compiler_comprehension_generator(c, generators, 0, elt,
4389 val, type))
4390 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 if (type != COMP_GENEXP) {
4393 ADDOP(c, RETURN_VALUE);
4394 }
4395
4396 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004397 qualname = c->u->u_qualname;
4398 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004400 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 goto error;
4402
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004403 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004405 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 Py_DECREF(co);
4407
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004408 VISIT(c, expr, outermost->iter);
4409
4410 if (outermost->is_async) {
4411 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004412 } else {
4413 ADDOP(c, GET_ITER);
4414 }
4415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004417
4418 if (is_async_generator && type != COMP_GENEXP) {
4419 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004420 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004421 ADDOP(c, YIELD_FROM);
4422 }
4423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004425error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004427error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004428 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 Py_XDECREF(co);
4430 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004431}
4432
4433static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434compiler_genexp(struct compiler *c, expr_ty e)
4435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 static identifier name;
4437 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004438 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if (!name)
4440 return 0;
4441 }
4442 assert(e->kind == GeneratorExp_kind);
4443 return compiler_comprehension(c, e, COMP_GENEXP, name,
4444 e->v.GeneratorExp.generators,
4445 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446}
4447
4448static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004449compiler_listcomp(struct compiler *c, expr_ty e)
4450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 static identifier name;
4452 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004453 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 if (!name)
4455 return 0;
4456 }
4457 assert(e->kind == ListComp_kind);
4458 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4459 e->v.ListComp.generators,
4460 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004461}
4462
4463static int
4464compiler_setcomp(struct compiler *c, expr_ty e)
4465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 static identifier name;
4467 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004468 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 if (!name)
4470 return 0;
4471 }
4472 assert(e->kind == SetComp_kind);
4473 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4474 e->v.SetComp.generators,
4475 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004476}
4477
4478
4479static int
4480compiler_dictcomp(struct compiler *c, expr_ty e)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 static identifier name;
4483 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004484 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 if (!name)
4486 return 0;
4487 }
4488 assert(e->kind == DictComp_kind);
4489 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4490 e->v.DictComp.generators,
4491 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004492}
4493
4494
4495static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004496compiler_visit_keyword(struct compiler *c, keyword_ty k)
4497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 VISIT(c, expr, k->value);
4499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004503 whether they are true or false.
4504
4505 Return values: 1 for true, 0 for false, -1 for non-constant.
4506 */
4507
4508static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004509expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004510{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004511 if (e->kind == Constant_kind) {
4512 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004513 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004514 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004515}
4516
Yury Selivanov75445082015-05-11 22:57:16 -04004517
4518/*
4519 Implements the async with statement.
4520
4521 The semantics outlined in that PEP are as follows:
4522
4523 async with EXPR as VAR:
4524 BLOCK
4525
4526 It is implemented roughly as:
4527
4528 context = EXPR
4529 exit = context.__aexit__ # not calling it
4530 value = await context.__aenter__()
4531 try:
4532 VAR = value # if VAR present in the syntax
4533 BLOCK
4534 finally:
4535 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004536 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004537 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004538 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004539 if not (await exit(*exc)):
4540 raise
4541 */
4542static int
4543compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4544{
4545 basicblock *block, *finally;
4546 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4547
4548 assert(s->kind == AsyncWith_kind);
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004549 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4550 return compiler_error(c, "'async with' outside async function");
4551 }
Yury Selivanov75445082015-05-11 22:57:16 -04004552
4553 block = compiler_new_block(c);
4554 finally = compiler_new_block(c);
4555 if (!block || !finally)
4556 return 0;
4557
4558 /* Evaluate EXPR */
4559 VISIT(c, expr, item->context_expr);
4560
4561 ADDOP(c, BEFORE_ASYNC_WITH);
4562 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004563 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004564 ADDOP(c, YIELD_FROM);
4565
4566 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4567
4568 /* SETUP_ASYNC_WITH pushes a finally block. */
4569 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004570 if (!compiler_push_fblock(c, ASYNC_WITH, block, finally)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004571 return 0;
4572 }
4573
4574 if (item->optional_vars) {
4575 VISIT(c, expr, item->optional_vars);
4576 }
4577 else {
4578 /* Discard result from context.__aenter__() */
4579 ADDOP(c, POP_TOP);
4580 }
4581
4582 pos++;
4583 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4584 /* BLOCK code */
4585 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4586 else if (!compiler_async_with(c, s, pos))
4587 return 0;
4588
4589 /* End of try block; start the finally block */
4590 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004591 ADDOP(c, BEGIN_FINALLY);
4592 compiler_pop_fblock(c, ASYNC_WITH, block);
Yury Selivanov75445082015-05-11 22:57:16 -04004593
Yury Selivanov75445082015-05-11 22:57:16 -04004594 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004595 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Yury Selivanov75445082015-05-11 22:57:16 -04004596 return 0;
4597
4598 /* Finally block starts; context.__exit__ is on the stack under
4599 the exception or return information. Just issue our magic
4600 opcode. */
4601 ADDOP(c, WITH_CLEANUP_START);
4602
4603 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004604 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004605 ADDOP(c, YIELD_FROM);
4606
4607 ADDOP(c, WITH_CLEANUP_FINISH);
4608
4609 /* Finally block ends. */
4610 ADDOP(c, END_FINALLY);
4611 compiler_pop_fblock(c, FINALLY_END, finally);
4612 return 1;
4613}
4614
4615
Guido van Rossumc2e20742006-02-27 22:32:47 +00004616/*
4617 Implements the with statement from PEP 343.
4618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004620
4621 with EXPR as VAR:
4622 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623
Guido van Rossumc2e20742006-02-27 22:32:47 +00004624 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625
Thomas Wouters477c8d52006-05-27 19:21:47 +00004626 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004627 exit = context.__exit__ # not calling it
4628 value = context.__enter__()
4629 try:
4630 VAR = value # if VAR present in the syntax
4631 BLOCK
4632 finally:
4633 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004634 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004635 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004636 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004637 exit(*exc)
4638 */
4639static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004640compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004641{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004642 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004643 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004644
4645 assert(s->kind == With_kind);
4646
Guido van Rossumc2e20742006-02-27 22:32:47 +00004647 block = compiler_new_block(c);
4648 finally = compiler_new_block(c);
4649 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004650 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004651
Thomas Wouters477c8d52006-05-27 19:21:47 +00004652 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004653 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004654 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004655
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004656 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004657 compiler_use_next_block(c, block);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004658 if (!compiler_push_fblock(c, WITH, block, finally)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004659 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004660 }
4661
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004662 if (item->optional_vars) {
4663 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004664 }
4665 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004667 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004668 }
4669
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004670 pos++;
4671 if (pos == asdl_seq_LEN(s->v.With.items))
4672 /* BLOCK code */
4673 VISIT_SEQ(c, stmt, s->v.With.body)
4674 else if (!compiler_with(c, s, pos))
4675 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004676
4677 /* End of try block; start the finally block */
4678 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004679 ADDOP(c, BEGIN_FINALLY);
4680 compiler_pop_fblock(c, WITH, block);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004681
Guido van Rossumc2e20742006-02-27 22:32:47 +00004682 compiler_use_next_block(c, finally);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004683 if (!compiler_push_fblock(c, FINALLY_END, finally, NULL))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004684 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004685
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004686 /* Finally block starts; context.__exit__ is on the stack under
4687 the exception or return information. Just issue our magic
4688 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004689 ADDOP(c, WITH_CLEANUP_START);
4690 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004691
4692 /* Finally block ends. */
4693 ADDOP(c, END_FINALLY);
4694 compiler_pop_fblock(c, FINALLY_END, finally);
4695 return 1;
4696}
4697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004699compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004702 case NamedExpr_kind:
4703 VISIT(c, expr, e->v.NamedExpr.value);
4704 ADDOP(c, DUP_TOP);
4705 VISIT(c, expr, e->v.NamedExpr.target);
4706 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 case BoolOp_kind:
4708 return compiler_boolop(c, e);
4709 case BinOp_kind:
4710 VISIT(c, expr, e->v.BinOp.left);
4711 VISIT(c, expr, e->v.BinOp.right);
4712 ADDOP(c, binop(c, e->v.BinOp.op));
4713 break;
4714 case UnaryOp_kind:
4715 VISIT(c, expr, e->v.UnaryOp.operand);
4716 ADDOP(c, unaryop(e->v.UnaryOp.op));
4717 break;
4718 case Lambda_kind:
4719 return compiler_lambda(c, e);
4720 case IfExp_kind:
4721 return compiler_ifexp(c, e);
4722 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004723 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004725 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 case GeneratorExp_kind:
4727 return compiler_genexp(c, e);
4728 case ListComp_kind:
4729 return compiler_listcomp(c, e);
4730 case SetComp_kind:
4731 return compiler_setcomp(c, e);
4732 case DictComp_kind:
4733 return compiler_dictcomp(c, e);
4734 case Yield_kind:
4735 if (c->u->u_ste->ste_type != FunctionBlock)
4736 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004737 if (e->v.Yield.value) {
4738 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 }
4740 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004741 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004743 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004745 case YieldFrom_kind:
4746 if (c->u->u_ste->ste_type != FunctionBlock)
4747 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004748
4749 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4750 return compiler_error(c, "'yield from' inside async function");
4751
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004752 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004753 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004754 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004755 ADDOP(c, YIELD_FROM);
4756 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004757 case Await_kind:
4758 if (c->u->u_ste->ste_type != FunctionBlock)
4759 return compiler_error(c, "'await' outside function");
4760
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004761 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4762 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004763 return compiler_error(c, "'await' outside async function");
4764
4765 VISIT(c, expr, e->v.Await.value);
4766 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004767 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004768 ADDOP(c, YIELD_FROM);
4769 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 case Compare_kind:
4771 return compiler_compare(c, e);
4772 case Call_kind:
4773 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004774 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004775 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004776 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004777 case JoinedStr_kind:
4778 return compiler_joined_str(c, e);
4779 case FormattedValue_kind:
4780 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 /* The following exprs can be assignment targets. */
4782 case Attribute_kind:
4783 if (e->v.Attribute.ctx != AugStore)
4784 VISIT(c, expr, e->v.Attribute.value);
4785 switch (e->v.Attribute.ctx) {
4786 case AugLoad:
4787 ADDOP(c, DUP_TOP);
Stefan Krahf432a322017-08-21 13:09:59 +02004788 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 case Load:
4790 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4791 break;
4792 case AugStore:
4793 ADDOP(c, ROT_TWO);
Stefan Krahf432a322017-08-21 13:09:59 +02004794 /* Fall through */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 case Store:
4796 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4797 break;
4798 case Del:
4799 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4800 break;
4801 case Param:
4802 default:
4803 PyErr_SetString(PyExc_SystemError,
4804 "param invalid in attribute expression");
4805 return 0;
4806 }
4807 break;
4808 case Subscript_kind:
4809 switch (e->v.Subscript.ctx) {
4810 case AugLoad:
4811 VISIT(c, expr, e->v.Subscript.value);
4812 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4813 break;
4814 case Load:
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004815 if (!check_subscripter(c, e->v.Subscript.value)) {
4816 return 0;
4817 }
4818 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
4819 return 0;
4820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 VISIT(c, expr, e->v.Subscript.value);
4822 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4823 break;
4824 case AugStore:
4825 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4826 break;
4827 case Store:
4828 VISIT(c, expr, e->v.Subscript.value);
4829 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4830 break;
4831 case Del:
4832 VISIT(c, expr, e->v.Subscript.value);
4833 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4834 break;
4835 case Param:
4836 default:
4837 PyErr_SetString(PyExc_SystemError,
4838 "param invalid in subscript expression");
4839 return 0;
4840 }
4841 break;
4842 case Starred_kind:
4843 switch (e->v.Starred.ctx) {
4844 case Store:
4845 /* In all legitimate cases, the Starred node was already replaced
4846 * by compiler_list/compiler_tuple. XXX: is that okay? */
4847 return compiler_error(c,
4848 "starred assignment target must be in a list or tuple");
4849 default:
4850 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004851 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 }
4853 break;
4854 case Name_kind:
4855 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4856 /* child nodes of List and Tuple will have expr_context set */
4857 case List_kind:
4858 return compiler_list(c, e);
4859 case Tuple_kind:
4860 return compiler_tuple(c, e);
4861 }
4862 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004863}
4864
4865static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004866compiler_visit_expr(struct compiler *c, expr_ty e)
4867{
4868 /* If expr e has a different line number than the last expr/stmt,
4869 set a new line number for the next instruction.
4870 */
4871 int old_lineno = c->u->u_lineno;
4872 int old_col_offset = c->u->u_col_offset;
4873 if (e->lineno != c->u->u_lineno) {
4874 c->u->u_lineno = e->lineno;
4875 c->u->u_lineno_set = 0;
4876 }
4877 /* Updating the column offset is always harmless. */
4878 c->u->u_col_offset = e->col_offset;
4879
4880 int res = compiler_visit_expr1(c, e);
4881
4882 if (old_lineno != c->u->u_lineno) {
4883 c->u->u_lineno = old_lineno;
4884 c->u->u_lineno_set = 0;
4885 }
4886 c->u->u_col_offset = old_col_offset;
4887 return res;
4888}
4889
4890static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004891compiler_augassign(struct compiler *c, stmt_ty s)
4892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 expr_ty e = s->v.AugAssign.target;
4894 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 switch (e->kind) {
4899 case Attribute_kind:
4900 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004901 AugLoad, e->lineno, e->col_offset,
4902 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 if (auge == NULL)
4904 return 0;
4905 VISIT(c, expr, auge);
4906 VISIT(c, expr, s->v.AugAssign.value);
4907 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4908 auge->v.Attribute.ctx = AugStore;
4909 VISIT(c, expr, auge);
4910 break;
4911 case Subscript_kind:
4912 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Ivan Levkivskyi9932a222019-01-22 11:18:22 +00004913 AugLoad, e->lineno, e->col_offset,
4914 e->end_lineno, e->end_col_offset, c->c_arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 if (auge == NULL)
4916 return 0;
4917 VISIT(c, expr, auge);
4918 VISIT(c, expr, s->v.AugAssign.value);
4919 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4920 auge->v.Subscript.ctx = AugStore;
4921 VISIT(c, expr, auge);
4922 break;
4923 case Name_kind:
4924 if (!compiler_nameop(c, e->v.Name.id, Load))
4925 return 0;
4926 VISIT(c, expr, s->v.AugAssign.value);
4927 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4928 return compiler_nameop(c, e->v.Name.id, Store);
4929 default:
4930 PyErr_Format(PyExc_SystemError,
4931 "invalid node type (%d) for augmented assignment",
4932 e->kind);
4933 return 0;
4934 }
4935 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004936}
4937
4938static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004939check_ann_expr(struct compiler *c, expr_ty e)
4940{
4941 VISIT(c, expr, e);
4942 ADDOP(c, POP_TOP);
4943 return 1;
4944}
4945
4946static int
4947check_annotation(struct compiler *c, stmt_ty s)
4948{
4949 /* Annotations are only evaluated in a module or class. */
4950 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4951 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4952 return check_ann_expr(c, s->v.AnnAssign.annotation);
4953 }
4954 return 1;
4955}
4956
4957static int
4958check_ann_slice(struct compiler *c, slice_ty sl)
4959{
4960 switch(sl->kind) {
4961 case Index_kind:
4962 return check_ann_expr(c, sl->v.Index.value);
4963 case Slice_kind:
4964 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4965 return 0;
4966 }
4967 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4968 return 0;
4969 }
4970 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4971 return 0;
4972 }
4973 break;
4974 default:
4975 PyErr_SetString(PyExc_SystemError,
4976 "unexpected slice kind");
4977 return 0;
4978 }
4979 return 1;
4980}
4981
4982static int
4983check_ann_subscr(struct compiler *c, slice_ty sl)
4984{
4985 /* We check that everything in a subscript is defined at runtime. */
4986 Py_ssize_t i, n;
4987
4988 switch (sl->kind) {
4989 case Index_kind:
4990 case Slice_kind:
4991 if (!check_ann_slice(c, sl)) {
4992 return 0;
4993 }
4994 break;
4995 case ExtSlice_kind:
4996 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4997 for (i = 0; i < n; i++) {
4998 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4999 switch (subsl->kind) {
5000 case Index_kind:
5001 case Slice_kind:
5002 if (!check_ann_slice(c, subsl)) {
5003 return 0;
5004 }
5005 break;
5006 case ExtSlice_kind:
5007 default:
5008 PyErr_SetString(PyExc_SystemError,
5009 "extended slice invalid in nested slice");
5010 return 0;
5011 }
5012 }
5013 break;
5014 default:
5015 PyErr_Format(PyExc_SystemError,
5016 "invalid subscript kind %d", sl->kind);
5017 return 0;
5018 }
5019 return 1;
5020}
5021
5022static int
5023compiler_annassign(struct compiler *c, stmt_ty s)
5024{
5025 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005026 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005027
5028 assert(s->kind == AnnAssign_kind);
5029
5030 /* We perform the actual assignment first. */
5031 if (s->v.AnnAssign.value) {
5032 VISIT(c, expr, s->v.AnnAssign.value);
5033 VISIT(c, expr, targ);
5034 }
5035 switch (targ->kind) {
5036 case Name_kind:
5037 /* If we have a simple name in a module or class, store annotation. */
5038 if (s->v.AnnAssign.simple &&
5039 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5040 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum95e4d582018-01-26 08:20:18 -08005041 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5042 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5043 }
5044 else {
5045 VISIT(c, expr, s->v.AnnAssign.annotation);
5046 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005047 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005048 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005050 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005051 }
5052 break;
5053 case Attribute_kind:
5054 if (!s->v.AnnAssign.value &&
5055 !check_ann_expr(c, targ->v.Attribute.value)) {
5056 return 0;
5057 }
5058 break;
5059 case Subscript_kind:
5060 if (!s->v.AnnAssign.value &&
5061 (!check_ann_expr(c, targ->v.Subscript.value) ||
5062 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5063 return 0;
5064 }
5065 break;
5066 default:
5067 PyErr_Format(PyExc_SystemError,
5068 "invalid node type (%d) for annotated assignment",
5069 targ->kind);
5070 return 0;
5071 }
5072 /* Annotation is evaluated last. */
5073 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5074 return 0;
5075 }
5076 return 1;
5077}
5078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005079/* Raises a SyntaxError and returns 0.
5080 If something goes wrong, a different exception may be raised.
5081*/
5082
5083static int
5084compiler_error(struct compiler *c, const char *errstr)
5085{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005086 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005088
Victor Stinner14e461d2013-08-26 22:28:21 +02005089 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 if (!loc) {
5091 Py_INCREF(Py_None);
5092 loc = Py_None;
5093 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005094 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005095 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 if (!u)
5097 goto exit;
5098 v = Py_BuildValue("(zO)", errstr, u);
5099 if (!v)
5100 goto exit;
5101 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005102 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 Py_DECREF(loc);
5104 Py_XDECREF(u);
5105 Py_XDECREF(v);
5106 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107}
5108
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005109/* Emits a SyntaxWarning and returns 1 on success.
5110 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5111 and returns 0.
5112*/
5113static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005114compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005115{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005116 va_list vargs;
5117#ifdef HAVE_STDARG_PROTOTYPES
5118 va_start(vargs, format);
5119#else
5120 va_start(vargs);
5121#endif
5122 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5123 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005124 if (msg == NULL) {
5125 return 0;
5126 }
5127 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5128 c->u->u_lineno, NULL, NULL) < 0)
5129 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005130 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005131 /* Replace the SyntaxWarning exception with a SyntaxError
5132 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005133 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005134 assert(PyUnicode_AsUTF8(msg) != NULL);
5135 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005136 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005137 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005138 return 0;
5139 }
5140 Py_DECREF(msg);
5141 return 1;
5142}
5143
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005144static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145compiler_handle_subscr(struct compiler *c, const char *kind,
5146 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005150 /* XXX this code is duplicated */
5151 switch (ctx) {
5152 case AugLoad: /* fall through to Load */
5153 case Load: op = BINARY_SUBSCR; break;
5154 case AugStore:/* fall through to Store */
5155 case Store: op = STORE_SUBSCR; break;
5156 case Del: op = DELETE_SUBSCR; break;
5157 case Param:
5158 PyErr_Format(PyExc_SystemError,
5159 "invalid %s kind %d in subscript\n",
5160 kind, ctx);
5161 return 0;
5162 }
5163 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00005164 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 }
5166 else if (ctx == AugStore) {
5167 ADDOP(c, ROT_THREE);
5168 }
5169 ADDOP(c, op);
5170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005171}
5172
5173static int
5174compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 int n = 2;
5177 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 /* only handles the cases where BUILD_SLICE is emitted */
5180 if (s->v.Slice.lower) {
5181 VISIT(c, expr, s->v.Slice.lower);
5182 }
5183 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005184 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005187 if (s->v.Slice.upper) {
5188 VISIT(c, expr, s->v.Slice.upper);
5189 }
5190 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005191 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 }
5193
5194 if (s->v.Slice.step) {
5195 n++;
5196 VISIT(c, expr, s->v.Slice.step);
5197 }
5198 ADDOP_I(c, BUILD_SLICE, n);
5199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005200}
5201
5202static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203compiler_visit_nested_slice(struct compiler *c, slice_ty s,
5204 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 switch (s->kind) {
5207 case Slice_kind:
5208 return compiler_slice(c, s, ctx);
5209 case Index_kind:
5210 VISIT(c, expr, s->v.Index.value);
5211 break;
5212 case ExtSlice_kind:
5213 default:
5214 PyErr_SetString(PyExc_SystemError,
5215 "extended slice invalid in nested slice");
5216 return 0;
5217 }
5218 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005219}
5220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005221static int
5222compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
5223{
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02005224 const char * kindname = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 switch (s->kind) {
5226 case Index_kind:
5227 kindname = "index";
5228 if (ctx != AugStore) {
5229 VISIT(c, expr, s->v.Index.value);
5230 }
5231 break;
5232 case Slice_kind:
5233 kindname = "slice";
5234 if (ctx != AugStore) {
5235 if (!compiler_slice(c, s, ctx))
5236 return 0;
5237 }
5238 break;
5239 case ExtSlice_kind:
5240 kindname = "extended slice";
5241 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01005242 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 for (i = 0; i < n; i++) {
5244 slice_ty sub = (slice_ty)asdl_seq_GET(
5245 s->v.ExtSlice.dims, i);
5246 if (!compiler_visit_nested_slice(c, sub, ctx))
5247 return 0;
5248 }
5249 ADDOP_I(c, BUILD_TUPLE, n);
5250 }
5251 break;
5252 default:
5253 PyErr_Format(PyExc_SystemError,
5254 "invalid subscript kind %d", s->kind);
5255 return 0;
5256 }
5257 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005258}
5259
Thomas Wouters89f507f2006-12-13 04:49:30 +00005260/* End of the compiler section, beginning of the assembler section */
5261
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005262/* do depth-first search of basic block graph, starting with block.
5263 post records the block indices in post-order.
5264
5265 XXX must handle implicit jumps from one block to next
5266*/
5267
Thomas Wouters89f507f2006-12-13 04:49:30 +00005268struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 PyObject *a_bytecode; /* string containing bytecode */
5270 int a_offset; /* offset into bytecode */
5271 int a_nblocks; /* number of reachable blocks */
5272 basicblock **a_postorder; /* list of blocks in dfs postorder */
5273 PyObject *a_lnotab; /* string containing lnotab */
5274 int a_lnotab_off; /* offset into lnotab */
5275 int a_lineno; /* last lineno of emitted instruction */
5276 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00005277};
5278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279static void
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005280dfs(struct compiler *c, basicblock *b, struct assembler *a, int end)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005281{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005282 int i, j;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005283
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005284 /* Get rid of recursion for normal control flow.
5285 Since the number of blocks is limited, unused space in a_postorder
5286 (from a_nblocks to end) can be used as a stack for still not ordered
5287 blocks. */
5288 for (j = end; b && !b->b_seen; b = b->b_next) {
5289 b->b_seen = 1;
5290 assert(a->a_nblocks < j);
5291 a->a_postorder[--j] = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005293 while (j < end) {
5294 b = a->a_postorder[j++];
5295 for (i = 0; i < b->b_iused; i++) {
5296 struct instr *instr = &b->b_instr[i];
5297 if (instr->i_jrel || instr->i_jabs)
5298 dfs(c, instr->i_target, a, j);
5299 }
5300 assert(a->a_nblocks < j);
5301 a->a_postorder[a->a_nblocks++] = b;
5302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303}
5304
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005305Py_LOCAL_INLINE(void)
5306stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005307{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005308 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005309 if (b->b_startdepth < depth) {
5310 assert(b->b_startdepth < 0);
5311 b->b_startdepth = depth;
5312 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314}
5315
5316/* Find the flow path that needs the largest stack. We assume that
5317 * cycles in the flow graph have no net effect on the stack depth.
5318 */
5319static int
5320stackdepth(struct compiler *c)
5321{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005322 basicblock *b, *entryblock = NULL;
5323 basicblock **stack, **sp;
5324 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 b->b_startdepth = INT_MIN;
5327 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005328 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005329 }
5330 if (!entryblock)
5331 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005332 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5333 if (!stack) {
5334 PyErr_NoMemory();
5335 return -1;
5336 }
5337
5338 sp = stack;
5339 stackdepth_push(&sp, entryblock, 0);
5340 while (sp != stack) {
5341 b = *--sp;
5342 int depth = b->b_startdepth;
5343 assert(depth >= 0);
5344 basicblock *next = b->b_next;
5345 for (int i = 0; i < b->b_iused; i++) {
5346 struct instr *instr = &b->b_instr[i];
5347 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5348 if (effect == PY_INVALID_STACK_EFFECT) {
5349 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
5350 Py_FatalError("PyCompile_OpcodeStackEffect()");
5351 }
5352 int new_depth = depth + effect;
5353 if (new_depth > maxdepth) {
5354 maxdepth = new_depth;
5355 }
5356 assert(depth >= 0); /* invalid code or bug in stackdepth() */
5357 if (instr->i_jrel || instr->i_jabs) {
5358 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5359 assert(effect != PY_INVALID_STACK_EFFECT);
5360 int target_depth = depth + effect;
5361 if (target_depth > maxdepth) {
5362 maxdepth = target_depth;
5363 }
5364 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005365 if (instr->i_opcode == CALL_FINALLY) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005366 assert(instr->i_target->b_startdepth >= 0);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005367 assert(instr->i_target->b_startdepth >= target_depth);
5368 depth = new_depth;
5369 continue;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005370 }
5371 stackdepth_push(&sp, instr->i_target, target_depth);
5372 }
5373 depth = new_depth;
5374 if (instr->i_opcode == JUMP_ABSOLUTE ||
5375 instr->i_opcode == JUMP_FORWARD ||
5376 instr->i_opcode == RETURN_VALUE ||
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005377 instr->i_opcode == RAISE_VARARGS)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005378 {
5379 /* remaining code is dead */
5380 next = NULL;
5381 break;
5382 }
5383 }
5384 if (next != NULL) {
5385 stackdepth_push(&sp, next, depth);
5386 }
5387 }
5388 PyObject_Free(stack);
5389 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005390}
5391
5392static int
5393assemble_init(struct assembler *a, int nblocks, int firstlineno)
5394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 memset(a, 0, sizeof(struct assembler));
5396 a->a_lineno = firstlineno;
5397 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
5398 if (!a->a_bytecode)
5399 return 0;
5400 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
5401 if (!a->a_lnotab)
5402 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005403 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 PyErr_NoMemory();
5405 return 0;
5406 }
5407 a->a_postorder = (basicblock **)PyObject_Malloc(
5408 sizeof(basicblock *) * nblocks);
5409 if (!a->a_postorder) {
5410 PyErr_NoMemory();
5411 return 0;
5412 }
5413 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005414}
5415
5416static void
5417assemble_free(struct assembler *a)
5418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 Py_XDECREF(a->a_bytecode);
5420 Py_XDECREF(a->a_lnotab);
5421 if (a->a_postorder)
5422 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005423}
5424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425static int
5426blocksize(basicblock *b)
5427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005428 int i;
5429 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005432 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005434}
5435
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00005436/* Appends a pair to the end of the line number table, a_lnotab, representing
5437 the instruction's bytecode offset and line number. See
5438 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00005439
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005440static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005441assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005443 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005444 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446
Serhiy Storchakaab874002016-09-11 13:48:15 +03005447 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 if(d_bytecode == 0 && d_lineno == 0)
5453 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 if (d_bytecode > 255) {
5456 int j, nbytes, ncodes = d_bytecode / 255;
5457 nbytes = a->a_lnotab_off + 2 * ncodes;
5458 len = PyBytes_GET_SIZE(a->a_lnotab);
5459 if (nbytes >= len) {
5460 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5461 len = nbytes;
5462 else if (len <= INT_MAX / 2)
5463 len *= 2;
5464 else {
5465 PyErr_NoMemory();
5466 return 0;
5467 }
5468 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5469 return 0;
5470 }
5471 lnotab = (unsigned char *)
5472 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5473 for (j = 0; j < ncodes; j++) {
5474 *lnotab++ = 255;
5475 *lnotab++ = 0;
5476 }
5477 d_bytecode -= ncodes * 255;
5478 a->a_lnotab_off += ncodes * 2;
5479 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005480 assert(0 <= d_bytecode && d_bytecode <= 255);
5481
5482 if (d_lineno < -128 || 127 < d_lineno) {
5483 int j, nbytes, ncodes, k;
5484 if (d_lineno < 0) {
5485 k = -128;
5486 /* use division on positive numbers */
5487 ncodes = (-d_lineno) / 128;
5488 }
5489 else {
5490 k = 127;
5491 ncodes = d_lineno / 127;
5492 }
5493 d_lineno -= ncodes * k;
5494 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 nbytes = a->a_lnotab_off + 2 * ncodes;
5496 len = PyBytes_GET_SIZE(a->a_lnotab);
5497 if (nbytes >= len) {
5498 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5499 len = nbytes;
5500 else if (len <= INT_MAX / 2)
5501 len *= 2;
5502 else {
5503 PyErr_NoMemory();
5504 return 0;
5505 }
5506 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5507 return 0;
5508 }
5509 lnotab = (unsigned char *)
5510 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5511 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005512 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 d_bytecode = 0;
5514 for (j = 1; j < ncodes; j++) {
5515 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005516 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 a->a_lnotab_off += ncodes * 2;
5519 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005520 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 len = PyBytes_GET_SIZE(a->a_lnotab);
5523 if (a->a_lnotab_off + 2 >= len) {
5524 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5525 return 0;
5526 }
5527 lnotab = (unsigned char *)
5528 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 a->a_lnotab_off += 2;
5531 if (d_bytecode) {
5532 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005533 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 }
5535 else { /* First line of a block; def stmt, etc. */
5536 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005537 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 }
5539 a->a_lineno = i->i_lineno;
5540 a->a_lineno_off = a->a_offset;
5541 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005542}
5543
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005544/* assemble_emit()
5545 Extend the bytecode with a new instruction.
5546 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005547*/
5548
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005549static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005550assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005551{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005552 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005554 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005556 arg = i->i_oparg;
5557 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 if (i->i_lineno && !assemble_lnotab(a, i))
5559 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005560 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 if (len > PY_SSIZE_T_MAX / 2)
5562 return 0;
5563 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5564 return 0;
5565 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005566 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005568 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005570}
5571
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005572static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005573assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005575 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005576 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 /* Compute the size of each block and fixup jump args.
5580 Replace block pointer with position in bytecode. */
5581 do {
5582 totsize = 0;
5583 for (i = a->a_nblocks - 1; i >= 0; i--) {
5584 b = a->a_postorder[i];
5585 bsize = blocksize(b);
5586 b->b_offset = totsize;
5587 totsize += bsize;
5588 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005589 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5591 bsize = b->b_offset;
5592 for (i = 0; i < b->b_iused; i++) {
5593 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005594 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 /* Relative jumps are computed relative to
5596 the instruction pointer after fetching
5597 the jump instruction.
5598 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005599 bsize += isize;
5600 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005602 if (instr->i_jrel) {
5603 instr->i_oparg -= bsize;
5604 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005605 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005606 if (instrsize(instr->i_oparg) != isize) {
5607 extended_arg_recompile = 1;
5608 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005610 }
5611 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005613 /* XXX: This is an awful hack that could hurt performance, but
5614 on the bright side it should work until we come up
5615 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005617 The issue is that in the first loop blocksize() is called
5618 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005619 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005622 So we loop until we stop seeing new EXTENDED_ARGs.
5623 The only EXTENDED_ARGs that could be popping up are
5624 ones in jump instructions. So this should converge
5625 fairly quickly.
5626 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005627 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005628}
5629
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005630static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005631dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005634 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 tuple = PyTuple_New(size);
5637 if (tuple == NULL)
5638 return NULL;
5639 while (PyDict_Next(dict, &pos, &k, &v)) {
5640 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005641 Py_INCREF(k);
5642 assert((i - offset) < size);
5643 assert((i - offset) >= 0);
5644 PyTuple_SET_ITEM(tuple, i - offset, k);
5645 }
5646 return tuple;
5647}
5648
5649static PyObject *
5650consts_dict_keys_inorder(PyObject *dict)
5651{
5652 PyObject *consts, *k, *v;
5653 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5654
5655 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5656 if (consts == NULL)
5657 return NULL;
5658 while (PyDict_Next(dict, &pos, &k, &v)) {
5659 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005660 /* The keys of the dictionary can be tuples wrapping a contant.
5661 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5662 * the object we want is always second. */
5663 if (PyTuple_CheckExact(k)) {
5664 k = PyTuple_GET_ITEM(k, 1);
5665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005667 assert(i < size);
5668 assert(i >= 0);
5669 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005671 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005672}
5673
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005674static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005675compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005678 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005680 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 if (ste->ste_nested)
5682 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005683 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005685 if (!ste->ste_generator && ste->ste_coroutine)
5686 flags |= CO_COROUTINE;
5687 if (ste->ste_generator && ste->ste_coroutine)
5688 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 if (ste->ste_varargs)
5690 flags |= CO_VARARGS;
5691 if (ste->ste_varkeywords)
5692 flags |= CO_VARKEYWORDS;
5693 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 /* (Only) inherit compilerflags in PyCF_MASK */
5696 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005699}
5700
INADA Naokic2e16072018-11-26 21:23:22 +09005701// Merge *tuple* with constant cache.
5702// Unlike merge_consts_recursive(), this function doesn't work recursively.
5703static int
5704merge_const_tuple(struct compiler *c, PyObject **tuple)
5705{
5706 assert(PyTuple_CheckExact(*tuple));
5707
5708 PyObject *key = _PyCode_ConstantKey(*tuple);
5709 if (key == NULL) {
5710 return 0;
5711 }
5712
5713 // t is borrowed reference
5714 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5715 Py_DECREF(key);
5716 if (t == NULL) {
5717 return 0;
5718 }
5719 if (t == key) { // tuple is new constant.
5720 return 1;
5721 }
5722
5723 PyObject *u = PyTuple_GET_ITEM(t, 1);
5724 Py_INCREF(u);
5725 Py_DECREF(*tuple);
5726 *tuple = u;
5727 return 1;
5728}
5729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005730static PyCodeObject *
5731makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 PyObject *tmp;
5734 PyCodeObject *co = NULL;
5735 PyObject *consts = NULL;
5736 PyObject *names = NULL;
5737 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 PyObject *name = NULL;
5739 PyObject *freevars = NULL;
5740 PyObject *cellvars = NULL;
5741 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005742 Py_ssize_t nlocals;
5743 int nlocals_int;
5744 int flags;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005745 int argcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005746
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005747 consts = consts_dict_keys_inorder(c->u->u_consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 names = dict_keys_inorder(c->u->u_names, 0);
5749 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5750 if (!consts || !names || !varnames)
5751 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5754 if (!cellvars)
5755 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005756 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 if (!freevars)
5758 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005759
INADA Naokic2e16072018-11-26 21:23:22 +09005760 if (!merge_const_tuple(c, &names) ||
5761 !merge_const_tuple(c, &varnames) ||
5762 !merge_const_tuple(c, &cellvars) ||
5763 !merge_const_tuple(c, &freevars))
5764 {
5765 goto error;
5766 }
5767
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005768 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005769 assert(nlocals < INT_MAX);
5770 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 flags = compute_code_flags(c);
5773 if (flags < 0)
5774 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5777 if (!bytecode)
5778 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5781 if (!tmp)
5782 goto error;
5783 Py_DECREF(consts);
5784 consts = tmp;
INADA Naokic2e16072018-11-26 21:23:22 +09005785 if (!merge_const_tuple(c, &consts)) {
5786 goto error;
5787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788
Victor Stinnerf8e32212013-11-19 23:56:34 +01005789 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5790 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005791 maxdepth = stackdepth(c);
5792 if (maxdepth < 0) {
5793 goto error;
5794 }
Victor Stinnerf8e32212013-11-19 23:56:34 +01005795 co = PyCode_New(argcount, kwonlyargcount,
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005796 nlocals_int, maxdepth, flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 bytecode, consts, names, varnames,
5798 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005799 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 c->u->u_firstlineno,
5801 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005802 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 Py_XDECREF(consts);
5804 Py_XDECREF(names);
5805 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 Py_XDECREF(name);
5807 Py_XDECREF(freevars);
5808 Py_XDECREF(cellvars);
5809 Py_XDECREF(bytecode);
5810 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005811}
5812
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005813
5814/* For debugging purposes only */
5815#if 0
5816static void
5817dump_instr(const struct instr *i)
5818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 const char *jrel = i->i_jrel ? "jrel " : "";
5820 const char *jabs = i->i_jabs ? "jabs " : "";
5821 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005824 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005825 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005826 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5828 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005829}
5830
5831static void
5832dump_basicblock(const basicblock *b)
5833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 const char *seen = b->b_seen ? "seen " : "";
5835 const char *b_return = b->b_return ? "return " : "";
5836 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5837 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5838 if (b->b_instr) {
5839 int i;
5840 for (i = 0; i < b->b_iused; i++) {
5841 fprintf(stderr, " [%02d] ", i);
5842 dump_instr(b->b_instr + i);
5843 }
5844 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005845}
5846#endif
5847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005848static PyCodeObject *
5849assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 basicblock *b, *entryblock;
5852 struct assembler a;
5853 int i, j, nblocks;
5854 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 /* Make sure every block that falls off the end returns None.
5857 XXX NEXT_BLOCK() isn't quite right, because if the last
5858 block ends with a jump or return b_next shouldn't set.
5859 */
5860 if (!c->u->u_curblock->b_return) {
5861 NEXT_BLOCK(c);
5862 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005863 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 ADDOP(c, RETURN_VALUE);
5865 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 nblocks = 0;
5868 entryblock = NULL;
5869 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5870 nblocks++;
5871 entryblock = b;
5872 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 /* Set firstlineno if it wasn't explicitly set. */
5875 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005876 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5878 else
5879 c->u->u_firstlineno = 1;
5880 }
5881 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5882 goto error;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005883 dfs(c, entryblock, &a, nblocks);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 /* Can't modify the bytecode after computing jump offsets. */
5886 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 /* Emit code in reverse postorder from dfs. */
5889 for (i = a.a_nblocks - 1; i >= 0; i--) {
5890 b = a.a_postorder[i];
5891 for (j = 0; j < b->b_iused; j++)
5892 if (!assemble_emit(&a, &b->b_instr[j]))
5893 goto error;
5894 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5897 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005898 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005899 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005901 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005902 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 assemble_free(&a);
5904 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005905}
Georg Brandl8334fd92010-12-04 10:26:46 +00005906
5907#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005908PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00005909PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5910 PyArena *arena)
5911{
5912 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5913}