blob: 17fef314829a8edaf3c9afcfc66a2e514ef19a7a [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"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030032#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000034#define DEFAULT_BLOCK_SIZE 16
35#define DEFAULT_BLOCKS 8
36#define DEFAULT_CODE_SIZE 128
37#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000038
Nick Coghlan650f0d02007-04-15 12:05:43 +000039#define COMP_GENEXP 0
40#define COMP_LISTCOMP 1
41#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000042#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000044struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 unsigned i_jabs : 1;
46 unsigned i_jrel : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 unsigned char i_opcode;
48 int i_oparg;
49 struct basicblock_ *i_target; /* target block (if jump instruction) */
50 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000051};
52
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 /* Each basicblock in a compilation unit is linked via b_list in the
55 reverse order that the block are allocated. b_list points to the next
56 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 struct basicblock_ *b_list;
58 /* number of instructions used */
59 int b_iused;
60 /* length of instruction array (b_instr) */
61 int b_ialloc;
62 /* pointer to an array of instructions, initially NULL */
63 struct instr *b_instr;
64 /* If b_next is non-NULL, it is a pointer to the next
65 block reached by normal control flow. */
66 struct basicblock_ *b_next;
67 /* b_seen is used to perform a DFS of basicblocks. */
68 unsigned b_seen : 1;
69 /* b_return is true if a RETURN_VALUE opcode is inserted. */
70 unsigned b_return : 1;
71 /* depth of stack upon entry of block, computed by stackdepth() */
72 int b_startdepth;
73 /* instruction offset for block, computed by assemble_jump_offsets() */
74 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075} basicblock;
76
77/* fblockinfo tracks the current frame block.
78
Jeremy Hyltone9357b22006-03-01 15:47:05 +000079A frame block is used to handle loops, try/except, and try/finally.
80It's called a frame block to distinguish it from a basic block in the
81compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082*/
83
84enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
85
86struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 enum fblocktype fb_type;
88 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089};
90
Antoine Pitrou86a36b52011-11-25 18:56:07 +010091enum {
92 COMPILER_SCOPE_MODULE,
93 COMPILER_SCOPE_CLASS,
94 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -040095 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040096 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010097 COMPILER_SCOPE_COMPREHENSION,
98};
99
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 int u_scope_type;
109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 /* The following fields are dicts that map objects to
111 the index of them in co_XXX. The index is used as
112 the argument for opcodes that refer to those collections.
113 */
114 PyObject *u_consts; /* all constants */
115 PyObject *u_names; /* all names */
116 PyObject *u_varnames; /* local variables */
117 PyObject *u_cellvars; /* cell variables */
118 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
Victor Stinnerf8e32212013-11-19 23:56:34 +0100122 Py_ssize_t u_argcount; /* number of arguments for block */
123 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 /* Pointer to the most recently allocated block. By following b_list
125 members, you can reach all early allocated blocks. */
126 basicblock *u_blocks;
127 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int u_nfblocks;
130 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int u_firstlineno; /* the first lineno of the block */
133 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000134 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 int u_lineno_set; /* boolean to indicate whether instr
136 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137};
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000144
145Note that we don't track recursion levels during compilation - the
146task of detecting and rejecting excessive levels of nesting is
147handled by the symbol analysis pass.
148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000149*/
150
151struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200152 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 struct symtable *c_st;
154 PyFutureFeatures *c_future; /* pointer to module's __future__ */
155 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 int c_interactive; /* true if in interactive mode */
159 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 struct compiler_unit *u; /* compiler state for current block */
162 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
163 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164};
165
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100166static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100172static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static int compiler_error(struct compiler *, const char *);
175static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
176
177static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
178static int compiler_visit_stmt(struct compiler *, stmt_ty);
179static int compiler_visit_keyword(struct compiler *, keyword_ty);
180static int compiler_visit_expr(struct compiler *, expr_ty);
181static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700182static int compiler_annassign(struct compiler *, stmt_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000194static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500196static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400197static int compiler_async_with(struct compiler *, stmt_ty, int);
198static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100199static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400201 asdl_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400203static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000204
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700205static int compiler_sync_comprehension_generator(
206 struct compiler *c,
207 asdl_seq *generators, int gen_index,
208 expr_ty elt, expr_ty val, int type);
209
210static int compiler_async_comprehension_generator(
211 struct compiler *c,
212 asdl_seq *generators, int gen_index,
213 expr_ty elt, expr_ty val, int type);
214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static PyCodeObject *assemble(struct compiler *, int addNone);
216static PyObject *__doc__;
217
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400218#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Name mangling: __private becomes _classname__private.
224 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 PyObject *result;
226 size_t nlen, plen, ipriv;
227 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200229 PyUnicode_READ_CHAR(ident, 0) != '_' ||
230 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_INCREF(ident);
232 return ident;
233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 nlen = PyUnicode_GET_LENGTH(ident);
235 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 The only time a name with a dot can occur is when
239 we are compiling an import statement that has a
240 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 TODO(jhylton): Decide whether we want to support
243 mangling of the module name, e.g. __M.X.
244 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200245 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
246 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
247 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_INCREF(ident);
249 return ident; /* Don't mangle __whatever__ */
250 }
251 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200252 ipriv = 0;
253 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
254 ipriv++;
255 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_INCREF(ident);
257 return ident; /* Don't mangle if class is just underscores */
258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000260
Antoine Pitrou55bff892013-04-06 21:21:04 +0200261 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
262 PyErr_SetString(PyExc_OverflowError,
263 "private identifier too large to be mangled");
264 return NULL;
265 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200267 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
268 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
269 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
270
271 result = PyUnicode_New(1 + nlen + plen, maxchar);
272 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
275 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200276 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
277 Py_DECREF(result);
278 return NULL;
279 }
280 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
281 Py_DECREF(result);
282 return NULL;
283 }
Victor Stinner8f825062012-04-27 13:55:39 +0200284 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200285 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000286}
287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288static int
289compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 c->c_stack = PyList_New(0);
294 if (!c->c_stack)
295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298}
299
300PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200301PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
302 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 struct compiler c;
305 PyCodeObject *co = NULL;
306 PyCompilerFlags local_flags;
307 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!__doc__) {
310 __doc__ = PyUnicode_InternFromString("__doc__");
311 if (!__doc__)
312 return NULL;
313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!compiler_init(&c))
316 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200317 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 c.c_filename = filename;
319 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200320 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (c.c_future == NULL)
322 goto finally;
323 if (!flags) {
324 local_flags.cf_flags = 0;
325 flags = &local_flags;
326 }
327 merged = c.c_future->ff_features | flags->cf_flags;
328 c.c_future->ff_features = merged;
329 flags->cf_flags = merged;
330 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000331 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (c.c_st == NULL) {
336 if (!PyErr_Occurred())
337 PyErr_SetString(PyExc_SystemError, "no symtable");
338 goto finally;
339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Thomas Wouters1175c432006-02-27 22:49:54 +0000343 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 compiler_free(&c);
345 assert(co || PyErr_Occurred());
346 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347}
348
349PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200350PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
351 int optimize, PyArena *arena)
352{
353 PyObject *filename;
354 PyCodeObject *co;
355 filename = PyUnicode_DecodeFSDefault(filename_str);
356 if (filename == NULL)
357 return NULL;
358 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
359 Py_DECREF(filename);
360 return co;
361
362}
363
364PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365PyNode_Compile(struct _node *n, const char *filename)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyCodeObject *co = NULL;
368 mod_ty mod;
369 PyArena *arena = PyArena_New();
370 if (!arena)
371 return NULL;
372 mod = PyAST_FromNode(n, NULL, filename, arena);
373 if (mod)
374 co = PyAST_Compile(mod, filename, NULL, arena);
375 PyArena_Free(arena);
376 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000377}
378
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (c->c_st)
383 PySymtable_Free(c->c_st);
384 if (c->c_future)
385 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000388}
389
Guido van Rossum79f25d91997-04-29 20:08:16 +0000390static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000391list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ssize_t i, n;
394 PyObject *v, *k;
395 PyObject *dict = PyDict_New();
396 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 n = PyList_Size(list);
399 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100400 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (!v) {
402 Py_DECREF(dict);
403 return NULL;
404 }
405 k = PyList_GET_ITEM(list, i);
Victor Stinnerefb24132016-01-22 12:33:12 +0100406 k = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
408 Py_XDECREF(k);
409 Py_DECREF(v);
410 Py_DECREF(dict);
411 return NULL;
412 }
413 Py_DECREF(k);
414 Py_DECREF(v);
415 }
416 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417}
418
419/* Return new dict containing names from src that match scope(s).
420
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000421src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000423values are integers, starting at offset and increasing by one for
424each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000425*/
426
427static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100428dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700430 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500432 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 assert(offset >= 0);
435 if (dest == NULL)
436 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000437
Meador Inge2ca63152012-07-18 14:20:11 -0500438 /* Sort the keys so that we have a deterministic order on the indexes
439 saved in the returned dictionary. These indexes are used as indexes
440 into the free and cell var storage. Therefore if they aren't
441 deterministic, then the generated bytecode is not deterministic.
442 */
443 sorted_keys = PyDict_Keys(src);
444 if (sorted_keys == NULL)
445 return NULL;
446 if (PyList_Sort(sorted_keys) != 0) {
447 Py_DECREF(sorted_keys);
448 return NULL;
449 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500450 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500451
452 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* XXX this should probably be a macro in symtable.h */
454 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500455 k = PyList_GET_ITEM(sorted_keys, key_i);
456 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(PyLong_Check(v));
458 vi = PyLong_AS_LONG(v);
459 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (scope == scope_type || vi & flag) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100462 PyObject *tuple, *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500464 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_DECREF(dest);
466 return NULL;
467 }
468 i++;
Victor Stinnerefb24132016-01-22 12:33:12 +0100469 tuple = _PyCode_ConstantKey(k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500471 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_DECREF(item);
473 Py_DECREF(dest);
474 Py_XDECREF(tuple);
475 return NULL;
476 }
477 Py_DECREF(item);
478 Py_DECREF(tuple);
479 }
480 }
Meador Inge2ca63152012-07-18 14:20:11 -0500481 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000483}
484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485static void
486compiler_unit_check(struct compiler_unit *u)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 basicblock *block;
489 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700490 assert((uintptr_t)block != 0xcbcbcbcbU);
491 assert((uintptr_t)block != 0xfbfbfbfbU);
492 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (block->b_instr != NULL) {
494 assert(block->b_ialloc > 0);
495 assert(block->b_iused > 0);
496 assert(block->b_ialloc >= block->b_iused);
497 }
498 else {
499 assert (block->b_iused == 0);
500 assert (block->b_ialloc == 0);
501 }
502 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503}
504
505static void
506compiler_unit_free(struct compiler_unit *u)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 compiler_unit_check(u);
511 b = u->u_blocks;
512 while (b != NULL) {
513 if (b->b_instr)
514 PyObject_Free((void *)b->b_instr);
515 next = b->b_list;
516 PyObject_Free((void *)b);
517 b = next;
518 }
519 Py_CLEAR(u->u_ste);
520 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400521 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_CLEAR(u->u_consts);
523 Py_CLEAR(u->u_names);
524 Py_CLEAR(u->u_varnames);
525 Py_CLEAR(u->u_freevars);
526 Py_CLEAR(u->u_cellvars);
527 Py_CLEAR(u->u_private);
528 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529}
530
531static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100532compiler_enter_scope(struct compiler *c, identifier name,
533 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100536 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
539 struct compiler_unit));
540 if (!u) {
541 PyErr_NoMemory();
542 return 0;
543 }
544 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100545 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 u->u_argcount = 0;
547 u->u_kwonlyargcount = 0;
548 u->u_ste = PySymtable_Lookup(c->c_st, key);
549 if (!u->u_ste) {
550 compiler_unit_free(u);
551 return 0;
552 }
553 Py_INCREF(name);
554 u->u_name = name;
555 u->u_varnames = list2dict(u->u_ste->ste_varnames);
556 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
557 if (!u->u_varnames || !u->u_cellvars) {
558 compiler_unit_free(u);
559 return 0;
560 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500561 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000562 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500563 _Py_IDENTIFIER(__class__);
564 PyObject *tuple, *name, *zero;
565 int res;
566 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200567 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500568 name = _PyUnicode_FromId(&PyId___class__);
569 if (!name) {
570 compiler_unit_free(u);
571 return 0;
572 }
Victor Stinnerefb24132016-01-22 12:33:12 +0100573 tuple = _PyCode_ConstantKey(name);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500574 if (!tuple) {
575 compiler_unit_free(u);
576 return 0;
577 }
578 zero = PyLong_FromLong(0);
579 if (!zero) {
580 Py_DECREF(tuple);
581 compiler_unit_free(u);
582 return 0;
583 }
584 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
585 Py_DECREF(tuple);
586 Py_DECREF(zero);
587 if (res < 0) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200594 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (!u->u_freevars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 u->u_blocks = NULL;
601 u->u_nfblocks = 0;
602 u->u_firstlineno = lineno;
603 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000604 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_lineno_set = 0;
606 u->u_consts = PyDict_New();
607 if (!u->u_consts) {
608 compiler_unit_free(u);
609 return 0;
610 }
611 u->u_names = PyDict_New();
612 if (!u->u_names) {
613 compiler_unit_free(u);
614 return 0;
615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Push the old compiler_unit on the stack. */
620 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400621 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
623 Py_XDECREF(capsule);
624 compiler_unit_free(u);
625 return 0;
626 }
627 Py_DECREF(capsule);
628 u->u_private = c->u->u_private;
629 Py_XINCREF(u->u_private);
630 }
631 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100634
635 block = compiler_new_block(c);
636 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100638 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000639
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400640 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
641 if (!compiler_set_qualname(c))
642 return 0;
643 }
644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646}
647
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000648static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649compiler_exit_scope(struct compiler *c)
650{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100651 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 c->c_nestlevel--;
655 compiler_unit_free(c->u);
656 /* Restore c->u to the parent unit. */
657 n = PyList_GET_SIZE(c->c_stack) - 1;
658 if (n >= 0) {
659 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400660 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 assert(c->u);
662 /* we are deleting from a list so this really shouldn't fail */
663 if (PySequence_DelItem(c->c_stack, n) < 0)
664 Py_FatalError("compiler_exit_scope()");
665 compiler_unit_check(c->u);
666 }
667 else
668 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400672static int
673compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100674{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100675 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400676 _Py_static_string(dot_locals, ".<locals>");
677 Py_ssize_t stack_size;
678 struct compiler_unit *u = c->u;
679 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100680
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400681 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100682 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400683 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400684 if (stack_size > 1) {
685 int scope, force_global = 0;
686 struct compiler_unit *parent;
687 PyObject *mangled, *capsule;
688
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400689 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400690 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691 assert(parent);
692
Yury Selivanov75445082015-05-11 22:57:16 -0400693 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
694 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
695 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696 assert(u->u_name);
697 mangled = _Py_Mangle(parent->u_private, u->u_name);
698 if (!mangled)
699 return 0;
700 scope = PyST_GetScope(parent->u_ste, mangled);
701 Py_DECREF(mangled);
702 assert(scope != GLOBAL_IMPLICIT);
703 if (scope == GLOBAL_EXPLICIT)
704 force_global = 1;
705 }
706
707 if (!force_global) {
708 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400709 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400710 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
711 dot_locals_str = _PyUnicode_FromId(&dot_locals);
712 if (dot_locals_str == NULL)
713 return 0;
714 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
715 if (base == NULL)
716 return 0;
717 }
718 else {
719 Py_INCREF(parent->u_qualname);
720 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400721 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100722 }
723 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400724
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400725 if (base != NULL) {
726 dot_str = _PyUnicode_FromId(&dot);
727 if (dot_str == NULL) {
728 Py_DECREF(base);
729 return 0;
730 }
731 name = PyUnicode_Concat(base, dot_str);
732 Py_DECREF(base);
733 if (name == NULL)
734 return 0;
735 PyUnicode_Append(&name, u->u_name);
736 if (name == NULL)
737 return 0;
738 }
739 else {
740 Py_INCREF(u->u_name);
741 name = u->u_name;
742 }
743 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100744
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400745 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746}
747
Eric V. Smith235a6f02015-09-19 14:51:32 -0400748
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749/* Allocate a new block and return a pointer to it.
750 Returns NULL on error.
751*/
752
753static basicblock *
754compiler_new_block(struct compiler *c)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 basicblock *b;
757 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 u = c->u;
760 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
761 if (b == NULL) {
762 PyErr_NoMemory();
763 return NULL;
764 }
765 memset((void *)b, 0, sizeof(basicblock));
766 /* Extend the singly linked list of blocks with new block. */
767 b->b_list = u->u_blocks;
768 u->u_blocks = b;
769 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000770}
771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773compiler_next_block(struct compiler *c)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 basicblock *block = compiler_new_block(c);
776 if (block == NULL)
777 return NULL;
778 c->u->u_curblock->b_next = block;
779 c->u->u_curblock = block;
780 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781}
782
783static basicblock *
784compiler_use_next_block(struct compiler *c, basicblock *block)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 assert(block != NULL);
787 c->u->u_curblock->b_next = block;
788 c->u->u_curblock = block;
789 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790}
791
792/* Returns the offset of the next instruction in the current block's
793 b_instr array. Resizes the b_instr as necessary.
794 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000795*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796
797static int
798compiler_next_instr(struct compiler *c, basicblock *b)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 assert(b != NULL);
801 if (b->b_instr == NULL) {
802 b->b_instr = (struct instr *)PyObject_Malloc(
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 if (b->b_instr == NULL) {
805 PyErr_NoMemory();
806 return -1;
807 }
808 b->b_ialloc = DEFAULT_BLOCK_SIZE;
809 memset((char *)b->b_instr, 0,
810 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
811 }
812 else if (b->b_iused == b->b_ialloc) {
813 struct instr *tmp;
814 size_t oldsize, newsize;
815 oldsize = b->b_ialloc * sizeof(struct instr);
816 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000817
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700818 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyErr_NoMemory();
820 return -1;
821 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (newsize == 0) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_ialloc <<= 1;
828 tmp = (struct instr *)PyObject_Realloc(
829 (void *)b->b_instr, newsize);
830 if (tmp == NULL) {
831 PyErr_NoMemory();
832 return -1;
833 }
834 b->b_instr = tmp;
835 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
836 }
837 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838}
839
Christian Heimes2202f872008-02-06 14:31:34 +0000840/* Set the i_lineno member of the instruction at offset off if the
841 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842 already been set. If it has been set, the call has no effect.
843
Christian Heimes2202f872008-02-06 14:31:34 +0000844 The line number is reset in the following cases:
845 - when entering a new scope
846 - on each statement
847 - on each expression that start a new line
848 - before the "except" clause
849 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000850*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000852static void
853compiler_set_lineno(struct compiler *c, int off)
854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 basicblock *b;
856 if (c->u->u_lineno_set)
857 return;
858 c->u->u_lineno_set = 1;
859 b = c->u->u_curblock;
860 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000861}
862
Larry Hastings3a907972013-11-23 14:49:22 -0800863int
864PyCompile_OpcodeStackEffect(int opcode, int oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 switch (opcode) {
867 case POP_TOP:
868 return -1;
869 case ROT_TWO:
870 case ROT_THREE:
871 return 0;
872 case DUP_TOP:
873 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000874 case DUP_TOP_TWO:
875 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 case UNARY_POSITIVE:
878 case UNARY_NEGATIVE:
879 case UNARY_NOT:
880 case UNARY_INVERT:
881 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 case SET_ADD:
884 case LIST_APPEND:
885 return -1;
886 case MAP_ADD:
887 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 case BINARY_POWER:
890 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400891 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 case BINARY_MODULO:
893 case BINARY_ADD:
894 case BINARY_SUBTRACT:
895 case BINARY_SUBSCR:
896 case BINARY_FLOOR_DIVIDE:
897 case BINARY_TRUE_DIVIDE:
898 return -1;
899 case INPLACE_FLOOR_DIVIDE:
900 case INPLACE_TRUE_DIVIDE:
901 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 case INPLACE_ADD:
904 case INPLACE_SUBTRACT:
905 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400906 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case INPLACE_MODULO:
908 return -1;
909 case STORE_SUBSCR:
910 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 case DELETE_SUBSCR:
912 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case BINARY_LSHIFT:
915 case BINARY_RSHIFT:
916 case BINARY_AND:
917 case BINARY_XOR:
918 case BINARY_OR:
919 return -1;
920 case INPLACE_POWER:
921 return -1;
922 case GET_ITER:
923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 case PRINT_EXPR:
926 return -1;
927 case LOAD_BUILD_CLASS:
928 return 1;
929 case INPLACE_LSHIFT:
930 case INPLACE_RSHIFT:
931 case INPLACE_AND:
932 case INPLACE_XOR:
933 case INPLACE_OR:
934 return -1;
935 case BREAK_LOOP:
936 return 0;
937 case SETUP_WITH:
938 return 7;
Yury Selivanov75445082015-05-11 22:57:16 -0400939 case WITH_CLEANUP_START:
940 return 1;
941 case WITH_CLEANUP_FINISH:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 case RETURN_VALUE:
944 return -1;
945 case IMPORT_STAR:
946 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700947 case SETUP_ANNOTATIONS:
948 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case YIELD_VALUE:
950 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500951 case YIELD_FROM:
952 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case POP_BLOCK:
954 return 0;
955 case POP_EXCEPT:
956 return 0; /* -3 except if bad bytecode */
957 case END_FINALLY:
958 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case STORE_NAME:
961 return -1;
962 case DELETE_NAME:
963 return 0;
964 case UNPACK_SEQUENCE:
965 return oparg-1;
966 case UNPACK_EX:
967 return (oparg&0xFF) + (oparg>>8);
968 case FOR_ITER:
969 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case STORE_ATTR:
972 return -2;
973 case DELETE_ATTR:
974 return -1;
975 case STORE_GLOBAL:
976 return -1;
977 case DELETE_GLOBAL:
978 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 case LOAD_CONST:
980 return 1;
981 case LOAD_NAME:
982 return 1;
983 case BUILD_TUPLE:
984 case BUILD_LIST:
985 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300986 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return 1-oparg;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400988 case BUILD_LIST_UNPACK:
989 case BUILD_TUPLE_UNPACK:
Serhiy Storchaka73442852016-10-02 10:33:46 +0300990 case BUILD_TUPLE_UNPACK_WITH_CALL:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400991 case BUILD_SET_UNPACK:
992 case BUILD_MAP_UNPACK:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400993 case BUILD_MAP_UNPACK_WITH_CALL:
Victor Stinnerf9b760f2016-09-09 10:17:08 -0700994 return 1 - oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -0700996 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +0300997 case BUILD_CONST_KEY_MAP:
998 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case LOAD_ATTR:
1000 return 0;
1001 case COMPARE_OP:
1002 return -1;
1003 case IMPORT_NAME:
1004 return -1;
1005 case IMPORT_FROM:
1006 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case JUMP_FORWARD:
1009 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
1010 case JUMP_IF_FALSE_OR_POP: /* "" */
1011 case JUMP_ABSOLUTE:
1012 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case POP_JUMP_IF_FALSE:
1015 case POP_JUMP_IF_TRUE:
1016 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case LOAD_GLOBAL:
1019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case CONTINUE_LOOP:
1022 return 0;
1023 case SETUP_LOOP:
1024 return 0;
1025 case SETUP_EXCEPT:
1026 case SETUP_FINALLY:
1027 return 6; /* can push 3 values for the new exception
1028 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 case LOAD_FAST:
1031 return 1;
1032 case STORE_FAST:
1033 return -1;
1034 case DELETE_FAST:
1035 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001036 case STORE_ANNOTATION:
1037 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case RAISE_VARARGS:
1040 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001042 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001043 case CALL_METHOD:
1044 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001046 return -oparg-1;
1047 case CALL_FUNCTION_EX:
1048 return - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001049 case MAKE_FUNCTION:
1050 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1051 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case BUILD_SLICE:
1053 if (oparg == 3)
1054 return -2;
1055 else
1056 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 case LOAD_CLOSURE:
1059 return 1;
1060 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001061 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return 1;
1063 case STORE_DEREF:
1064 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001065 case DELETE_DEREF:
1066 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001067 case GET_AWAITABLE:
1068 return 0;
1069 case SETUP_ASYNC_WITH:
1070 return 6;
1071 case BEFORE_ASYNC_WITH:
1072 return 1;
1073 case GET_AITER:
1074 return 0;
1075 case GET_ANEXT:
1076 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001077 case GET_YIELD_FROM_ITER:
1078 return 0;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001079 case FORMAT_VALUE:
1080 /* If there's a fmt_spec on the stack, we go from 2->1,
1081 else 1->1. */
1082 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001083 case LOAD_METHOD:
1084 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001086 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
Larry Hastings3a907972013-11-23 14:49:22 -08001088 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089}
1090
1091/* Add an opcode with no argument.
1092 Returns 0 on failure, 1 on success.
1093*/
1094
1095static int
1096compiler_addop(struct compiler *c, int opcode)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 basicblock *b;
1099 struct instr *i;
1100 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001101 assert(!HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 off = compiler_next_instr(c, c->u->u_curblock);
1103 if (off < 0)
1104 return 0;
1105 b = c->u->u_curblock;
1106 i = &b->b_instr[off];
1107 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001108 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (opcode == RETURN_VALUE)
1110 b->b_return = 1;
1111 compiler_set_lineno(c, off);
1112 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113}
1114
Victor Stinnerf8e32212013-11-19 23:56:34 +01001115static Py_ssize_t
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *t, *v;
1119 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120
Victor Stinnerefb24132016-01-22 12:33:12 +01001121 t = _PyCode_ConstantKey(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (t == NULL)
1123 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 v = PyDict_GetItem(dict, t);
1126 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001127 if (PyErr_Occurred()) {
1128 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001130 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001131 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001132 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (!v) {
1134 Py_DECREF(t);
1135 return -1;
1136 }
1137 if (PyDict_SetItem(dict, t, v) < 0) {
1138 Py_DECREF(t);
1139 Py_DECREF(v);
1140 return -1;
1141 }
1142 Py_DECREF(v);
1143 }
1144 else
1145 arg = PyLong_AsLong(v);
1146 Py_DECREF(t);
1147 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148}
1149
1150static int
1151compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001154 Py_ssize_t arg = compiler_add_o(c, dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 return compiler_addop_i(c, opcode, arg);
1158}
1159
1160static int
1161compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001164 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1166 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001167 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 arg = compiler_add_o(c, dict, mangled);
1169 Py_DECREF(mangled);
1170 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001171 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 return compiler_addop_i(c, opcode, arg);
1173}
1174
1175/* Add an opcode with an integer argument.
1176 Returns 0 on failure, 1 on success.
1177*/
1178
1179static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001180compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 struct instr *i;
1183 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001184
Victor Stinner2ad474b2016-03-01 23:34:47 +01001185 /* oparg value is unsigned, but a signed C int is usually used to store
1186 it in the C code (like Python/ceval.c).
1187
1188 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1189
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001190 The argument of a concrete bytecode instruction is limited to 8-bit.
1191 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1192 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001193 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 off = compiler_next_instr(c, c->u->u_curblock);
1196 if (off < 0)
1197 return 0;
1198 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001199 i->i_opcode = opcode;
1200 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 compiler_set_lineno(c, off);
1202 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203}
1204
1205static int
1206compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 struct instr *i;
1209 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001211 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 assert(b != NULL);
1213 off = compiler_next_instr(c, c->u->u_curblock);
1214 if (off < 0)
1215 return 0;
1216 i = &c->u->u_curblock->b_instr[off];
1217 i->i_opcode = opcode;
1218 i->i_target = b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (absolute)
1220 i->i_jabs = 1;
1221 else
1222 i->i_jrel = 1;
1223 compiler_set_lineno(c, off);
1224 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001227/* NEXT_BLOCK() creates an implicit jump from the current block
1228 to the new block.
1229
1230 The returns inside this macro make it impossible to decref objects
1231 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001232*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (compiler_next_block((C)) == NULL) \
1235 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236}
1237
1238#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (!compiler_addop((C), (OP))) \
1240 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241}
1242
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001243#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (!compiler_addop((C), (OP))) { \
1245 compiler_exit_scope(c); \
1246 return 0; \
1247 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001248}
1249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1252 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001255/* Same as ADDOP_O, but steals a reference. */
1256#define ADDOP_N(C, OP, O, TYPE) { \
1257 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1258 Py_DECREF((O)); \
1259 return 0; \
1260 } \
1261 Py_DECREF((O)); \
1262}
1263
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
1269#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!compiler_addop_i((C), (OP), (O))) \
1271 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272}
1273
1274#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (!compiler_addop_j((C), (OP), (O), 1)) \
1276 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (!compiler_addop_j((C), (OP), (O), 0)) \
1281 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282}
1283
1284/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1285 the ASDL name to synthesize the name of the C type and the visit function.
1286*/
1287
1288#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!compiler_visit_ ## TYPE((C), (V))) \
1290 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291}
1292
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001293#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!compiler_visit_ ## TYPE((C), (V))) { \
1295 compiler_exit_scope(c); \
1296 return 0; \
1297 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001298}
1299
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (!compiler_visit_slice((C), (V), (CTX))) \
1302 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303}
1304
1305#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 int _i; \
1307 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1308 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1309 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1310 if (!compiler_visit_ ## TYPE((C), elt)) \
1311 return 0; \
1312 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313}
1314
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001315#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 int _i; \
1317 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1318 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1319 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1320 if (!compiler_visit_ ## TYPE((C), elt)) { \
1321 compiler_exit_scope(c); \
1322 return 0; \
1323 } \
1324 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001325}
1326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327static int
1328compiler_isdocstring(stmt_ty s)
1329{
1330 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001331 return 0;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001332 if (s->v.Expr.value->kind == Str_kind)
1333 return 1;
1334 if (s->v.Expr.value->kind == Constant_kind)
1335 return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value);
1336 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337}
1338
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001339static int
1340is_const(expr_ty e)
1341{
1342 switch (e->kind) {
1343 case Constant_kind:
1344 case Num_kind:
1345 case Str_kind:
1346 case Bytes_kind:
1347 case Ellipsis_kind:
1348 case NameConstant_kind:
1349 return 1;
1350 default:
1351 return 0;
1352 }
1353}
1354
1355static PyObject *
1356get_const_value(expr_ty e)
1357{
1358 switch (e->kind) {
1359 case Constant_kind:
1360 return e->v.Constant.value;
1361 case Num_kind:
1362 return e->v.Num.n;
1363 case Str_kind:
1364 return e->v.Str.s;
1365 case Bytes_kind:
1366 return e->v.Bytes.s;
1367 case Ellipsis_kind:
1368 return Py_Ellipsis;
1369 case NameConstant_kind:
1370 return e->v.NameConstant.value;
1371 default:
1372 assert(!is_const(e));
1373 return NULL;
1374 }
1375}
1376
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001377/* Search if variable annotations are present statically in a block. */
1378
1379static int
1380find_ann(asdl_seq *stmts)
1381{
1382 int i, j, res = 0;
1383 stmt_ty st;
1384
1385 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1386 st = (stmt_ty)asdl_seq_GET(stmts, i);
1387 switch (st->kind) {
1388 case AnnAssign_kind:
1389 return 1;
1390 case For_kind:
1391 res = find_ann(st->v.For.body) ||
1392 find_ann(st->v.For.orelse);
1393 break;
1394 case AsyncFor_kind:
1395 res = find_ann(st->v.AsyncFor.body) ||
1396 find_ann(st->v.AsyncFor.orelse);
1397 break;
1398 case While_kind:
1399 res = find_ann(st->v.While.body) ||
1400 find_ann(st->v.While.orelse);
1401 break;
1402 case If_kind:
1403 res = find_ann(st->v.If.body) ||
1404 find_ann(st->v.If.orelse);
1405 break;
1406 case With_kind:
1407 res = find_ann(st->v.With.body);
1408 break;
1409 case AsyncWith_kind:
1410 res = find_ann(st->v.AsyncWith.body);
1411 break;
1412 case Try_kind:
1413 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1414 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1415 st->v.Try.handlers, j);
1416 if (find_ann(handler->v.ExceptHandler.body)) {
1417 return 1;
1418 }
1419 }
1420 res = find_ann(st->v.Try.body) ||
1421 find_ann(st->v.Try.finalbody) ||
1422 find_ann(st->v.Try.orelse);
1423 break;
1424 default:
1425 res = 0;
1426 }
1427 if (res) {
1428 break;
1429 }
1430 }
1431 return res;
1432}
1433
1434/* Compile a sequence of statements, checking for a docstring
1435 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436
1437static int
1438compiler_body(struct compiler *c, asdl_seq *stmts)
1439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 int i = 0;
1441 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001443 /* Set current line number to the line number of first statement.
1444 This way line number for SETUP_ANNOTATIONS will always
1445 coincide with the line number of first "real" statement in module.
1446 If body is empy, then lineno will be set later in assemble. */
1447 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE &&
1448 !c->u->u_lineno && asdl_seq_LEN(stmts)) {
1449 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1450 c->u->u_lineno = st->lineno;
1451 }
1452 /* Every annotated class and module should have __annotations__. */
1453 if (find_ann(stmts)) {
1454 ADDOP(c, SETUP_ANNOTATIONS);
1455 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (!asdl_seq_LEN(stmts))
1457 return 1;
1458 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001459 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 /* don't generate docstrings if -OO */
1461 i = 1;
1462 VISIT(c, expr, st->v.Expr.value);
1463 if (!compiler_nameop(c, __doc__, Store))
1464 return 0;
1465 }
1466 for (; i < asdl_seq_LEN(stmts); i++)
1467 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1468 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471static PyCodeObject *
1472compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 PyCodeObject *co;
1475 int addNone = 1;
1476 static PyObject *module;
1477 if (!module) {
1478 module = PyUnicode_InternFromString("<module>");
1479 if (!module)
1480 return NULL;
1481 }
1482 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001483 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 return NULL;
1485 switch (mod->kind) {
1486 case Module_kind:
1487 if (!compiler_body(c, mod->v.Module.body)) {
1488 compiler_exit_scope(c);
1489 return 0;
1490 }
1491 break;
1492 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001493 if (find_ann(mod->v.Interactive.body)) {
1494 ADDOP(c, SETUP_ANNOTATIONS);
1495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 c->c_interactive = 1;
1497 VISIT_SEQ_IN_SCOPE(c, stmt,
1498 mod->v.Interactive.body);
1499 break;
1500 case Expression_kind:
1501 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1502 addNone = 0;
1503 break;
1504 case Suite_kind:
1505 PyErr_SetString(PyExc_SystemError,
1506 "suite should not be possible");
1507 return 0;
1508 default:
1509 PyErr_Format(PyExc_SystemError,
1510 "module kind %d should not be possible",
1511 mod->kind);
1512 return 0;
1513 }
1514 co = assemble(c, addNone);
1515 compiler_exit_scope(c);
1516 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001517}
1518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519/* The test for LOCAL must come before the test for FREE in order to
1520 handle classes where name is both local and free. The local var is
1521 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001522*/
1523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524static int
1525get_ref_type(struct compiler *c, PyObject *name)
1526{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001527 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001528 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001529 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001530 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001531 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (scope == 0) {
1533 char buf[350];
1534 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001535 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 "symbols: %s\nlocals: %s\nglobals: %s",
Serhiy Storchakadf4518c2014-11-18 23:34:33 +02001537 PyUnicode_AsUTF8(name),
1538 PyUnicode_AsUTF8(c->u->u_name),
1539 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1540 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1541 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1542 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 );
1544 Py_FatalError(buf);
1545 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548}
1549
1550static int
1551compiler_lookup_arg(PyObject *dict, PyObject *name)
1552{
1553 PyObject *k, *v;
Victor Stinnerefb24132016-01-22 12:33:12 +01001554 k = _PyCode_ConstantKey(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001556 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001558 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001560 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001561 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562}
1563
1564static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001565compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001567 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001568 if (qualname == NULL)
1569 qualname = co->co_name;
1570
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001571 if (free) {
1572 for (i = 0; i < free; ++i) {
1573 /* Bypass com_addop_varname because it will generate
1574 LOAD_DEREF but LOAD_CLOSURE is needed.
1575 */
1576 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1577 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001578
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001579 /* Special case: If a class contains a method with a
1580 free variable that has the same name as a method,
1581 the name will be considered free *and* local in the
1582 class. It should be handled by the closure, as
1583 well as by the normal name loookup logic.
1584 */
1585 reftype = get_ref_type(c, name);
1586 if (reftype == CELL)
1587 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1588 else /* (reftype == FREE) */
1589 arg = compiler_lookup_arg(c->u->u_freevars, name);
1590 if (arg == -1) {
1591 fprintf(stderr,
1592 "lookup %s in %s %d %d\n"
1593 "freevars of %s: %s\n",
1594 PyUnicode_AsUTF8(PyObject_Repr(name)),
1595 PyUnicode_AsUTF8(c->u->u_name),
1596 reftype, arg,
1597 PyUnicode_AsUTF8(co->co_name),
1598 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
1599 Py_FatalError("compiler_make_closure()");
1600 }
1601 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001603 flags |= 0x08;
1604 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001607 ADDOP_O(c, LOAD_CONST, qualname, consts);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001608 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610}
1611
1612static int
1613compiler_decorators(struct compiler *c, asdl_seq* decos)
1614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (!decos)
1618 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1621 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1622 }
1623 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624}
1625
1626static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001627compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001629{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001630 /* Push a dict of keyword-only default values.
1631
1632 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1633 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001634 int i;
1635 PyObject *keys = NULL;
1636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1638 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1639 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1640 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001641 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001642 if (!mangled) {
1643 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001645 if (keys == NULL) {
1646 keys = PyList_New(1);
1647 if (keys == NULL) {
1648 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001649 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001650 }
1651 PyList_SET_ITEM(keys, 0, mangled);
1652 }
1653 else {
1654 int res = PyList_Append(keys, mangled);
1655 Py_DECREF(mangled);
1656 if (res == -1) {
1657 goto error;
1658 }
1659 }
1660 if (!compiler_visit_expr(c, default_)) {
1661 goto error;
1662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 }
1664 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001665 if (keys != NULL) {
1666 Py_ssize_t default_count = PyList_GET_SIZE(keys);
1667 PyObject *keys_tuple = PyList_AsTuple(keys);
1668 Py_DECREF(keys);
1669 if (keys_tuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001670 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001671 }
1672 ADDOP_N(c, LOAD_CONST, keys_tuple, consts);
1673 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001674 assert(default_count > 0);
1675 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001676 }
1677 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001678 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001679 }
1680
1681error:
1682 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001683 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001684}
1685
1686static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001687compiler_visit_argannotation(struct compiler *c, identifier id,
1688 expr_ty annotation, PyObject *names)
1689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01001691 PyObject *mangled;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 VISIT(c, expr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01001693 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001694 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001695 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001696 if (PyList_Append(names, mangled) < 0) {
1697 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001698 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05001699 }
1700 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001702 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001703}
1704
1705static int
1706compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1707 PyObject *names)
1708{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001709 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 for (i = 0; i < asdl_seq_LEN(args); i++) {
1711 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001712 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 c,
1714 arg->arg,
1715 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001716 names))
1717 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001719 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001720}
1721
1722static int
1723compiler_visit_annotations(struct compiler *c, arguments_ty args,
1724 expr_ty returns)
1725{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001726 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001727 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001728
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001729 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 */
1731 static identifier return_str;
1732 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001733 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 names = PyList_New(0);
1735 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001736 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001737
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001738 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001740 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001741 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001742 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001744 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001746 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001747 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001748 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 if (!return_str) {
1752 return_str = PyUnicode_InternFromString("return");
1753 if (!return_str)
1754 goto error;
1755 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03001756 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 goto error;
1758 }
1759
1760 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001762 PyObject *keytuple = PyList_AsTuple(names);
1763 Py_DECREF(names);
1764 if (keytuple == NULL) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001765 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001767 ADDOP_N(c, LOAD_CONST, keytuple, consts);
1768 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001769 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001771 else {
1772 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001773 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001774 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001775
1776error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03001778 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001779}
1780
1781static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001782compiler_visit_defaults(struct compiler *c, arguments_ty args)
1783{
1784 VISIT_SEQ(c, expr, args->defaults);
1785 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1786 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787}
1788
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001789static Py_ssize_t
1790compiler_default_arguments(struct compiler *c, arguments_ty args)
1791{
1792 Py_ssize_t funcflags = 0;
1793 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001794 if (!compiler_visit_defaults(c, args))
1795 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001796 funcflags |= 0x01;
1797 }
1798 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001799 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001800 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001801 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001802 return -1;
1803 }
1804 else if (res > 0) {
1805 funcflags |= 0x02;
1806 }
1807 }
1808 return funcflags;
1809}
1810
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811static int
Yury Selivanov75445082015-05-11 22:57:16 -04001812compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001815 PyObject *qualname, *first_const = Py_None;
Yury Selivanov75445082015-05-11 22:57:16 -04001816 arguments_ty args;
1817 expr_ty returns;
1818 identifier name;
1819 asdl_seq* decos;
1820 asdl_seq *body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 stmt_ty st;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001822 Py_ssize_t i, n, funcflags;
1823 int docstring;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001824 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04001825 int scope_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826
Yury Selivanov75445082015-05-11 22:57:16 -04001827 if (is_async) {
1828 assert(s->kind == AsyncFunctionDef_kind);
1829
1830 args = s->v.AsyncFunctionDef.args;
1831 returns = s->v.AsyncFunctionDef.returns;
1832 decos = s->v.AsyncFunctionDef.decorator_list;
1833 name = s->v.AsyncFunctionDef.name;
1834 body = s->v.AsyncFunctionDef.body;
1835
1836 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
1837 } else {
1838 assert(s->kind == FunctionDef_kind);
1839
1840 args = s->v.FunctionDef.args;
1841 returns = s->v.FunctionDef.returns;
1842 decos = s->v.FunctionDef.decorator_list;
1843 name = s->v.FunctionDef.name;
1844 body = s->v.FunctionDef.body;
1845
1846 scope_type = COMPILER_SCOPE_FUNCTION;
1847 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (!compiler_decorators(c, decos))
1850 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001851
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001852 funcflags = compiler_default_arguments(c, args);
1853 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001855 }
1856
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001857 annotations = compiler_visit_annotations(c, args, returns);
1858 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001859 return 0;
1860 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001861 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001862 funcflags |= 0x04;
1863 }
1864
1865 if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) {
1866 return 0;
1867 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868
Yury Selivanov75445082015-05-11 22:57:16 -04001869 st = (stmt_ty)asdl_seq_GET(body, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 docstring = compiler_isdocstring(st);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01001871 if (docstring && c->c_optimize < 2) {
1872 if (st->v.Expr.value->kind == Constant_kind)
1873 first_const = st->v.Expr.value->v.Constant.value;
1874 else
1875 first_const = st->v.Expr.value->v.Str.s;
1876 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1878 compiler_exit_scope(c);
1879 return 0;
1880 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 c->u->u_argcount = asdl_seq_LEN(args->args);
1883 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Yury Selivanov75445082015-05-11 22:57:16 -04001884 n = asdl_seq_LEN(body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* if there was a docstring, we need to skip the first statement */
1886 for (i = docstring; i < n; i++) {
Yury Selivanov75445082015-05-11 22:57:16 -04001887 st = (stmt_ty)asdl_seq_GET(body, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 VISIT_IN_SCOPE(c, stmt, st);
1889 }
1890 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001891 qualname = c->u->u_qualname;
1892 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001894 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001895 Py_XDECREF(qualname);
1896 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001898 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001900 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001901 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* decorators */
1905 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1906 ADDOP_I(c, CALL_FUNCTION, 1);
1907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908
Yury Selivanov75445082015-05-11 22:57:16 -04001909 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910}
1911
1912static int
1913compiler_class(struct compiler *c, stmt_ty s)
1914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyCodeObject *co;
1916 PyObject *str;
1917 int i;
1918 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (!compiler_decorators(c, decos))
1921 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 /* ultimately generate code for:
1924 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1925 where:
1926 <func> is a function/closure created from the class body;
1927 it has a single argument (__locals__) where the dict
1928 (or MutableSequence) representing the locals is passed
1929 <name> is the class name
1930 <bases> is the positional arguments and *varargs argument
1931 <keywords> is the keyword arguments and **kwds argument
1932 This borrows from compiler_call.
1933 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001936 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1937 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 return 0;
1939 /* this block represents what we do in the new scope */
1940 {
1941 /* use the class name for name mangling */
1942 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001943 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 /* load (global) __name__ ... */
1945 str = PyUnicode_InternFromString("__name__");
1946 if (!str || !compiler_nameop(c, str, Load)) {
1947 Py_XDECREF(str);
1948 compiler_exit_scope(c);
1949 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001950 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 Py_DECREF(str);
1952 /* ... and store it as __module__ */
1953 str = PyUnicode_InternFromString("__module__");
1954 if (!str || !compiler_nameop(c, str, Store)) {
1955 Py_XDECREF(str);
1956 compiler_exit_scope(c);
1957 return 0;
1958 }
1959 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001960 assert(c->u->u_qualname);
1961 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001962 str = PyUnicode_InternFromString("__qualname__");
1963 if (!str || !compiler_nameop(c, str, Store)) {
1964 Py_XDECREF(str);
1965 compiler_exit_scope(c);
1966 return 0;
1967 }
1968 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* compile the body proper */
1970 if (!compiler_body(c, s->v.ClassDef.body)) {
1971 compiler_exit_scope(c);
1972 return 0;
1973 }
Nick Coghlan19d24672016-12-05 16:47:55 +10001974 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001975 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10001976 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05001977 str = PyUnicode_InternFromString("__class__");
1978 if (str == NULL) {
1979 compiler_exit_scope(c);
1980 return 0;
1981 }
1982 i = compiler_lookup_arg(c->u->u_cellvars, str);
1983 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001984 if (i < 0) {
1985 compiler_exit_scope(c);
1986 return 0;
1987 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001988 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10001991 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10001992 str = PyUnicode_InternFromString("__classcell__");
1993 if (!str || !compiler_nameop(c, str, Store)) {
1994 Py_XDECREF(str);
1995 compiler_exit_scope(c);
1996 return 0;
1997 }
1998 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002000 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002001 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002002 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Nick Coghlan19d24672016-12-05 16:47:55 +10002003 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002004 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002005 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 /* create the code object */
2007 co = assemble(c, 1);
2008 }
2009 /* leave the new scope */
2010 compiler_exit_scope(c);
2011 if (co == NULL)
2012 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 /* 2. load the 'build_class' function */
2015 ADDOP(c, LOAD_BUILD_CLASS);
2016
2017 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002018 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_DECREF(co);
2020
2021 /* 4. load class name */
2022 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2023
2024 /* 5. generate the rest of the code for the call */
2025 if (!compiler_call_helper(c, 2,
2026 s->v.ClassDef.bases,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04002027 s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 return 0;
2029
2030 /* 6. apply decorators */
2031 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2032 ADDOP_I(c, CALL_FUNCTION, 1);
2033 }
2034
2035 /* 7. store into <name> */
2036 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2037 return 0;
2038 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039}
2040
2041static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002042compiler_ifexp(struct compiler *c, expr_ty e)
2043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 basicblock *end, *next;
2045
2046 assert(e->kind == IfExp_kind);
2047 end = compiler_new_block(c);
2048 if (end == NULL)
2049 return 0;
2050 next = compiler_new_block(c);
2051 if (next == NULL)
2052 return 0;
2053 VISIT(c, expr, e->v.IfExp.test);
2054 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2055 VISIT(c, expr, e->v.IfExp.body);
2056 ADDOP_JREL(c, JUMP_FORWARD, end);
2057 compiler_use_next_block(c, next);
2058 VISIT(c, expr, e->v.IfExp.orelse);
2059 compiler_use_next_block(c, end);
2060 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002061}
2062
2063static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064compiler_lambda(struct compiler *c, expr_ty e)
2065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002067 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002069 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 arguments_ty args = e->v.Lambda.args;
2071 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (!name) {
2074 name = PyUnicode_InternFromString("<lambda>");
2075 if (!name)
2076 return 0;
2077 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002079 funcflags = compiler_default_arguments(c, args);
2080 if (funcflags == -1) {
2081 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002083
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002084 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002085 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* Make None the first constant, so the lambda can't have a
2089 docstring. */
2090 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
2091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 c->u->u_argcount = asdl_seq_LEN(args->args);
2094 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2095 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2096 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002097 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 }
2099 else {
2100 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002101 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002103 qualname = c->u->u_qualname;
2104 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002106 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002110 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 Py_DECREF(co);
2112
2113 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114}
2115
2116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117compiler_if(struct compiler *c, stmt_ty s)
2118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 basicblock *end, *next;
2120 int constant;
2121 assert(s->kind == If_kind);
2122 end = compiler_new_block(c);
2123 if (end == NULL)
2124 return 0;
2125
Georg Brandl8334fd92010-12-04 10:26:46 +00002126 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 /* constant = 0: "if 0"
2128 * constant = 1: "if 1", "if 2", ...
2129 * constant = -1: rest */
2130 if (constant == 0) {
2131 if (s->v.If.orelse)
2132 VISIT_SEQ(c, stmt, s->v.If.orelse);
2133 } else if (constant == 1) {
2134 VISIT_SEQ(c, stmt, s->v.If.body);
2135 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002136 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 next = compiler_new_block(c);
2138 if (next == NULL)
2139 return 0;
2140 }
2141 else
2142 next = end;
2143 VISIT(c, expr, s->v.If.test);
2144 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
2145 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002146 if (asdl_seq_LEN(s->v.If.orelse)) {
2147 ADDOP_JREL(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 compiler_use_next_block(c, next);
2149 VISIT_SEQ(c, stmt, s->v.If.orelse);
2150 }
2151 }
2152 compiler_use_next_block(c, end);
2153 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154}
2155
2156static int
2157compiler_for(struct compiler *c, stmt_ty s)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 start = compiler_new_block(c);
2162 cleanup = compiler_new_block(c);
2163 end = compiler_new_block(c);
2164 if (start == NULL || end == NULL || cleanup == NULL)
2165 return 0;
2166 ADDOP_JREL(c, SETUP_LOOP, end);
2167 if (!compiler_push_fblock(c, LOOP, start))
2168 return 0;
2169 VISIT(c, expr, s->v.For.iter);
2170 ADDOP(c, GET_ITER);
2171 compiler_use_next_block(c, start);
2172 ADDOP_JREL(c, FOR_ITER, cleanup);
2173 VISIT(c, expr, s->v.For.target);
2174 VISIT_SEQ(c, stmt, s->v.For.body);
2175 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2176 compiler_use_next_block(c, cleanup);
2177 ADDOP(c, POP_BLOCK);
2178 compiler_pop_fblock(c, LOOP, start);
2179 VISIT_SEQ(c, stmt, s->v.For.orelse);
2180 compiler_use_next_block(c, end);
2181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182}
2183
Yury Selivanov75445082015-05-11 22:57:16 -04002184
2185static int
2186compiler_async_for(struct compiler *c, stmt_ty s)
2187{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002188 _Py_IDENTIFIER(StopAsyncIteration);
2189
Yury Selivanov75445082015-05-11 22:57:16 -04002190 basicblock *try, *except, *end, *after_try, *try_cleanup,
2191 *after_loop, *after_loop_else;
2192
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002193 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
2194 if (stop_aiter_error == NULL) {
2195 return 0;
Yury Selivanov75445082015-05-11 22:57:16 -04002196 }
2197
2198 try = compiler_new_block(c);
2199 except = compiler_new_block(c);
2200 end = compiler_new_block(c);
2201 after_try = compiler_new_block(c);
2202 try_cleanup = compiler_new_block(c);
2203 after_loop = compiler_new_block(c);
2204 after_loop_else = compiler_new_block(c);
2205
2206 if (try == NULL || except == NULL || end == NULL
2207 || after_try == NULL || try_cleanup == NULL)
2208 return 0;
2209
2210 ADDOP_JREL(c, SETUP_LOOP, after_loop);
2211 if (!compiler_push_fblock(c, LOOP, try))
2212 return 0;
2213
2214 VISIT(c, expr, s->v.AsyncFor.iter);
2215 ADDOP(c, GET_AITER);
2216 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2217 ADDOP(c, YIELD_FROM);
2218
2219 compiler_use_next_block(c, try);
2220
2221
2222 ADDOP_JREL(c, SETUP_EXCEPT, except);
2223 if (!compiler_push_fblock(c, EXCEPT, try))
2224 return 0;
2225
2226 ADDOP(c, GET_ANEXT);
2227 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2228 ADDOP(c, YIELD_FROM);
2229 VISIT(c, expr, s->v.AsyncFor.target);
2230 ADDOP(c, POP_BLOCK);
2231 compiler_pop_fblock(c, EXCEPT, try);
2232 ADDOP_JREL(c, JUMP_FORWARD, after_try);
2233
2234
2235 compiler_use_next_block(c, except);
2236 ADDOP(c, DUP_TOP);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07002237 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
Yury Selivanov75445082015-05-11 22:57:16 -04002238 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2239 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
2240
2241 ADDOP(c, POP_TOP);
2242 ADDOP(c, POP_TOP);
2243 ADDOP(c, POP_TOP);
2244 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
2245 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2246 ADDOP_JABS(c, JUMP_ABSOLUTE, after_loop_else);
2247
2248
2249 compiler_use_next_block(c, try_cleanup);
2250 ADDOP(c, END_FINALLY);
2251
2252 compiler_use_next_block(c, after_try);
2253 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2254 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
2255
2256 ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */
2257 compiler_pop_fblock(c, LOOP, try);
2258
2259 compiler_use_next_block(c, after_loop);
2260 ADDOP_JABS(c, JUMP_ABSOLUTE, end);
2261
2262 compiler_use_next_block(c, after_loop_else);
2263 VISIT_SEQ(c, stmt, s->v.For.orelse);
2264
2265 compiler_use_next_block(c, end);
2266
2267 return 1;
2268}
2269
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270static int
2271compiler_while(struct compiler *c, stmt_ty s)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00002274 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (constant == 0) {
2277 if (s->v.While.orelse)
2278 VISIT_SEQ(c, stmt, s->v.While.orelse);
2279 return 1;
2280 }
2281 loop = compiler_new_block(c);
2282 end = compiler_new_block(c);
2283 if (constant == -1) {
2284 anchor = compiler_new_block(c);
2285 if (anchor == NULL)
2286 return 0;
2287 }
2288 if (loop == NULL || end == NULL)
2289 return 0;
2290 if (s->v.While.orelse) {
2291 orelse = compiler_new_block(c);
2292 if (orelse == NULL)
2293 return 0;
2294 }
2295 else
2296 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 ADDOP_JREL(c, SETUP_LOOP, end);
2299 compiler_use_next_block(c, loop);
2300 if (!compiler_push_fblock(c, LOOP, loop))
2301 return 0;
2302 if (constant == -1) {
2303 VISIT(c, expr, s->v.While.test);
2304 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2305 }
2306 VISIT_SEQ(c, stmt, s->v.While.body);
2307 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* XXX should the two POP instructions be in a separate block
2310 if there is no else clause ?
2311 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002313 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 compiler_use_next_block(c, anchor);
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002315 ADDOP(c, POP_BLOCK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 compiler_pop_fblock(c, LOOP, loop);
2317 if (orelse != NULL) /* what if orelse is just pass? */
2318 VISIT_SEQ(c, stmt, s->v.While.orelse);
2319 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322}
2323
2324static int
2325compiler_continue(struct compiler *c)
2326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2328 static const char IN_FINALLY_ERROR_MSG[] =
2329 "'continue' not supported inside 'finally' clause";
2330 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (!c->u->u_nfblocks)
2333 return compiler_error(c, LOOP_ERROR_MSG);
2334 i = c->u->u_nfblocks - 1;
2335 switch (c->u->u_fblock[i].fb_type) {
2336 case LOOP:
2337 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2338 break;
2339 case EXCEPT:
2340 case FINALLY_TRY:
2341 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2342 /* Prevent continue anywhere under a finally
2343 even if hidden in a sub-try or except. */
2344 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2345 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2346 }
2347 if (i == -1)
2348 return compiler_error(c, LOOP_ERROR_MSG);
2349 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2350 break;
2351 case FINALLY_END:
2352 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356}
2357
2358/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359
2360 SETUP_FINALLY L
2361 <code for body>
2362 POP_BLOCK
2363 LOAD_CONST <None>
2364 L: <code for finalbody>
2365 END_FINALLY
2366
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367 The special instructions use the block stack. Each block
2368 stack entry contains the instruction that created it (here
2369 SETUP_FINALLY), the level of the value stack at the time the
2370 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 Pushes the current value stack level and the label
2374 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Pops en entry from the block stack, and pops the value
2377 stack until its level is the same as indicated on the
2378 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Pops a variable number of entries from the *value* stack
2381 and re-raises the exception they specify. The number of
2382 entries popped depends on the (pseudo) exception type.
2383
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384 The block stack is unwound when an exception is raised:
2385 when a SETUP_FINALLY entry is found, the exception is pushed
2386 onto the value stack (and the exception condition is cleared),
2387 and the interpreter jumps to the label gotten from the block
2388 stack.
2389*/
2390
2391static int
2392compiler_try_finally(struct compiler *c, stmt_ty s)
2393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 basicblock *body, *end;
2395 body = compiler_new_block(c);
2396 end = compiler_new_block(c);
2397 if (body == NULL || end == NULL)
2398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 ADDOP_JREL(c, SETUP_FINALLY, end);
2401 compiler_use_next_block(c, body);
2402 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2403 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002404 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2405 if (!compiler_try_except(c, s))
2406 return 0;
2407 }
2408 else {
2409 VISIT_SEQ(c, stmt, s->v.Try.body);
2410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 ADDOP(c, POP_BLOCK);
2412 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2415 compiler_use_next_block(c, end);
2416 if (!compiler_push_fblock(c, FINALLY_END, end))
2417 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002418 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 ADDOP(c, END_FINALLY);
2420 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423}
2424
2425/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002426 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427 (The contents of the value stack is shown in [], with the top
2428 at the right; 'tb' is trace-back info, 'val' the exception's
2429 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430
2431 Value stack Label Instruction Argument
2432 [] SETUP_EXCEPT L1
2433 [] <code for S>
2434 [] POP_BLOCK
2435 [] JUMP_FORWARD L0
2436
2437 [tb, val, exc] L1: DUP )
2438 [tb, val, exc, exc] <evaluate E1> )
2439 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2440 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2441 [tb, val, exc] POP
2442 [tb, val] <assign to V1> (or POP if no V1)
2443 [tb] POP
2444 [] <code for S1>
2445 JUMP_FORWARD L0
2446
2447 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 .............................etc.......................
2449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2451
2452 [] L0: <next statement>
2453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 Of course, parts are not generated if Vi or Ei is not present.
2455*/
2456static int
2457compiler_try_except(struct compiler *c, stmt_ty s)
2458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002460 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 body = compiler_new_block(c);
2463 except = compiler_new_block(c);
2464 orelse = compiler_new_block(c);
2465 end = compiler_new_block(c);
2466 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2467 return 0;
2468 ADDOP_JREL(c, SETUP_EXCEPT, except);
2469 compiler_use_next_block(c, body);
2470 if (!compiler_push_fblock(c, EXCEPT, body))
2471 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002472 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 ADDOP(c, POP_BLOCK);
2474 compiler_pop_fblock(c, EXCEPT, body);
2475 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002476 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 compiler_use_next_block(c, except);
2478 for (i = 0; i < n; i++) {
2479 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002480 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (!handler->v.ExceptHandler.type && i < n-1)
2482 return compiler_error(c, "default 'except:' must be last");
2483 c->u->u_lineno_set = 0;
2484 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002485 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 except = compiler_new_block(c);
2487 if (except == NULL)
2488 return 0;
2489 if (handler->v.ExceptHandler.type) {
2490 ADDOP(c, DUP_TOP);
2491 VISIT(c, expr, handler->v.ExceptHandler.type);
2492 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2493 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2494 }
2495 ADDOP(c, POP_TOP);
2496 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002497 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002498
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002499 cleanup_end = compiler_new_block(c);
2500 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002501 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002502 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002503
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002504 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2505 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002507 /*
2508 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002509 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002510 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002511 try:
2512 # body
2513 finally:
2514 name = None
2515 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002516 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002518 /* second try: */
2519 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2520 compiler_use_next_block(c, cleanup_body);
2521 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2522 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002524 /* second # body */
2525 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2526 ADDOP(c, POP_BLOCK);
2527 ADDOP(c, POP_EXCEPT);
2528 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002530 /* finally: */
2531 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2532 compiler_use_next_block(c, cleanup_end);
2533 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2534 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002536 /* name = None */
2537 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2538 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002540 /* del name */
2541 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002543 ADDOP(c, END_FINALLY);
2544 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 }
2546 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002547 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002549 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002550 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002551 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552
Guido van Rossumb940e112007-01-10 16:19:56 +00002553 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002554 ADDOP(c, POP_TOP);
2555 compiler_use_next_block(c, cleanup_body);
2556 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2557 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002559 ADDOP(c, POP_EXCEPT);
2560 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 }
2562 ADDOP_JREL(c, JUMP_FORWARD, end);
2563 compiler_use_next_block(c, except);
2564 }
2565 ADDOP(c, END_FINALLY);
2566 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002567 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 compiler_use_next_block(c, end);
2569 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570}
2571
2572static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002573compiler_try(struct compiler *c, stmt_ty s) {
2574 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2575 return compiler_try_finally(c, s);
2576 else
2577 return compiler_try_except(c, s);
2578}
2579
2580
2581static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582compiler_import_as(struct compiler *c, identifier name, identifier asname)
2583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* The IMPORT_NAME opcode was already generated. This function
2585 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 If there is a dot in name, we need to split it and emit a
2588 LOAD_ATTR for each name.
2589 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2591 PyUnicode_GET_LENGTH(name), 1);
2592 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002593 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 Py_ssize_t pos = dot + 1;
2597 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 dot = PyUnicode_FindChar(name, '.', pos,
2600 PyUnicode_GET_LENGTH(name), 1);
2601 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002602 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002603 attr = PyUnicode_Substring(name, pos,
2604 (dot != -1) ? dot :
2605 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002607 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 ADDOP_O(c, LOAD_ATTR, attr, names);
2609 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 }
2612 }
2613 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614}
2615
2616static int
2617compiler_import(struct compiler *c, stmt_ty s)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 /* The Import node stores a module name like a.b.c as a single
2620 string. This is convenient for all cases except
2621 import a.b.c as d
2622 where we need to parse that string to extract the individual
2623 module names.
2624 XXX Perhaps change the representation to make this case simpler?
2625 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01002626 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 for (i = 0; i < n; i++) {
2629 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2630 int r;
2631 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 level = PyLong_FromLong(0);
2634 if (level == NULL)
2635 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 ADDOP_O(c, LOAD_CONST, level, consts);
2638 Py_DECREF(level);
2639 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2640 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (alias->asname) {
2643 r = compiler_import_as(c, alias->name, alias->asname);
2644 if (!r)
2645 return r;
2646 }
2647 else {
2648 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002649 Py_ssize_t dot = PyUnicode_FindChar(
2650 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002651 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002653 if (tmp == NULL)
2654 return 0;
2655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 Py_DECREF(tmp);
2659 }
2660 if (!r)
2661 return r;
2662 }
2663 }
2664 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665}
2666
2667static int
2668compiler_from_import(struct compiler *c, stmt_ty s)
2669{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002670 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 PyObject *names = PyTuple_New(n);
2673 PyObject *level;
2674 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (!empty_string) {
2677 empty_string = PyUnicode_FromString("");
2678 if (!empty_string)
2679 return 0;
2680 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (!names)
2683 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 level = PyLong_FromLong(s->v.ImportFrom.level);
2686 if (!level) {
2687 Py_DECREF(names);
2688 return 0;
2689 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 /* build up the names */
2692 for (i = 0; i < n; i++) {
2693 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2694 Py_INCREF(alias->name);
2695 PyTuple_SET_ITEM(names, i, alias->name);
2696 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02002699 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 Py_DECREF(level);
2701 Py_DECREF(names);
2702 return compiler_error(c, "from __future__ imports must occur "
2703 "at the beginning of the file");
2704 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 ADDOP_O(c, LOAD_CONST, level, consts);
2707 Py_DECREF(level);
2708 ADDOP_O(c, LOAD_CONST, names, consts);
2709 Py_DECREF(names);
2710 if (s->v.ImportFrom.module) {
2711 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2712 }
2713 else {
2714 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2715 }
2716 for (i = 0; i < n; i++) {
2717 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2718 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 assert(n == 1);
2722 ADDOP(c, IMPORT_STAR);
2723 return 1;
2724 }
2725
2726 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2727 store_name = alias->name;
2728 if (alias->asname)
2729 store_name = alias->asname;
2730
2731 if (!compiler_nameop(c, store_name, Store)) {
2732 Py_DECREF(names);
2733 return 0;
2734 }
2735 }
2736 /* remove imported module */
2737 ADDOP(c, POP_TOP);
2738 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739}
2740
2741static int
2742compiler_assert(struct compiler *c, stmt_ty s)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 static PyObject *assertion_error = NULL;
2745 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002746 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747
Georg Brandl8334fd92010-12-04 10:26:46 +00002748 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 return 1;
2750 if (assertion_error == NULL) {
2751 assertion_error = PyUnicode_InternFromString("AssertionError");
2752 if (assertion_error == NULL)
2753 return 0;
2754 }
2755 if (s->v.Assert.test->kind == Tuple_kind &&
2756 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002757 msg = PyUnicode_FromString("assertion is always true, "
2758 "perhaps remove parentheses?");
2759 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002761 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2762 c->c_filename, c->u->u_lineno,
2763 NULL, NULL) == -1) {
2764 Py_DECREF(msg);
2765 return 0;
2766 }
2767 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 }
2769 VISIT(c, expr, s->v.Assert.test);
2770 end = compiler_new_block(c);
2771 if (end == NULL)
2772 return 0;
2773 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2774 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2775 if (s->v.Assert.msg) {
2776 VISIT(c, expr, s->v.Assert.msg);
2777 ADDOP_I(c, CALL_FUNCTION, 1);
2778 }
2779 ADDOP_I(c, RAISE_VARARGS, 1);
2780 compiler_use_next_block(c, end);
2781 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782}
2783
2784static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002785compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
2786{
2787 if (c->c_interactive && c->c_nestlevel <= 1) {
2788 VISIT(c, expr, value);
2789 ADDOP(c, PRINT_EXPR);
2790 return 1;
2791 }
2792
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03002793 if (is_const(value)) {
Victor Stinner15a30952016-02-08 22:45:06 +01002794 /* ignore constant statement */
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002795 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002796 }
2797
2798 VISIT(c, expr, value);
2799 ADDOP(c, POP_TOP);
2800 return 1;
2801}
2802
2803static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804compiler_visit_stmt(struct compiler *c, stmt_ty s)
2805{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002806 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 /* Always assign a lineno to the next instruction for a stmt. */
2809 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002810 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 switch (s->kind) {
2814 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04002815 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 case ClassDef_kind:
2817 return compiler_class(c, s);
2818 case Return_kind:
2819 if (c->u->u_ste->ste_type != FunctionBlock)
2820 return compiler_error(c, "'return' outside function");
2821 if (s->v.Return.value) {
Yury Selivanoveb636452016-09-08 22:01:51 -07002822 if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2823 return compiler_error(
2824 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 VISIT(c, expr, s->v.Return.value);
2826 }
2827 else
2828 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2829 ADDOP(c, RETURN_VALUE);
2830 break;
2831 case Delete_kind:
2832 VISIT_SEQ(c, expr, s->v.Delete.targets)
2833 break;
2834 case Assign_kind:
2835 n = asdl_seq_LEN(s->v.Assign.targets);
2836 VISIT(c, expr, s->v.Assign.value);
2837 for (i = 0; i < n; i++) {
2838 if (i < n - 1)
2839 ADDOP(c, DUP_TOP);
2840 VISIT(c, expr,
2841 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2842 }
2843 break;
2844 case AugAssign_kind:
2845 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07002846 case AnnAssign_kind:
2847 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 case For_kind:
2849 return compiler_for(c, s);
2850 case While_kind:
2851 return compiler_while(c, s);
2852 case If_kind:
2853 return compiler_if(c, s);
2854 case Raise_kind:
2855 n = 0;
2856 if (s->v.Raise.exc) {
2857 VISIT(c, expr, s->v.Raise.exc);
2858 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002859 if (s->v.Raise.cause) {
2860 VISIT(c, expr, s->v.Raise.cause);
2861 n++;
2862 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01002864 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002866 case Try_kind:
2867 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 case Assert_kind:
2869 return compiler_assert(c, s);
2870 case Import_kind:
2871 return compiler_import(c, s);
2872 case ImportFrom_kind:
2873 return compiler_from_import(c, s);
2874 case Global_kind:
2875 case Nonlocal_kind:
2876 break;
2877 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01002878 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 case Pass_kind:
2880 break;
2881 case Break_kind:
2882 if (!compiler_in_loop(c))
2883 return compiler_error(c, "'break' outside loop");
2884 ADDOP(c, BREAK_LOOP);
2885 break;
2886 case Continue_kind:
2887 return compiler_continue(c);
2888 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002889 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04002890 case AsyncFunctionDef_kind:
2891 return compiler_function(c, s, 1);
2892 case AsyncWith_kind:
2893 return compiler_async_with(c, s, 0);
2894 case AsyncFor_kind:
2895 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 }
Yury Selivanov75445082015-05-11 22:57:16 -04002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899}
2900
2901static int
2902unaryop(unaryop_ty op)
2903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 switch (op) {
2905 case Invert:
2906 return UNARY_INVERT;
2907 case Not:
2908 return UNARY_NOT;
2909 case UAdd:
2910 return UNARY_POSITIVE;
2911 case USub:
2912 return UNARY_NEGATIVE;
2913 default:
2914 PyErr_Format(PyExc_SystemError,
2915 "unary op %d should not be possible", op);
2916 return 0;
2917 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918}
2919
2920static int
2921binop(struct compiler *c, operator_ty op)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 switch (op) {
2924 case Add:
2925 return BINARY_ADD;
2926 case Sub:
2927 return BINARY_SUBTRACT;
2928 case Mult:
2929 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002930 case MatMult:
2931 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 case Div:
2933 return BINARY_TRUE_DIVIDE;
2934 case Mod:
2935 return BINARY_MODULO;
2936 case Pow:
2937 return BINARY_POWER;
2938 case LShift:
2939 return BINARY_LSHIFT;
2940 case RShift:
2941 return BINARY_RSHIFT;
2942 case BitOr:
2943 return BINARY_OR;
2944 case BitXor:
2945 return BINARY_XOR;
2946 case BitAnd:
2947 return BINARY_AND;
2948 case FloorDiv:
2949 return BINARY_FLOOR_DIVIDE;
2950 default:
2951 PyErr_Format(PyExc_SystemError,
2952 "binary op %d should not be possible", op);
2953 return 0;
2954 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955}
2956
2957static int
2958cmpop(cmpop_ty op)
2959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 switch (op) {
2961 case Eq:
2962 return PyCmp_EQ;
2963 case NotEq:
2964 return PyCmp_NE;
2965 case Lt:
2966 return PyCmp_LT;
2967 case LtE:
2968 return PyCmp_LE;
2969 case Gt:
2970 return PyCmp_GT;
2971 case GtE:
2972 return PyCmp_GE;
2973 case Is:
2974 return PyCmp_IS;
2975 case IsNot:
2976 return PyCmp_IS_NOT;
2977 case In:
2978 return PyCmp_IN;
2979 case NotIn:
2980 return PyCmp_NOT_IN;
2981 default:
2982 return PyCmp_BAD;
2983 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984}
2985
2986static int
2987inplace_binop(struct compiler *c, operator_ty op)
2988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 switch (op) {
2990 case Add:
2991 return INPLACE_ADD;
2992 case Sub:
2993 return INPLACE_SUBTRACT;
2994 case Mult:
2995 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04002996 case MatMult:
2997 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 case Div:
2999 return INPLACE_TRUE_DIVIDE;
3000 case Mod:
3001 return INPLACE_MODULO;
3002 case Pow:
3003 return INPLACE_POWER;
3004 case LShift:
3005 return INPLACE_LSHIFT;
3006 case RShift:
3007 return INPLACE_RSHIFT;
3008 case BitOr:
3009 return INPLACE_OR;
3010 case BitXor:
3011 return INPLACE_XOR;
3012 case BitAnd:
3013 return INPLACE_AND;
3014 case FloorDiv:
3015 return INPLACE_FLOOR_DIVIDE;
3016 default:
3017 PyErr_Format(PyExc_SystemError,
3018 "inplace binary op %d should not be possible", op);
3019 return 0;
3020 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021}
3022
3023static int
3024compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3025{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003026 int op, scope;
3027 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 PyObject *dict = c->u->u_names;
3031 PyObject *mangled;
3032 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 mangled = _Py_Mangle(c->u->u_private, name);
3035 if (!mangled)
3036 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003037
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003038 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3039 !_PyUnicode_EqualToASCIIString(name, "True") &&
3040 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 op = 0;
3043 optype = OP_NAME;
3044 scope = PyST_GetScope(c->u->u_ste, mangled);
3045 switch (scope) {
3046 case FREE:
3047 dict = c->u->u_freevars;
3048 optype = OP_DEREF;
3049 break;
3050 case CELL:
3051 dict = c->u->u_cellvars;
3052 optype = OP_DEREF;
3053 break;
3054 case LOCAL:
3055 if (c->u->u_ste->ste_type == FunctionBlock)
3056 optype = OP_FAST;
3057 break;
3058 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003059 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 optype = OP_GLOBAL;
3061 break;
3062 case GLOBAL_EXPLICIT:
3063 optype = OP_GLOBAL;
3064 break;
3065 default:
3066 /* scope can be 0 */
3067 break;
3068 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003071 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 switch (optype) {
3074 case OP_DEREF:
3075 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003076 case Load:
3077 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3078 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 case Store: op = STORE_DEREF; break;
3080 case AugLoad:
3081 case AugStore:
3082 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003083 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 case Param:
3085 default:
3086 PyErr_SetString(PyExc_SystemError,
3087 "param invalid for deref variable");
3088 return 0;
3089 }
3090 break;
3091 case OP_FAST:
3092 switch (ctx) {
3093 case Load: op = LOAD_FAST; break;
3094 case Store: op = STORE_FAST; break;
3095 case Del: op = DELETE_FAST; break;
3096 case AugLoad:
3097 case AugStore:
3098 break;
3099 case Param:
3100 default:
3101 PyErr_SetString(PyExc_SystemError,
3102 "param invalid for local variable");
3103 return 0;
3104 }
3105 ADDOP_O(c, op, mangled, varnames);
3106 Py_DECREF(mangled);
3107 return 1;
3108 case OP_GLOBAL:
3109 switch (ctx) {
3110 case Load: op = LOAD_GLOBAL; break;
3111 case Store: op = STORE_GLOBAL; break;
3112 case Del: op = DELETE_GLOBAL; break;
3113 case AugLoad:
3114 case AugStore:
3115 break;
3116 case Param:
3117 default:
3118 PyErr_SetString(PyExc_SystemError,
3119 "param invalid for global variable");
3120 return 0;
3121 }
3122 break;
3123 case OP_NAME:
3124 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003125 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 case Store: op = STORE_NAME; break;
3127 case Del: op = DELETE_NAME; break;
3128 case AugLoad:
3129 case AugStore:
3130 break;
3131 case Param:
3132 default:
3133 PyErr_SetString(PyExc_SystemError,
3134 "param invalid for name variable");
3135 return 0;
3136 }
3137 break;
3138 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 assert(op);
3141 arg = compiler_add_o(c, dict, mangled);
3142 Py_DECREF(mangled);
3143 if (arg < 0)
3144 return 0;
3145 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146}
3147
3148static int
3149compiler_boolop(struct compiler *c, expr_ty e)
3150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003152 int jumpi;
3153 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 assert(e->kind == BoolOp_kind);
3157 if (e->v.BoolOp.op == And)
3158 jumpi = JUMP_IF_FALSE_OR_POP;
3159 else
3160 jumpi = JUMP_IF_TRUE_OR_POP;
3161 end = compiler_new_block(c);
3162 if (end == NULL)
3163 return 0;
3164 s = e->v.BoolOp.values;
3165 n = asdl_seq_LEN(s) - 1;
3166 assert(n >= 0);
3167 for (i = 0; i < n; ++i) {
3168 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3169 ADDOP_JABS(c, jumpi, end);
3170 }
3171 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3172 compiler_use_next_block(c, end);
3173 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174}
3175
3176static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003177starunpack_helper(struct compiler *c, asdl_seq *elts,
3178 int single_op, int inner_op, int outer_op)
3179{
3180 Py_ssize_t n = asdl_seq_LEN(elts);
3181 Py_ssize_t i, nsubitems = 0, nseen = 0;
3182 for (i = 0; i < n; i++) {
3183 expr_ty elt = asdl_seq_GET(elts, i);
3184 if (elt->kind == Starred_kind) {
3185 if (nseen) {
3186 ADDOP_I(c, inner_op, nseen);
3187 nseen = 0;
3188 nsubitems++;
3189 }
3190 VISIT(c, expr, elt->v.Starred.value);
3191 nsubitems++;
3192 }
3193 else {
3194 VISIT(c, expr, elt);
3195 nseen++;
3196 }
3197 }
3198 if (nsubitems) {
3199 if (nseen) {
3200 ADDOP_I(c, inner_op, nseen);
3201 nsubitems++;
3202 }
3203 ADDOP_I(c, outer_op, nsubitems);
3204 }
3205 else
3206 ADDOP_I(c, single_op, nseen);
3207 return 1;
3208}
3209
3210static int
3211assignment_helper(struct compiler *c, asdl_seq *elts)
3212{
3213 Py_ssize_t n = asdl_seq_LEN(elts);
3214 Py_ssize_t i;
3215 int seen_star = 0;
3216 for (i = 0; i < n; i++) {
3217 expr_ty elt = asdl_seq_GET(elts, i);
3218 if (elt->kind == Starred_kind && !seen_star) {
3219 if ((i >= (1 << 8)) ||
3220 (n-i-1 >= (INT_MAX >> 8)))
3221 return compiler_error(c,
3222 "too many expressions in "
3223 "star-unpacking assignment");
3224 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3225 seen_star = 1;
3226 asdl_seq_SET(elts, i, elt->v.Starred.value);
3227 }
3228 else if (elt->kind == Starred_kind) {
3229 return compiler_error(c,
3230 "two starred expressions in assignment");
3231 }
3232 }
3233 if (!seen_star) {
3234 ADDOP_I(c, UNPACK_SEQUENCE, n);
3235 }
3236 VISIT_SEQ(c, expr, elts);
3237 return 1;
3238}
3239
3240static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003241compiler_list(struct compiler *c, expr_ty e)
3242{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003243 asdl_seq *elts = e->v.List.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003245 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003247 else if (e->v.List.ctx == Load) {
3248 return starunpack_helper(c, elts,
3249 BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003251 else
3252 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254}
3255
3256static int
3257compiler_tuple(struct compiler *c, expr_ty e)
3258{
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003259 asdl_seq *elts = e->v.Tuple.elts;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003261 return assignment_helper(c, elts);
3262 }
3263 else if (e->v.Tuple.ctx == Load) {
3264 return starunpack_helper(c, elts,
3265 BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK);
3266 }
3267 else
3268 VISIT_SEQ(c, expr, elts);
3269 return 1;
3270}
3271
3272static int
3273compiler_set(struct compiler *c, expr_ty e)
3274{
3275 return starunpack_helper(c, e->v.Set.elts, BUILD_SET,
3276 BUILD_SET, BUILD_SET_UNPACK);
3277}
3278
3279static int
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003280are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end)
3281{
3282 Py_ssize_t i;
3283 for (i = begin; i < end; i++) {
3284 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
3285 if (key == NULL || !is_const(key))
3286 return 0;
3287 }
3288 return 1;
3289}
3290
3291static int
3292compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3293{
3294 Py_ssize_t i, n = end - begin;
3295 PyObject *keys, *key;
3296 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3297 for (i = begin; i < end; i++) {
3298 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3299 }
3300 keys = PyTuple_New(n);
3301 if (keys == NULL) {
3302 return 0;
3303 }
3304 for (i = begin; i < end; i++) {
3305 key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3306 Py_INCREF(key);
3307 PyTuple_SET_ITEM(keys, i - begin, key);
3308 }
3309 ADDOP_N(c, LOAD_CONST, keys, consts);
3310 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3311 }
3312 else {
3313 for (i = begin; i < end; i++) {
3314 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3315 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3316 }
3317 ADDOP_I(c, BUILD_MAP, n);
3318 }
3319 return 1;
3320}
3321
3322static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003323compiler_dict(struct compiler *c, expr_ty e)
3324{
Victor Stinner976bb402016-03-23 11:36:19 +01003325 Py_ssize_t i, n, elements;
3326 int containers;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003327 int is_unpacking = 0;
3328 n = asdl_seq_LEN(e->v.Dict.values);
3329 containers = 0;
3330 elements = 0;
3331 for (i = 0; i < n; i++) {
3332 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3333 if (elements == 0xFFFF || (elements && is_unpacking)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003334 if (!compiler_subdict(c, e, i - elements, i))
3335 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003336 containers++;
3337 elements = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003339 if (is_unpacking) {
3340 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3341 containers++;
3342 }
3343 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003344 elements++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 }
3346 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003347 if (elements || containers == 0) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003348 if (!compiler_subdict(c, e, n - elements, n))
3349 return 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003350 containers++;
3351 }
3352 /* If there is more than one dict, they need to be merged into a new
3353 * dict. If there is one dict and it's an unpacking, then it needs
3354 * to be copied into a new dict." */
Serhiy Storchaka3d85fae2016-11-28 20:56:37 +02003355 if (containers > 1 || is_unpacking) {
3356 ADDOP_I(c, BUILD_MAP_UNPACK, containers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
3358 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359}
3360
3361static int
3362compiler_compare(struct compiler *c, expr_ty e)
3363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003364 Py_ssize_t i, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3368 VISIT(c, expr, e->v.Compare.left);
3369 n = asdl_seq_LEN(e->v.Compare.ops);
3370 assert(n > 0);
3371 if (n > 1) {
3372 cleanup = compiler_new_block(c);
3373 if (cleanup == NULL)
3374 return 0;
3375 VISIT(c, expr,
3376 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3377 }
3378 for (i = 1; i < n; i++) {
3379 ADDOP(c, DUP_TOP);
3380 ADDOP(c, ROT_THREE);
3381 ADDOP_I(c, COMPARE_OP,
3382 cmpop((cmpop_ty)(asdl_seq_GET(
3383 e->v.Compare.ops, i - 1))));
3384 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
3385 NEXT_BLOCK(c);
3386 if (i < (n - 1))
3387 VISIT(c, expr,
3388 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3389 }
3390 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
3391 ADDOP_I(c, COMPARE_OP,
3392 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
3393 if (n > 1) {
3394 basicblock *end = compiler_new_block(c);
3395 if (end == NULL)
3396 return 0;
3397 ADDOP_JREL(c, JUMP_FORWARD, end);
3398 compiler_use_next_block(c, cleanup);
3399 ADDOP(c, ROT_TWO);
3400 ADDOP(c, POP_TOP);
3401 compiler_use_next_block(c, end);
3402 }
3403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003404}
3405
3406static int
Yury Selivanovf2392132016-12-13 19:03:51 -05003407maybe_optimize_method_call(struct compiler *c, expr_ty e)
3408{
3409 Py_ssize_t argsl, i;
3410 expr_ty meth = e->v.Call.func;
3411 asdl_seq *args = e->v.Call.args;
3412
3413 /* Check that the call node is an attribute access, and that
3414 the call doesn't have keyword parameters. */
3415 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
3416 asdl_seq_LEN(e->v.Call.keywords))
3417 return -1;
3418
3419 /* Check that there are no *varargs types of arguments. */
3420 argsl = asdl_seq_LEN(args);
3421 for (i = 0; i < argsl; i++) {
3422 expr_ty elt = asdl_seq_GET(args, i);
3423 if (elt->kind == Starred_kind) {
3424 return -1;
3425 }
3426 }
3427
3428 /* Alright, we can optimize the code. */
3429 VISIT(c, expr, meth->v.Attribute.value);
3430 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
3431 VISIT_SEQ(c, expr, e->v.Call.args);
3432 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
3433 return 1;
3434}
3435
3436static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437compiler_call(struct compiler *c, expr_ty e)
3438{
Yury Selivanovf2392132016-12-13 19:03:51 -05003439 if (maybe_optimize_method_call(c, e) > 0)
3440 return 1;
3441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 VISIT(c, expr, e->v.Call.func);
3443 return compiler_call_helper(c, 0,
3444 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003445 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003446}
3447
Eric V. Smith235a6f02015-09-19 14:51:32 -04003448static int
3449compiler_joined_str(struct compiler *c, expr_ty e)
3450{
Eric V. Smith235a6f02015-09-19 14:51:32 -04003451 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02003452 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
3453 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04003454 return 1;
3455}
3456
Eric V. Smitha78c7952015-11-03 12:45:05 -05003457/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003458static int
3459compiler_formatted_value(struct compiler *c, expr_ty e)
3460{
Eric V. Smitha78c7952015-11-03 12:45:05 -05003461 /* Our oparg encodes 2 pieces of information: the conversion
3462 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04003463
Eric V. Smitha78c7952015-11-03 12:45:05 -05003464 Convert the conversion char to 2 bits:
3465 None: 000 0x0 FVC_NONE
3466 !s : 001 0x1 FVC_STR
3467 !r : 010 0x2 FVC_REPR
3468 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04003469
Eric V. Smitha78c7952015-11-03 12:45:05 -05003470 next bit is whether or not we have a format spec:
3471 yes : 100 0x4
3472 no : 000 0x0
3473 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003474
Eric V. Smitha78c7952015-11-03 12:45:05 -05003475 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003476
Eric V. Smitha78c7952015-11-03 12:45:05 -05003477 /* Evaluate the expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003478 VISIT(c, expr, e->v.FormattedValue.value);
3479
Eric V. Smitha78c7952015-11-03 12:45:05 -05003480 switch (e->v.FormattedValue.conversion) {
3481 case 's': oparg = FVC_STR; break;
3482 case 'r': oparg = FVC_REPR; break;
3483 case 'a': oparg = FVC_ASCII; break;
3484 case -1: oparg = FVC_NONE; break;
3485 default:
3486 PyErr_SetString(PyExc_SystemError,
3487 "Unrecognized conversion character");
3488 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003489 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04003490 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05003491 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04003492 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05003493 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04003494 }
3495
Eric V. Smitha78c7952015-11-03 12:45:05 -05003496 /* And push our opcode and oparg */
3497 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith235a6f02015-09-19 14:51:32 -04003498 return 1;
3499}
3500
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003501static int
3502compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
3503{
3504 Py_ssize_t i, n = end - begin;
3505 keyword_ty kw;
3506 PyObject *keys, *key;
3507 assert(n > 0);
3508 if (n > 1) {
3509 for (i = begin; i < end; i++) {
3510 kw = asdl_seq_GET(keywords, i);
3511 VISIT(c, expr, kw->value);
3512 }
3513 keys = PyTuple_New(n);
3514 if (keys == NULL) {
3515 return 0;
3516 }
3517 for (i = begin; i < end; i++) {
3518 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
3519 Py_INCREF(key);
3520 PyTuple_SET_ITEM(keys, i - begin, key);
3521 }
3522 ADDOP_N(c, LOAD_CONST, keys, consts);
3523 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3524 }
3525 else {
3526 /* a for loop only executes once */
3527 for (i = begin; i < end; i++) {
3528 kw = asdl_seq_GET(keywords, i);
3529 ADDOP_O(c, LOAD_CONST, kw->arg, consts);
3530 VISIT(c, expr, kw->value);
3531 }
3532 ADDOP_I(c, BUILD_MAP, n);
3533 }
3534 return 1;
3535}
3536
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003537/* shared code between compiler_call and compiler_class */
3538static int
3539compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01003540 int n, /* Args already pushed */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003541 asdl_seq *args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003542 asdl_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003543{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003544 Py_ssize_t i, nseen, nelts, nkwelts;
Serhiy Storchakab7281052016-09-12 00:52:40 +03003545 int mustdictunpack = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00003546
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003547 /* the number of tuples and dictionaries on the stack */
3548 Py_ssize_t nsubargs = 0, nsubkwargs = 0;
3549
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003550 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003551 nkwelts = asdl_seq_LEN(keywords);
3552
3553 for (i = 0; i < nkwelts; i++) {
3554 keyword_ty kw = asdl_seq_GET(keywords, i);
3555 if (kw->arg == NULL) {
3556 mustdictunpack = 1;
3557 break;
3558 }
3559 }
3560
3561 nseen = n; /* the number of positional arguments on the stack */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003562 for (i = 0; i < nelts; i++) {
3563 expr_ty elt = asdl_seq_GET(args, i);
3564 if (elt->kind == Starred_kind) {
3565 /* A star-arg. If we've seen positional arguments,
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003566 pack the positional arguments into a tuple. */
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003567 if (nseen) {
3568 ADDOP_I(c, BUILD_TUPLE, nseen);
3569 nseen = 0;
3570 nsubargs++;
3571 }
3572 VISIT(c, expr, elt->v.Starred.value);
3573 nsubargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003574 }
3575 else {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003576 VISIT(c, expr, elt);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003577 nseen++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003578 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003580
3581 /* Same dance again for keyword arguments */
Serhiy Storchakab7281052016-09-12 00:52:40 +03003582 if (nsubargs || mustdictunpack) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003583 if (nseen) {
3584 /* Pack up any trailing positional arguments. */
3585 ADDOP_I(c, BUILD_TUPLE, nseen);
3586 nsubargs++;
3587 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003588 if (nsubargs > 1) {
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003589 /* If we ended up with more than one stararg, we need
3590 to concatenate them into a single sequence. */
Serhiy Storchaka73442852016-10-02 10:33:46 +03003591 ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003592 }
3593 else if (nsubargs == 0) {
3594 ADDOP_I(c, BUILD_TUPLE, 0);
3595 }
3596 nseen = 0; /* the number of keyword arguments on the stack following */
3597 for (i = 0; i < nkwelts; i++) {
3598 keyword_ty kw = asdl_seq_GET(keywords, i);
3599 if (kw->arg == NULL) {
3600 /* A keyword argument unpacking. */
3601 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003602 if (!compiler_subkwargs(c, keywords, i - nseen, i))
3603 return 0;
3604 nsubkwargs++;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003605 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003606 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003607 VISIT(c, expr, kw->value);
3608 nsubkwargs++;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003609 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003610 else {
3611 nseen++;
3612 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003613 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003614 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003615 /* Pack up any trailing keyword arguments. */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003616 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts))
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003617 return 0;
3618 nsubkwargs++;
3619 }
Serhiy Storchakab7281052016-09-12 00:52:40 +03003620 if (nsubkwargs > 1) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003621 /* Pack it all up */
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003622 ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003623 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003624 ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0);
3625 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003627 else if (nkwelts) {
3628 PyObject *names;
3629 VISIT_SEQ(c, keyword, keywords);
3630 names = PyTuple_New(nkwelts);
3631 if (names == NULL) {
3632 return 0;
3633 }
3634 for (i = 0; i < nkwelts; i++) {
3635 keyword_ty kw = asdl_seq_GET(keywords, i);
3636 Py_INCREF(kw->arg);
3637 PyTuple_SET_ITEM(names, i, kw->arg);
3638 }
3639 ADDOP_N(c, LOAD_CONST, names, consts);
3640 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
3641 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07003643 else {
3644 ADDOP_I(c, CALL_FUNCTION, n + nelts);
3645 return 1;
3646 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647}
3648
Nick Coghlan650f0d02007-04-15 12:05:43 +00003649
3650/* List and set comprehensions and generator expressions work by creating a
3651 nested function to perform the actual iteration. This means that the
3652 iteration variables don't leak into the current scope.
3653 The defined function is called immediately following its definition, with the
3654 result of that call being the result of the expression.
3655 The LC/SC version returns the populated container, while the GE version is
3656 flagged in symtable.c as a generator, so it returns the generator object
3657 when the function is called.
3658 This code *knows* that the loop cannot contain break, continue, or return,
3659 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3660
3661 Possible cleanups:
3662 - iterate over the generator sequence instead of using recursion
3663*/
3664
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003665
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667compiler_comprehension_generator(struct compiler *c,
3668 asdl_seq *generators, int gen_index,
3669 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003671 comprehension_ty gen;
3672 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3673 if (gen->is_async) {
3674 return compiler_async_comprehension_generator(
3675 c, generators, gen_index, elt, val, type);
3676 } else {
3677 return compiler_sync_comprehension_generator(
3678 c, generators, gen_index, elt, val, type);
3679 }
3680}
3681
3682static int
3683compiler_sync_comprehension_generator(struct compiler *c,
3684 asdl_seq *generators, int gen_index,
3685 expr_ty elt, expr_ty val, int type)
3686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 /* generate code for the iterator, then each of the ifs,
3688 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 comprehension_ty gen;
3691 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003692 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 start = compiler_new_block(c);
3695 skip = compiler_new_block(c);
3696 if_cleanup = compiler_new_block(c);
3697 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3700 anchor == NULL)
3701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 if (gen_index == 0) {
3706 /* Receive outermost iter as an implicit argument */
3707 c->u->u_argcount = 1;
3708 ADDOP_I(c, LOAD_FAST, 0);
3709 }
3710 else {
3711 /* Sub-iter - calculate on the fly */
3712 VISIT(c, expr, gen->iter);
3713 ADDOP(c, GET_ITER);
3714 }
3715 compiler_use_next_block(c, start);
3716 ADDOP_JREL(c, FOR_ITER, anchor);
3717 NEXT_BLOCK(c);
3718 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 /* XXX this needs to be cleaned up...a lot! */
3721 n = asdl_seq_LEN(gen->ifs);
3722 for (i = 0; i < n; i++) {
3723 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3724 VISIT(c, expr, e);
3725 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3726 NEXT_BLOCK(c);
3727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 if (++gen_index < asdl_seq_LEN(generators))
3730 if (!compiler_comprehension_generator(c,
3731 generators, gen_index,
3732 elt, val, type))
3733 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 /* only append after the last for generator */
3736 if (gen_index >= asdl_seq_LEN(generators)) {
3737 /* comprehension specific code */
3738 switch (type) {
3739 case COMP_GENEXP:
3740 VISIT(c, expr, elt);
3741 ADDOP(c, YIELD_VALUE);
3742 ADDOP(c, POP_TOP);
3743 break;
3744 case COMP_LISTCOMP:
3745 VISIT(c, expr, elt);
3746 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3747 break;
3748 case COMP_SETCOMP:
3749 VISIT(c, expr, elt);
3750 ADDOP_I(c, SET_ADD, gen_index + 1);
3751 break;
3752 case COMP_DICTCOMP:
3753 /* With 'd[k] = v', v is evaluated before k, so we do
3754 the same. */
3755 VISIT(c, expr, val);
3756 VISIT(c, expr, elt);
3757 ADDOP_I(c, MAP_ADD, gen_index + 1);
3758 break;
3759 default:
3760 return 0;
3761 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 compiler_use_next_block(c, skip);
3764 }
3765 compiler_use_next_block(c, if_cleanup);
3766 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3767 compiler_use_next_block(c, anchor);
3768
3769 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770}
3771
3772static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003773compiler_async_comprehension_generator(struct compiler *c,
3774 asdl_seq *generators, int gen_index,
3775 expr_ty elt, expr_ty val, int type)
3776{
3777 _Py_IDENTIFIER(StopAsyncIteration);
3778
3779 comprehension_ty gen;
3780 basicblock *anchor, *skip, *if_cleanup, *try,
3781 *after_try, *except, *try_cleanup;
3782 Py_ssize_t i, n;
3783
3784 PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
3785 if (stop_aiter_error == NULL) {
3786 return 0;
3787 }
3788
3789 try = compiler_new_block(c);
3790 after_try = compiler_new_block(c);
3791 try_cleanup = compiler_new_block(c);
3792 except = compiler_new_block(c);
3793 skip = compiler_new_block(c);
3794 if_cleanup = compiler_new_block(c);
3795 anchor = compiler_new_block(c);
3796
3797 if (skip == NULL || if_cleanup == NULL || anchor == NULL ||
3798 try == NULL || after_try == NULL ||
3799 except == NULL || after_try == NULL) {
3800 return 0;
3801 }
3802
3803 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
3804
3805 if (gen_index == 0) {
3806 /* Receive outermost iter as an implicit argument */
3807 c->u->u_argcount = 1;
3808 ADDOP_I(c, LOAD_FAST, 0);
3809 }
3810 else {
3811 /* Sub-iter - calculate on the fly */
3812 VISIT(c, expr, gen->iter);
3813 ADDOP(c, GET_AITER);
3814 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3815 ADDOP(c, YIELD_FROM);
3816 }
3817
3818 compiler_use_next_block(c, try);
3819
3820
3821 ADDOP_JREL(c, SETUP_EXCEPT, except);
3822 if (!compiler_push_fblock(c, EXCEPT, try))
3823 return 0;
3824
3825 ADDOP(c, GET_ANEXT);
3826 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3827 ADDOP(c, YIELD_FROM);
3828 VISIT(c, expr, gen->target);
3829 ADDOP(c, POP_BLOCK);
3830 compiler_pop_fblock(c, EXCEPT, try);
3831 ADDOP_JREL(c, JUMP_FORWARD, after_try);
3832
3833
3834 compiler_use_next_block(c, except);
3835 ADDOP(c, DUP_TOP);
3836 ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names);
3837 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
3838 ADDOP_JABS(c, POP_JUMP_IF_FALSE, try_cleanup);
3839
3840 ADDOP(c, POP_TOP);
3841 ADDOP(c, POP_TOP);
3842 ADDOP(c, POP_TOP);
3843 ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */
3844 ADDOP_JABS(c, JUMP_ABSOLUTE, anchor);
3845
3846
3847 compiler_use_next_block(c, try_cleanup);
3848 ADDOP(c, END_FINALLY);
3849
3850 compiler_use_next_block(c, after_try);
3851
3852 n = asdl_seq_LEN(gen->ifs);
3853 for (i = 0; i < n; i++) {
3854 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3855 VISIT(c, expr, e);
3856 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3857 NEXT_BLOCK(c);
3858 }
3859
3860 if (++gen_index < asdl_seq_LEN(generators))
3861 if (!compiler_comprehension_generator(c,
3862 generators, gen_index,
3863 elt, val, type))
3864 return 0;
3865
3866 /* only append after the last for generator */
3867 if (gen_index >= asdl_seq_LEN(generators)) {
3868 /* comprehension specific code */
3869 switch (type) {
3870 case COMP_GENEXP:
3871 VISIT(c, expr, elt);
3872 ADDOP(c, YIELD_VALUE);
3873 ADDOP(c, POP_TOP);
3874 break;
3875 case COMP_LISTCOMP:
3876 VISIT(c, expr, elt);
3877 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3878 break;
3879 case COMP_SETCOMP:
3880 VISIT(c, expr, elt);
3881 ADDOP_I(c, SET_ADD, gen_index + 1);
3882 break;
3883 case COMP_DICTCOMP:
3884 /* With 'd[k] = v', v is evaluated before k, so we do
3885 the same. */
3886 VISIT(c, expr, val);
3887 VISIT(c, expr, elt);
3888 ADDOP_I(c, MAP_ADD, gen_index + 1);
3889 break;
3890 default:
3891 return 0;
3892 }
3893
3894 compiler_use_next_block(c, skip);
3895 }
3896 compiler_use_next_block(c, if_cleanup);
3897 ADDOP_JABS(c, JUMP_ABSOLUTE, try);
3898 compiler_use_next_block(c, anchor);
3899 ADDOP(c, POP_TOP);
3900
3901 return 1;
3902}
3903
3904static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003905compiler_comprehension(struct compiler *c, expr_ty e, int type,
3906 identifier name, asdl_seq *generators, expr_ty elt,
3907 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003910 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003911 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003912 int is_async_function = c->u->u_ste->ste_coroutine;
3913 int is_async_generator = 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003914
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003915 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003916
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003917 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3918 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003919 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003921 }
3922
3923 is_async_generator = c->u->u_ste->ste_coroutine;
3924
3925 if (is_async_generator && !is_async_function) {
3926 if (e->lineno > c->u->u_lineno) {
3927 c->u->u_lineno = e->lineno;
3928 c->u->u_lineno_set = 0;
3929 }
3930 compiler_error(c, "asynchronous comprehension outside of "
3931 "an asynchronous function");
3932 goto error_in_scope;
3933 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 if (type != COMP_GENEXP) {
3936 int op;
3937 switch (type) {
3938 case COMP_LISTCOMP:
3939 op = BUILD_LIST;
3940 break;
3941 case COMP_SETCOMP:
3942 op = BUILD_SET;
3943 break;
3944 case COMP_DICTCOMP:
3945 op = BUILD_MAP;
3946 break;
3947 default:
3948 PyErr_Format(PyExc_SystemError,
3949 "unknown comprehension type %d", type);
3950 goto error_in_scope;
3951 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 ADDOP_I(c, op, 0);
3954 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 if (!compiler_comprehension_generator(c, generators, 0, elt,
3957 val, type))
3958 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 if (type != COMP_GENEXP) {
3961 ADDOP(c, RETURN_VALUE);
3962 }
3963
3964 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003965 qualname = c->u->u_qualname;
3966 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003968 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 goto error;
3970
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003971 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003973 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 Py_DECREF(co);
3975
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003976 VISIT(c, expr, outermost->iter);
3977
3978 if (outermost->is_async) {
3979 ADDOP(c, GET_AITER);
3980 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3981 ADDOP(c, YIELD_FROM);
3982 } else {
3983 ADDOP(c, GET_ITER);
3984 }
3985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07003987
3988 if (is_async_generator && type != COMP_GENEXP) {
3989 ADDOP(c, GET_AWAITABLE);
3990 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3991 ADDOP(c, YIELD_FROM);
3992 }
3993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003995error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003997error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003998 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 Py_XDECREF(co);
4000 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004001}
4002
4003static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004004compiler_genexp(struct compiler *c, expr_ty e)
4005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 static identifier name;
4007 if (!name) {
4008 name = PyUnicode_FromString("<genexpr>");
4009 if (!name)
4010 return 0;
4011 }
4012 assert(e->kind == GeneratorExp_kind);
4013 return compiler_comprehension(c, e, COMP_GENEXP, name,
4014 e->v.GeneratorExp.generators,
4015 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016}
4017
4018static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004019compiler_listcomp(struct compiler *c, expr_ty e)
4020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 static identifier name;
4022 if (!name) {
4023 name = PyUnicode_FromString("<listcomp>");
4024 if (!name)
4025 return 0;
4026 }
4027 assert(e->kind == ListComp_kind);
4028 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4029 e->v.ListComp.generators,
4030 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004031}
4032
4033static int
4034compiler_setcomp(struct compiler *c, expr_ty e)
4035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 static identifier name;
4037 if (!name) {
4038 name = PyUnicode_FromString("<setcomp>");
4039 if (!name)
4040 return 0;
4041 }
4042 assert(e->kind == SetComp_kind);
4043 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4044 e->v.SetComp.generators,
4045 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004046}
4047
4048
4049static int
4050compiler_dictcomp(struct compiler *c, expr_ty e)
4051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 static identifier name;
4053 if (!name) {
4054 name = PyUnicode_FromString("<dictcomp>");
4055 if (!name)
4056 return 0;
4057 }
4058 assert(e->kind == DictComp_kind);
4059 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4060 e->v.DictComp.generators,
4061 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004062}
4063
4064
4065static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066compiler_visit_keyword(struct compiler *c, keyword_ty k)
4067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 VISIT(c, expr, k->value);
4069 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070}
4071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073 whether they are true or false.
4074
4075 Return values: 1 for true, 0 for false, -1 for non-constant.
4076 */
4077
4078static int
Georg Brandl8334fd92010-12-04 10:26:46 +00004079expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02004081 const char *id;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 switch (e->kind) {
4083 case Ellipsis_kind:
4084 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004085 case Constant_kind:
4086 return PyObject_IsTrue(e->v.Constant.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 case Num_kind:
4088 return PyObject_IsTrue(e->v.Num.n);
4089 case Str_kind:
4090 return PyObject_IsTrue(e->v.Str.s);
4091 case Name_kind:
4092 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004093 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004094 if (id && strcmp(id, "__debug__") == 0)
4095 return !c->c_optimize;
4096 return -1;
4097 case NameConstant_kind: {
4098 PyObject *o = e->v.NameConstant.value;
4099 if (o == Py_None)
4100 return 0;
4101 else if (o == Py_True)
4102 return 1;
4103 else if (o == Py_False)
4104 return 0;
4105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 default:
4107 return -1;
4108 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109}
4110
Yury Selivanov75445082015-05-11 22:57:16 -04004111
4112/*
4113 Implements the async with statement.
4114
4115 The semantics outlined in that PEP are as follows:
4116
4117 async with EXPR as VAR:
4118 BLOCK
4119
4120 It is implemented roughly as:
4121
4122 context = EXPR
4123 exit = context.__aexit__ # not calling it
4124 value = await context.__aenter__()
4125 try:
4126 VAR = value # if VAR present in the syntax
4127 BLOCK
4128 finally:
4129 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004130 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004131 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004132 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004133 if not (await exit(*exc)):
4134 raise
4135 */
4136static int
4137compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4138{
4139 basicblock *block, *finally;
4140 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4141
4142 assert(s->kind == AsyncWith_kind);
4143
4144 block = compiler_new_block(c);
4145 finally = compiler_new_block(c);
4146 if (!block || !finally)
4147 return 0;
4148
4149 /* Evaluate EXPR */
4150 VISIT(c, expr, item->context_expr);
4151
4152 ADDOP(c, BEFORE_ASYNC_WITH);
4153 ADDOP(c, GET_AWAITABLE);
4154 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4155 ADDOP(c, YIELD_FROM);
4156
4157 ADDOP_JREL(c, SETUP_ASYNC_WITH, finally);
4158
4159 /* SETUP_ASYNC_WITH pushes a finally block. */
4160 compiler_use_next_block(c, block);
4161 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
4162 return 0;
4163 }
4164
4165 if (item->optional_vars) {
4166 VISIT(c, expr, item->optional_vars);
4167 }
4168 else {
4169 /* Discard result from context.__aenter__() */
4170 ADDOP(c, POP_TOP);
4171 }
4172
4173 pos++;
4174 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4175 /* BLOCK code */
4176 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4177 else if (!compiler_async_with(c, s, pos))
4178 return 0;
4179
4180 /* End of try block; start the finally block */
4181 ADDOP(c, POP_BLOCK);
4182 compiler_pop_fblock(c, FINALLY_TRY, block);
4183
4184 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4185 compiler_use_next_block(c, finally);
4186 if (!compiler_push_fblock(c, FINALLY_END, finally))
4187 return 0;
4188
4189 /* Finally block starts; context.__exit__ is on the stack under
4190 the exception or return information. Just issue our magic
4191 opcode. */
4192 ADDOP(c, WITH_CLEANUP_START);
4193
4194 ADDOP(c, GET_AWAITABLE);
4195 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4196 ADDOP(c, YIELD_FROM);
4197
4198 ADDOP(c, WITH_CLEANUP_FINISH);
4199
4200 /* Finally block ends. */
4201 ADDOP(c, END_FINALLY);
4202 compiler_pop_fblock(c, FINALLY_END, finally);
4203 return 1;
4204}
4205
4206
Guido van Rossumc2e20742006-02-27 22:32:47 +00004207/*
4208 Implements the with statement from PEP 343.
4209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004211
4212 with EXPR as VAR:
4213 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214
Guido van Rossumc2e20742006-02-27 22:32:47 +00004215 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216
Thomas Wouters477c8d52006-05-27 19:21:47 +00004217 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00004218 exit = context.__exit__ # not calling it
4219 value = context.__enter__()
4220 try:
4221 VAR = value # if VAR present in the syntax
4222 BLOCK
4223 finally:
4224 if an exception was raised:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004225 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004226 else:
Serhiy Storchakad741a882015-06-11 00:06:39 +03004227 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004228 exit(*exc)
4229 */
4230static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004231compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004232{
Guido van Rossumc2e20742006-02-27 22:32:47 +00004233 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004234 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004235
4236 assert(s->kind == With_kind);
4237
Guido van Rossumc2e20742006-02-27 22:32:47 +00004238 block = compiler_new_block(c);
4239 finally = compiler_new_block(c);
4240 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004241 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004242
Thomas Wouters477c8d52006-05-27 19:21:47 +00004243 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004244 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004245 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004246
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004247 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004248 compiler_use_next_block(c, block);
4249 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004250 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004251 }
4252
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004253 if (item->optional_vars) {
4254 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004255 }
4256 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004258 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004259 }
4260
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004261 pos++;
4262 if (pos == asdl_seq_LEN(s->v.With.items))
4263 /* BLOCK code */
4264 VISIT_SEQ(c, stmt, s->v.With.body)
4265 else if (!compiler_with(c, s, pos))
4266 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004267
4268 /* End of try block; start the finally block */
4269 ADDOP(c, POP_BLOCK);
4270 compiler_pop_fblock(c, FINALLY_TRY, block);
4271
4272 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4273 compiler_use_next_block(c, finally);
4274 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004275 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004276
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004277 /* Finally block starts; context.__exit__ is on the stack under
4278 the exception or return information. Just issue our magic
4279 opcode. */
Yury Selivanov75445082015-05-11 22:57:16 -04004280 ADDOP(c, WITH_CLEANUP_START);
4281 ADDOP(c, WITH_CLEANUP_FINISH);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004282
4283 /* Finally block ends. */
4284 ADDOP(c, END_FINALLY);
4285 compiler_pop_fblock(c, FINALLY_END, finally);
4286 return 1;
4287}
4288
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289static int
4290compiler_visit_expr(struct compiler *c, expr_ty e)
4291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 /* If expr e has a different line number than the last expr/stmt,
4293 set a new line number for the next instruction.
4294 */
4295 if (e->lineno > c->u->u_lineno) {
4296 c->u->u_lineno = e->lineno;
4297 c->u->u_lineno_set = 0;
4298 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004299 /* Updating the column offset is always harmless. */
4300 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 switch (e->kind) {
4302 case BoolOp_kind:
4303 return compiler_boolop(c, e);
4304 case BinOp_kind:
4305 VISIT(c, expr, e->v.BinOp.left);
4306 VISIT(c, expr, e->v.BinOp.right);
4307 ADDOP(c, binop(c, e->v.BinOp.op));
4308 break;
4309 case UnaryOp_kind:
4310 VISIT(c, expr, e->v.UnaryOp.operand);
4311 ADDOP(c, unaryop(e->v.UnaryOp.op));
4312 break;
4313 case Lambda_kind:
4314 return compiler_lambda(c, e);
4315 case IfExp_kind:
4316 return compiler_ifexp(c, e);
4317 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004318 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004320 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 case GeneratorExp_kind:
4322 return compiler_genexp(c, e);
4323 case ListComp_kind:
4324 return compiler_listcomp(c, e);
4325 case SetComp_kind:
4326 return compiler_setcomp(c, e);
4327 case DictComp_kind:
4328 return compiler_dictcomp(c, e);
4329 case Yield_kind:
4330 if (c->u->u_ste->ste_type != FunctionBlock)
4331 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004332 if (e->v.Yield.value) {
4333 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 }
4335 else {
4336 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4337 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004338 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004340 case YieldFrom_kind:
4341 if (c->u->u_ste->ste_type != FunctionBlock)
4342 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04004343
4344 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
4345 return compiler_error(c, "'yield from' inside async function");
4346
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004347 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04004348 ADDOP(c, GET_YIELD_FROM_ITER);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004349 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4350 ADDOP(c, YIELD_FROM);
4351 break;
Yury Selivanov75445082015-05-11 22:57:16 -04004352 case Await_kind:
4353 if (c->u->u_ste->ste_type != FunctionBlock)
4354 return compiler_error(c, "'await' outside function");
4355
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004356 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
4357 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION)
Yury Selivanov75445082015-05-11 22:57:16 -04004358 return compiler_error(c, "'await' outside async function");
4359
4360 VISIT(c, expr, e->v.Await.value);
4361 ADDOP(c, GET_AWAITABLE);
4362 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4363 ADDOP(c, YIELD_FROM);
4364 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 case Compare_kind:
4366 return compiler_compare(c, e);
4367 case Call_kind:
4368 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01004369 case Constant_kind:
4370 ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts);
4371 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 case Num_kind:
4373 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
4374 break;
4375 case Str_kind:
4376 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
4377 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004378 case JoinedStr_kind:
4379 return compiler_joined_str(c, e);
4380 case FormattedValue_kind:
4381 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 case Bytes_kind:
4383 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
4384 break;
4385 case Ellipsis_kind:
4386 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
4387 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05004388 case NameConstant_kind:
4389 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
4390 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 /* The following exprs can be assignment targets. */
4392 case Attribute_kind:
4393 if (e->v.Attribute.ctx != AugStore)
4394 VISIT(c, expr, e->v.Attribute.value);
4395 switch (e->v.Attribute.ctx) {
4396 case AugLoad:
4397 ADDOP(c, DUP_TOP);
4398 /* Fall through to load */
4399 case Load:
4400 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
4401 break;
4402 case AugStore:
4403 ADDOP(c, ROT_TWO);
4404 /* Fall through to save */
4405 case Store:
4406 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
4407 break;
4408 case Del:
4409 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
4410 break;
4411 case Param:
4412 default:
4413 PyErr_SetString(PyExc_SystemError,
4414 "param invalid in attribute expression");
4415 return 0;
4416 }
4417 break;
4418 case Subscript_kind:
4419 switch (e->v.Subscript.ctx) {
4420 case AugLoad:
4421 VISIT(c, expr, e->v.Subscript.value);
4422 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
4423 break;
4424 case Load:
4425 VISIT(c, expr, e->v.Subscript.value);
4426 VISIT_SLICE(c, e->v.Subscript.slice, Load);
4427 break;
4428 case AugStore:
4429 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
4430 break;
4431 case Store:
4432 VISIT(c, expr, e->v.Subscript.value);
4433 VISIT_SLICE(c, e->v.Subscript.slice, Store);
4434 break;
4435 case Del:
4436 VISIT(c, expr, e->v.Subscript.value);
4437 VISIT_SLICE(c, e->v.Subscript.slice, Del);
4438 break;
4439 case Param:
4440 default:
4441 PyErr_SetString(PyExc_SystemError,
4442 "param invalid in subscript expression");
4443 return 0;
4444 }
4445 break;
4446 case Starred_kind:
4447 switch (e->v.Starred.ctx) {
4448 case Store:
4449 /* In all legitimate cases, the Starred node was already replaced
4450 * by compiler_list/compiler_tuple. XXX: is that okay? */
4451 return compiler_error(c,
4452 "starred assignment target must be in a list or tuple");
4453 default:
4454 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004455 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 }
4457 break;
4458 case Name_kind:
4459 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
4460 /* child nodes of List and Tuple will have expr_context set */
4461 case List_kind:
4462 return compiler_list(c, e);
4463 case Tuple_kind:
4464 return compiler_tuple(c, e);
4465 }
4466 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467}
4468
4469static int
4470compiler_augassign(struct compiler *c, stmt_ty s)
4471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 expr_ty e = s->v.AugAssign.target;
4473 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 switch (e->kind) {
4478 case Attribute_kind:
4479 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
4480 AugLoad, e->lineno, e->col_offset, c->c_arena);
4481 if (auge == NULL)
4482 return 0;
4483 VISIT(c, expr, auge);
4484 VISIT(c, expr, s->v.AugAssign.value);
4485 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4486 auge->v.Attribute.ctx = AugStore;
4487 VISIT(c, expr, auge);
4488 break;
4489 case Subscript_kind:
4490 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
4491 AugLoad, e->lineno, e->col_offset, c->c_arena);
4492 if (auge == NULL)
4493 return 0;
4494 VISIT(c, expr, auge);
4495 VISIT(c, expr, s->v.AugAssign.value);
4496 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4497 auge->v.Subscript.ctx = AugStore;
4498 VISIT(c, expr, auge);
4499 break;
4500 case Name_kind:
4501 if (!compiler_nameop(c, e->v.Name.id, Load))
4502 return 0;
4503 VISIT(c, expr, s->v.AugAssign.value);
4504 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
4505 return compiler_nameop(c, e->v.Name.id, Store);
4506 default:
4507 PyErr_Format(PyExc_SystemError,
4508 "invalid node type (%d) for augmented assignment",
4509 e->kind);
4510 return 0;
4511 }
4512 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004513}
4514
4515static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004516check_ann_expr(struct compiler *c, expr_ty e)
4517{
4518 VISIT(c, expr, e);
4519 ADDOP(c, POP_TOP);
4520 return 1;
4521}
4522
4523static int
4524check_annotation(struct compiler *c, stmt_ty s)
4525{
4526 /* Annotations are only evaluated in a module or class. */
4527 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4528 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
4529 return check_ann_expr(c, s->v.AnnAssign.annotation);
4530 }
4531 return 1;
4532}
4533
4534static int
4535check_ann_slice(struct compiler *c, slice_ty sl)
4536{
4537 switch(sl->kind) {
4538 case Index_kind:
4539 return check_ann_expr(c, sl->v.Index.value);
4540 case Slice_kind:
4541 if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) {
4542 return 0;
4543 }
4544 if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) {
4545 return 0;
4546 }
4547 if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) {
4548 return 0;
4549 }
4550 break;
4551 default:
4552 PyErr_SetString(PyExc_SystemError,
4553 "unexpected slice kind");
4554 return 0;
4555 }
4556 return 1;
4557}
4558
4559static int
4560check_ann_subscr(struct compiler *c, slice_ty sl)
4561{
4562 /* We check that everything in a subscript is defined at runtime. */
4563 Py_ssize_t i, n;
4564
4565 switch (sl->kind) {
4566 case Index_kind:
4567 case Slice_kind:
4568 if (!check_ann_slice(c, sl)) {
4569 return 0;
4570 }
4571 break;
4572 case ExtSlice_kind:
4573 n = asdl_seq_LEN(sl->v.ExtSlice.dims);
4574 for (i = 0; i < n; i++) {
4575 slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i);
4576 switch (subsl->kind) {
4577 case Index_kind:
4578 case Slice_kind:
4579 if (!check_ann_slice(c, subsl)) {
4580 return 0;
4581 }
4582 break;
4583 case ExtSlice_kind:
4584 default:
4585 PyErr_SetString(PyExc_SystemError,
4586 "extended slice invalid in nested slice");
4587 return 0;
4588 }
4589 }
4590 break;
4591 default:
4592 PyErr_Format(PyExc_SystemError,
4593 "invalid subscript kind %d", sl->kind);
4594 return 0;
4595 }
4596 return 1;
4597}
4598
4599static int
4600compiler_annassign(struct compiler *c, stmt_ty s)
4601{
4602 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07004603 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004604
4605 assert(s->kind == AnnAssign_kind);
4606
4607 /* We perform the actual assignment first. */
4608 if (s->v.AnnAssign.value) {
4609 VISIT(c, expr, s->v.AnnAssign.value);
4610 VISIT(c, expr, targ);
4611 }
4612 switch (targ->kind) {
4613 case Name_kind:
4614 /* If we have a simple name in a module or class, store annotation. */
4615 if (s->v.AnnAssign.simple &&
4616 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
4617 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Guido van Rossum015d8742016-09-11 09:45:24 -07004618 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
4619 if (!mangled) {
4620 return 0;
4621 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004622 VISIT(c, expr, s->v.AnnAssign.annotation);
Guido van Rossum015d8742016-09-11 09:45:24 -07004623 /* ADDOP_N decrefs its argument */
4624 ADDOP_N(c, STORE_ANNOTATION, mangled, names);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07004625 }
4626 break;
4627 case Attribute_kind:
4628 if (!s->v.AnnAssign.value &&
4629 !check_ann_expr(c, targ->v.Attribute.value)) {
4630 return 0;
4631 }
4632 break;
4633 case Subscript_kind:
4634 if (!s->v.AnnAssign.value &&
4635 (!check_ann_expr(c, targ->v.Subscript.value) ||
4636 !check_ann_subscr(c, targ->v.Subscript.slice))) {
4637 return 0;
4638 }
4639 break;
4640 default:
4641 PyErr_Format(PyExc_SystemError,
4642 "invalid node type (%d) for annotated assignment",
4643 targ->kind);
4644 return 0;
4645 }
4646 /* Annotation is evaluated last. */
4647 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
4648 return 0;
4649 }
4650 return 1;
4651}
4652
4653static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004654compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 struct fblockinfo *f;
4657 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Benjamin Petersone09ed542016-07-14 22:00:03 -07004658 PyErr_SetString(PyExc_SyntaxError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 "too many statically nested blocks");
4660 return 0;
4661 }
4662 f = &c->u->u_fblock[c->u->u_nfblocks++];
4663 f->fb_type = t;
4664 f->fb_block = b;
4665 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004666}
4667
4668static void
4669compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
4670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 struct compiler_unit *u = c->u;
4672 assert(u->u_nfblocks > 0);
4673 u->u_nfblocks--;
4674 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
4675 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004676}
4677
Thomas Wouters89f507f2006-12-13 04:49:30 +00004678static int
4679compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 int i;
4681 struct compiler_unit *u = c->u;
4682 for (i = 0; i < u->u_nfblocks; ++i) {
4683 if (u->u_fblock[i].fb_type == LOOP)
4684 return 1;
4685 }
4686 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00004687}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004688/* Raises a SyntaxError and returns 0.
4689 If something goes wrong, a different exception may be raised.
4690*/
4691
4692static int
4693compiler_error(struct compiler *c, const char *errstr)
4694{
Benjamin Peterson43b06862011-05-27 09:08:01 -05004695 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004697
Victor Stinner14e461d2013-08-26 22:28:21 +02004698 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (!loc) {
4700 Py_INCREF(Py_None);
4701 loc = Py_None;
4702 }
Victor Stinner14e461d2013-08-26 22:28:21 +02004703 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00004704 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 if (!u)
4706 goto exit;
4707 v = Py_BuildValue("(zO)", errstr, u);
4708 if (!v)
4709 goto exit;
4710 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 Py_DECREF(loc);
4713 Py_XDECREF(u);
4714 Py_XDECREF(v);
4715 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004716}
4717
4718static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719compiler_handle_subscr(struct compiler *c, const char *kind,
4720 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 /* XXX this code is duplicated */
4725 switch (ctx) {
4726 case AugLoad: /* fall through to Load */
4727 case Load: op = BINARY_SUBSCR; break;
4728 case AugStore:/* fall through to Store */
4729 case Store: op = STORE_SUBSCR; break;
4730 case Del: op = DELETE_SUBSCR; break;
4731 case Param:
4732 PyErr_Format(PyExc_SystemError,
4733 "invalid %s kind %d in subscript\n",
4734 kind, ctx);
4735 return 0;
4736 }
4737 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00004738 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 }
4740 else if (ctx == AugStore) {
4741 ADDOP(c, ROT_THREE);
4742 }
4743 ADDOP(c, op);
4744 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745}
4746
4747static int
4748compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 int n = 2;
4751 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 /* only handles the cases where BUILD_SLICE is emitted */
4754 if (s->v.Slice.lower) {
4755 VISIT(c, expr, s->v.Slice.lower);
4756 }
4757 else {
4758 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4759 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 if (s->v.Slice.upper) {
4762 VISIT(c, expr, s->v.Slice.upper);
4763 }
4764 else {
4765 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4766 }
4767
4768 if (s->v.Slice.step) {
4769 n++;
4770 VISIT(c, expr, s->v.Slice.step);
4771 }
4772 ADDOP_I(c, BUILD_SLICE, n);
4773 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774}
4775
4776static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777compiler_visit_nested_slice(struct compiler *c, slice_ty s,
4778 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 switch (s->kind) {
4781 case Slice_kind:
4782 return compiler_slice(c, s, ctx);
4783 case Index_kind:
4784 VISIT(c, expr, s->v.Index.value);
4785 break;
4786 case ExtSlice_kind:
4787 default:
4788 PyErr_SetString(PyExc_SystemError,
4789 "extended slice invalid in nested slice");
4790 return 0;
4791 }
4792 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004793}
4794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004795static int
4796compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
4797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 char * kindname = NULL;
4799 switch (s->kind) {
4800 case Index_kind:
4801 kindname = "index";
4802 if (ctx != AugStore) {
4803 VISIT(c, expr, s->v.Index.value);
4804 }
4805 break;
4806 case Slice_kind:
4807 kindname = "slice";
4808 if (ctx != AugStore) {
4809 if (!compiler_slice(c, s, ctx))
4810 return 0;
4811 }
4812 break;
4813 case ExtSlice_kind:
4814 kindname = "extended slice";
4815 if (ctx != AugStore) {
Victor Stinnerad9a0662013-11-19 22:23:20 +01004816 Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 for (i = 0; i < n; i++) {
4818 slice_ty sub = (slice_ty)asdl_seq_GET(
4819 s->v.ExtSlice.dims, i);
4820 if (!compiler_visit_nested_slice(c, sub, ctx))
4821 return 0;
4822 }
4823 ADDOP_I(c, BUILD_TUPLE, n);
4824 }
4825 break;
4826 default:
4827 PyErr_Format(PyExc_SystemError,
4828 "invalid subscript kind %d", s->kind);
4829 return 0;
4830 }
4831 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004832}
4833
Thomas Wouters89f507f2006-12-13 04:49:30 +00004834/* End of the compiler section, beginning of the assembler section */
4835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004836/* do depth-first search of basic block graph, starting with block.
4837 post records the block indices in post-order.
4838
4839 XXX must handle implicit jumps from one block to next
4840*/
4841
Thomas Wouters89f507f2006-12-13 04:49:30 +00004842struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004843 PyObject *a_bytecode; /* string containing bytecode */
4844 int a_offset; /* offset into bytecode */
4845 int a_nblocks; /* number of reachable blocks */
4846 basicblock **a_postorder; /* list of blocks in dfs postorder */
4847 PyObject *a_lnotab; /* string containing lnotab */
4848 int a_lnotab_off; /* offset into lnotab */
4849 int a_lineno; /* last lineno of emitted instruction */
4850 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00004851};
4852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004853static void
4854dfs(struct compiler *c, basicblock *b, struct assembler *a)
4855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 int i;
4857 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 if (b->b_seen)
4860 return;
4861 b->b_seen = 1;
4862 if (b->b_next != NULL)
4863 dfs(c, b->b_next, a);
4864 for (i = 0; i < b->b_iused; i++) {
4865 instr = &b->b_instr[i];
4866 if (instr->i_jrel || instr->i_jabs)
4867 dfs(c, instr->i_target, a);
4868 }
4869 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004870}
4871
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004872static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004873stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4874{
Larry Hastings3a907972013-11-23 14:49:22 -08004875 int i, target_depth, effect;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 struct instr *instr;
4877 if (b->b_seen || b->b_startdepth >= depth)
4878 return maxdepth;
4879 b->b_seen = 1;
4880 b->b_startdepth = depth;
4881 for (i = 0; i < b->b_iused; i++) {
4882 instr = &b->b_instr[i];
Larry Hastings3a907972013-11-23 14:49:22 -08004883 effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg);
4884 if (effect == PY_INVALID_STACK_EFFECT) {
4885 fprintf(stderr, "opcode = %d\n", instr->i_opcode);
4886 Py_FatalError("PyCompile_OpcodeStackEffect()");
4887 }
4888 depth += effect;
4889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 if (depth > maxdepth)
4891 maxdepth = depth;
4892 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4893 if (instr->i_jrel || instr->i_jabs) {
4894 target_depth = depth;
4895 if (instr->i_opcode == FOR_ITER) {
4896 target_depth = depth-2;
Antoine Pitrou99614052014-05-23 11:46:03 +02004897 }
4898 else if (instr->i_opcode == SETUP_FINALLY ||
4899 instr->i_opcode == SETUP_EXCEPT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 target_depth = depth+3;
4901 if (target_depth > maxdepth)
4902 maxdepth = target_depth;
4903 }
Antoine Pitrou99614052014-05-23 11:46:03 +02004904 else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP ||
4905 instr->i_opcode == JUMP_IF_FALSE_OR_POP)
4906 depth = depth - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 maxdepth = stackdepth_walk(c, instr->i_target,
4908 target_depth, maxdepth);
4909 if (instr->i_opcode == JUMP_ABSOLUTE ||
4910 instr->i_opcode == JUMP_FORWARD) {
4911 goto out; /* remaining code is dead */
4912 }
4913 }
4914 }
4915 if (b->b_next)
4916 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004917out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 b->b_seen = 0;
4919 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004920}
4921
4922/* Find the flow path that needs the largest stack. We assume that
4923 * cycles in the flow graph have no net effect on the stack depth.
4924 */
4925static int
4926stackdepth(struct compiler *c)
4927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 basicblock *b, *entryblock;
4929 entryblock = NULL;
4930 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4931 b->b_seen = 0;
4932 b->b_startdepth = INT_MIN;
4933 entryblock = b;
4934 }
4935 if (!entryblock)
4936 return 0;
4937 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004938}
4939
4940static int
4941assemble_init(struct assembler *a, int nblocks, int firstlineno)
4942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 memset(a, 0, sizeof(struct assembler));
4944 a->a_lineno = firstlineno;
4945 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4946 if (!a->a_bytecode)
4947 return 0;
4948 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4949 if (!a->a_lnotab)
4950 return 0;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07004951 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 PyErr_NoMemory();
4953 return 0;
4954 }
4955 a->a_postorder = (basicblock **)PyObject_Malloc(
4956 sizeof(basicblock *) * nblocks);
4957 if (!a->a_postorder) {
4958 PyErr_NoMemory();
4959 return 0;
4960 }
4961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004962}
4963
4964static void
4965assemble_free(struct assembler *a)
4966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 Py_XDECREF(a->a_bytecode);
4968 Py_XDECREF(a->a_lnotab);
4969 if (a->a_postorder)
4970 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004971}
4972
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004973static int
4974blocksize(basicblock *b)
4975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 int i;
4977 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03004980 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004982}
4983
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00004984/* Appends a pair to the end of the line number table, a_lnotab, representing
4985 the instruction's bytecode offset and line number. See
4986 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00004987
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004988static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004989assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 int d_bytecode, d_lineno;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004992 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004994
Serhiy Storchakaab874002016-09-11 13:48:15 +03004995 d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 assert(d_bytecode >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 if(d_bytecode == 0 && d_lineno == 0)
5001 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00005002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 if (d_bytecode > 255) {
5004 int j, nbytes, ncodes = d_bytecode / 255;
5005 nbytes = a->a_lnotab_off + 2 * ncodes;
5006 len = PyBytes_GET_SIZE(a->a_lnotab);
5007 if (nbytes >= len) {
5008 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
5009 len = nbytes;
5010 else if (len <= INT_MAX / 2)
5011 len *= 2;
5012 else {
5013 PyErr_NoMemory();
5014 return 0;
5015 }
5016 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5017 return 0;
5018 }
5019 lnotab = (unsigned char *)
5020 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5021 for (j = 0; j < ncodes; j++) {
5022 *lnotab++ = 255;
5023 *lnotab++ = 0;
5024 }
5025 d_bytecode -= ncodes * 255;
5026 a->a_lnotab_off += ncodes * 2;
5027 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005028 assert(0 <= d_bytecode && d_bytecode <= 255);
5029
5030 if (d_lineno < -128 || 127 < d_lineno) {
5031 int j, nbytes, ncodes, k;
5032 if (d_lineno < 0) {
5033 k = -128;
5034 /* use division on positive numbers */
5035 ncodes = (-d_lineno) / 128;
5036 }
5037 else {
5038 k = 127;
5039 ncodes = d_lineno / 127;
5040 }
5041 d_lineno -= ncodes * k;
5042 assert(ncodes >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 nbytes = a->a_lnotab_off + 2 * ncodes;
5044 len = PyBytes_GET_SIZE(a->a_lnotab);
5045 if (nbytes >= len) {
5046 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
5047 len = nbytes;
5048 else if (len <= INT_MAX / 2)
5049 len *= 2;
5050 else {
5051 PyErr_NoMemory();
5052 return 0;
5053 }
5054 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
5055 return 0;
5056 }
5057 lnotab = (unsigned char *)
5058 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
5059 *lnotab++ = d_bytecode;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005060 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 d_bytecode = 0;
5062 for (j = 1; j < ncodes; j++) {
5063 *lnotab++ = 0;
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005064 *lnotab++ = k;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 a->a_lnotab_off += ncodes * 2;
5067 }
Victor Stinnerf3914eb2016-01-20 12:16:21 +01005068 assert(-128 <= d_lineno && d_lineno <= 127);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 len = PyBytes_GET_SIZE(a->a_lnotab);
5071 if (a->a_lnotab_off + 2 >= len) {
5072 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5073 return 0;
5074 }
5075 lnotab = (unsigned char *)
5076 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 a->a_lnotab_off += 2;
5079 if (d_bytecode) {
5080 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005081 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 }
5083 else { /* First line of a block; def stmt, etc. */
5084 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02005085 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 }
5087 a->a_lineno = i->i_lineno;
5088 a->a_lineno_off = a->a_offset;
5089 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005090}
5091
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005092/* assemble_emit()
5093 Extend the bytecode with a new instruction.
5094 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005095*/
5096
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005097static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005098assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005099{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005100 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005102 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005103
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005104 arg = i->i_oparg;
5105 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 if (i->i_lineno && !assemble_lnotab(a, i))
5107 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005108 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 if (len > PY_SSIZE_T_MAX / 2)
5110 return 0;
5111 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5112 return 0;
5113 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005114 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005116 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005118}
5119
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005120static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005121assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005124 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 /* Compute the size of each block and fixup jump args.
5128 Replace block pointer with position in bytecode. */
5129 do {
5130 totsize = 0;
5131 for (i = a->a_nblocks - 1; i >= 0; i--) {
5132 b = a->a_postorder[i];
5133 bsize = blocksize(b);
5134 b->b_offset = totsize;
5135 totsize += bsize;
5136 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005137 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005138 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5139 bsize = b->b_offset;
5140 for (i = 0; i < b->b_iused; i++) {
5141 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005142 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005143 /* Relative jumps are computed relative to
5144 the instruction pointer after fetching
5145 the jump instruction.
5146 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005147 bsize += isize;
5148 if (instr->i_jabs || instr->i_jrel) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 instr->i_oparg = instr->i_target->b_offset;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005150 if (instr->i_jrel) {
5151 instr->i_oparg -= bsize;
5152 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005153 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005154 if (instrsize(instr->i_oparg) != isize) {
5155 extended_arg_recompile = 1;
5156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 }
5159 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 /* XXX: This is an awful hack that could hurt performance, but
5162 on the bright side it should work until we come up
5163 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 The issue is that in the first loop blocksize() is called
5166 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005167 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 So we loop until we stop seeing new EXTENDED_ARGs.
5171 The only EXTENDED_ARGs that could be popping up are
5172 ones in jump instructions. So this should converge
5173 fairly quickly.
5174 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005175 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005176}
5177
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005178static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005179dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005182 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 tuple = PyTuple_New(size);
5185 if (tuple == NULL)
5186 return NULL;
5187 while (PyDict_Next(dict, &pos, &k, &v)) {
5188 i = PyLong_AS_LONG(v);
Victor Stinnerefb24132016-01-22 12:33:12 +01005189 /* The keys of the dictionary are tuples. (see compiler_add_o
5190 * and _PyCode_ConstantKey). The object we want is always second,
5191 * though. */
5192 k = PyTuple_GET_ITEM(k, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 Py_INCREF(k);
5194 assert((i - offset) < size);
5195 assert((i - offset) >= 0);
5196 PyTuple_SET_ITEM(tuple, i - offset, k);
5197 }
5198 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005199}
5200
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005201static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005202compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005205 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005207 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 if (ste->ste_nested)
5209 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005210 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005212 if (!ste->ste_generator && ste->ste_coroutine)
5213 flags |= CO_COROUTINE;
5214 if (ste->ste_generator && ste->ste_coroutine)
5215 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 if (ste->ste_varargs)
5217 flags |= CO_VARARGS;
5218 if (ste->ste_varkeywords)
5219 flags |= CO_VARKEYWORDS;
5220 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 /* (Only) inherit compilerflags in PyCF_MASK */
5223 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005224
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005225 if (!PyDict_GET_SIZE(c->u->u_freevars) &&
5226 !PyDict_GET_SIZE(c->u->u_cellvars)) {
5227 flags |= CO_NOFREE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00005229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005231}
5232
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005233static PyCodeObject *
5234makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 PyObject *tmp;
5237 PyCodeObject *co = NULL;
5238 PyObject *consts = NULL;
5239 PyObject *names = NULL;
5240 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 PyObject *name = NULL;
5242 PyObject *freevars = NULL;
5243 PyObject *cellvars = NULL;
5244 PyObject *bytecode = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005245 Py_ssize_t nlocals;
5246 int nlocals_int;
5247 int flags;
Victor Stinnerf8e32212013-11-19 23:56:34 +01005248 int argcount, kwonlyargcount;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 tmp = dict_keys_inorder(c->u->u_consts, 0);
5251 if (!tmp)
5252 goto error;
5253 consts = PySequence_List(tmp); /* optimize_code requires a list */
5254 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 names = dict_keys_inorder(c->u->u_names, 0);
5257 varnames = dict_keys_inorder(c->u->u_varnames, 0);
5258 if (!consts || !names || !varnames)
5259 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5262 if (!cellvars)
5263 goto error;
5264 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
5265 if (!freevars)
5266 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005267
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005268 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005269 assert(nlocals < INT_MAX);
5270 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 flags = compute_code_flags(c);
5273 if (flags < 0)
5274 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
5277 if (!bytecode)
5278 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5281 if (!tmp)
5282 goto error;
5283 Py_DECREF(consts);
5284 consts = tmp;
5285
Victor Stinnerf8e32212013-11-19 23:56:34 +01005286 argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
5287 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
5288 co = PyCode_New(argcount, kwonlyargcount,
Victor Stinnerad9a0662013-11-19 22:23:20 +01005289 nlocals_int, stackdepth(c), flags,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 bytecode, consts, names, varnames,
5291 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02005292 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 c->u->u_firstlineno,
5294 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005295 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 Py_XDECREF(consts);
5297 Py_XDECREF(names);
5298 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 Py_XDECREF(name);
5300 Py_XDECREF(freevars);
5301 Py_XDECREF(cellvars);
5302 Py_XDECREF(bytecode);
5303 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005304}
5305
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005306
5307/* For debugging purposes only */
5308#if 0
5309static void
5310dump_instr(const struct instr *i)
5311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005312 const char *jrel = i->i_jrel ? "jrel " : "";
5313 const char *jabs = i->i_jabs ? "jabs " : "";
5314 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005317 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005318 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5321 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005322}
5323
5324static void
5325dump_basicblock(const basicblock *b)
5326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 const char *seen = b->b_seen ? "seen " : "";
5328 const char *b_return = b->b_return ? "return " : "";
5329 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
5330 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
5331 if (b->b_instr) {
5332 int i;
5333 for (i = 0; i < b->b_iused; i++) {
5334 fprintf(stderr, " [%02d] ", i);
5335 dump_instr(b->b_instr + i);
5336 }
5337 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005338}
5339#endif
5340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005341static PyCodeObject *
5342assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 basicblock *b, *entryblock;
5345 struct assembler a;
5346 int i, j, nblocks;
5347 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 /* Make sure every block that falls off the end returns None.
5350 XXX NEXT_BLOCK() isn't quite right, because if the last
5351 block ends with a jump or return b_next shouldn't set.
5352 */
5353 if (!c->u->u_curblock->b_return) {
5354 NEXT_BLOCK(c);
5355 if (addNone)
5356 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5357 ADDOP(c, RETURN_VALUE);
5358 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 nblocks = 0;
5361 entryblock = NULL;
5362 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5363 nblocks++;
5364 entryblock = b;
5365 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 /* Set firstlineno if it wasn't explicitly set. */
5368 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005369 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
5371 else
5372 c->u->u_firstlineno = 1;
5373 }
5374 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5375 goto error;
5376 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 /* Can't modify the bytecode after computing jump offsets. */
5379 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 /* Emit code in reverse postorder from dfs. */
5382 for (i = a.a_nblocks - 1; i >= 0; i--) {
5383 b = a.a_postorder[i];
5384 for (j = 0; j < b->b_iused; j++)
5385 if (!assemble_emit(&a, &b->b_instr[j]))
5386 goto error;
5387 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5390 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005391 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005395 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 assemble_free(&a);
5397 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005398}
Georg Brandl8334fd92010-12-04 10:26:46 +00005399
5400#undef PyAST_Compile
5401PyAPI_FUNC(PyCodeObject *)
5402PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
5403 PyArena *arena)
5404{
5405 return PyAST_CompileEx(mod, filename, flags, -1, arena);
5406}