blob: 160c6fce013f90f6a80028b1fa63bdab60f8ee62 [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"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 unsigned i_jabs : 1;
47 unsigned i_jrel : 1;
48 unsigned i_hasarg : 1;
49 unsigned char i_opcode;
50 int i_oparg;
51 struct basicblock_ *i_target; /* target block (if jump instruction) */
52 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000053};
54
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056 /* Each basicblock in a compilation unit is linked via b_list in the
57 reverse order that the block are allocated. b_list points to the next
58 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 struct basicblock_ *b_list;
60 /* number of instructions used */
61 int b_iused;
62 /* length of instruction array (b_instr) */
63 int b_ialloc;
64 /* pointer to an array of instructions, initially NULL */
65 struct instr *b_instr;
66 /* If b_next is non-NULL, it is a pointer to the next
67 block reached by normal control flow. */
68 struct basicblock_ *b_next;
69 /* b_seen is used to perform a DFS of basicblocks. */
70 unsigned b_seen : 1;
71 /* b_return is true if a RETURN_VALUE opcode is inserted. */
72 unsigned b_return : 1;
73 /* depth of stack upon entry of block, computed by stackdepth() */
74 int b_startdepth;
75 /* instruction offset for block, computed by assemble_jump_offsets() */
76 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077} basicblock;
78
79/* fblockinfo tracks the current frame block.
80
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081A frame block is used to handle loops, try/except, and try/finally.
82It's called a frame block to distinguish it from a basic block in the
83compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084*/
85
86enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
87
88struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 enum fblocktype fb_type;
90 basicblock *fb_block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091};
92
Antoine Pitrou86a36b52011-11-25 18:56:07 +010093enum {
94 COMPILER_SCOPE_MODULE,
95 COMPILER_SCOPE_CLASS,
96 COMPILER_SCOPE_FUNCTION,
97 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;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100107 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
108 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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 int u_argcount; /* number of arguments for block */
123 int u_kwonlyargcount; /* number of keyword only arguments for block */
124 /* 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 *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static 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);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000197static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 asdl_seq *args,
199 asdl_seq *keywords,
200 expr_ty starargs,
201 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500202static int compiler_try_except(struct compiler *, stmt_ty);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static PyCodeObject *assemble(struct compiler *, int addNone);
205static PyObject *__doc__;
206
Benjamin Petersonb173f782009-05-05 22:31:58 +0000207#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* Name mangling: __private becomes _classname__private.
213 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200214 PyObject *result;
215 size_t nlen, plen, ipriv;
216 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200218 PyUnicode_READ_CHAR(ident, 0) != '_' ||
219 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 Py_INCREF(ident);
221 return ident;
222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200223 nlen = PyUnicode_GET_LENGTH(ident);
224 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 The only time a name with a dot can occur is when
228 we are compiling an import statement that has a
229 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 TODO(jhylton): Decide whether we want to support
232 mangling of the module name, e.g. __M.X.
233 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200234 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
235 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
236 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_INCREF(ident);
238 return ident; /* Don't mangle __whatever__ */
239 }
240 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200241 ipriv = 0;
242 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
243 ipriv++;
244 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_INCREF(ident);
246 return ident; /* Don't mangle if class is just underscores */
247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200248 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000249
Antoine Pitrou55bff892013-04-06 21:21:04 +0200250 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
251 PyErr_SetString(PyExc_OverflowError,
252 "private identifier too large to be mangled");
253 return NULL;
254 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200256 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
257 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
258 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
259
260 result = PyUnicode_New(1 + nlen + plen, maxchar);
261 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
264 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200265 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
266 Py_DECREF(result);
267 return NULL;
268 }
269 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
270 Py_DECREF(result);
271 return NULL;
272 }
Victor Stinner8f825062012-04-27 13:55:39 +0200273 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200274 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000275}
276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277static int
278compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 c->c_stack = PyList_New(0);
283 if (!c->c_stack)
284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287}
288
289PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200290PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
291 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 struct compiler c;
294 PyCodeObject *co = NULL;
295 PyCompilerFlags local_flags;
296 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (!__doc__) {
299 __doc__ = PyUnicode_InternFromString("__doc__");
300 if (!__doc__)
301 return NULL;
302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!compiler_init(&c))
305 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200306 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 c.c_filename = filename;
308 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200309 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (c.c_future == NULL)
311 goto finally;
312 if (!flags) {
313 local_flags.cf_flags = 0;
314 flags = &local_flags;
315 }
316 merged = c.c_future->ff_features | flags->cf_flags;
317 c.c_future->ff_features = merged;
318 flags->cf_flags = merged;
319 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000320 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322
Victor Stinner14e461d2013-08-26 22:28:21 +0200323 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (c.c_st == NULL) {
325 if (!PyErr_Occurred())
326 PyErr_SetString(PyExc_SystemError, "no symtable");
327 goto finally;
328 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Thomas Wouters1175c432006-02-27 22:49:54 +0000332 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 compiler_free(&c);
334 assert(co || PyErr_Occurred());
335 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336}
337
338PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200339PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
340 int optimize, PyArena *arena)
341{
342 PyObject *filename;
343 PyCodeObject *co;
344 filename = PyUnicode_DecodeFSDefault(filename_str);
345 if (filename == NULL)
346 return NULL;
347 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
348 Py_DECREF(filename);
349 return co;
350
351}
352
353PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354PyNode_Compile(struct _node *n, const char *filename)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyCodeObject *co = NULL;
357 mod_ty mod;
358 PyArena *arena = PyArena_New();
359 if (!arena)
360 return NULL;
361 mod = PyAST_FromNode(n, NULL, filename, arena);
362 if (mod)
363 co = PyAST_Compile(mod, filename, NULL, arena);
364 PyArena_Free(arena);
365 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000366}
367
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000368static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c->c_st)
372 PySymtable_Free(c->c_st);
373 if (c->c_future)
374 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000377}
378
Guido van Rossum79f25d91997-04-29 20:08:16 +0000379static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ssize_t i, n;
383 PyObject *v, *k;
384 PyObject *dict = PyDict_New();
385 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 n = PyList_Size(list);
388 for (i = 0; i < n; i++) {
389 v = PyLong_FromLong(i);
390 if (!v) {
391 Py_DECREF(dict);
392 return NULL;
393 }
394 k = PyList_GET_ITEM(list, i);
395 k = PyTuple_Pack(2, k, k->ob_type);
396 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
397 Py_XDECREF(k);
398 Py_DECREF(v);
399 Py_DECREF(dict);
400 return NULL;
401 }
402 Py_DECREF(k);
403 Py_DECREF(v);
404 }
405 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406}
407
408/* Return new dict containing names from src that match scope(s).
409
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000410src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412values are integers, starting at offset and increasing by one for
413each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414*/
415
416static PyObject *
417dictbytype(PyObject *src, int scope_type, int flag, int offset)
418{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700419 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500421 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 assert(offset >= 0);
424 if (dest == NULL)
425 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426
Meador Inge2ca63152012-07-18 14:20:11 -0500427 /* Sort the keys so that we have a deterministic order on the indexes
428 saved in the returned dictionary. These indexes are used as indexes
429 into the free and cell var storage. Therefore if they aren't
430 deterministic, then the generated bytecode is not deterministic.
431 */
432 sorted_keys = PyDict_Keys(src);
433 if (sorted_keys == NULL)
434 return NULL;
435 if (PyList_Sort(sorted_keys) != 0) {
436 Py_DECREF(sorted_keys);
437 return NULL;
438 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500439 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500440
441 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* XXX this should probably be a macro in symtable.h */
443 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500444 k = PyList_GET_ITEM(sorted_keys, key_i);
445 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 assert(PyLong_Check(v));
447 vi = PyLong_AS_LONG(v);
448 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (scope == scope_type || vi & flag) {
451 PyObject *tuple, *item = PyLong_FromLong(i);
452 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500453 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 Py_DECREF(dest);
455 return NULL;
456 }
457 i++;
458 tuple = PyTuple_Pack(2, k, k->ob_type);
459 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500460 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_DECREF(item);
462 Py_DECREF(dest);
463 Py_XDECREF(tuple);
464 return NULL;
465 }
466 Py_DECREF(item);
467 Py_DECREF(tuple);
468 }
469 }
Meador Inge2ca63152012-07-18 14:20:11 -0500470 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000472}
473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474static void
475compiler_unit_check(struct compiler_unit *u)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 basicblock *block;
478 for (block = u->u_blocks; block != NULL; block = block->b_list) {
479 assert((void *)block != (void *)0xcbcbcbcb);
480 assert((void *)block != (void *)0xfbfbfbfb);
481 assert((void *)block != (void *)0xdbdbdbdb);
482 if (block->b_instr != NULL) {
483 assert(block->b_ialloc > 0);
484 assert(block->b_iused > 0);
485 assert(block->b_ialloc >= block->b_iused);
486 }
487 else {
488 assert (block->b_iused == 0);
489 assert (block->b_ialloc == 0);
490 }
491 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492}
493
494static void
495compiler_unit_free(struct compiler_unit *u)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 compiler_unit_check(u);
500 b = u->u_blocks;
501 while (b != NULL) {
502 if (b->b_instr)
503 PyObject_Free((void *)b->b_instr);
504 next = b->b_list;
505 PyObject_Free((void *)b);
506 b = next;
507 }
508 Py_CLEAR(u->u_ste);
509 Py_CLEAR(u->u_name);
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100510 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(u->u_consts);
512 Py_CLEAR(u->u_names);
513 Py_CLEAR(u->u_varnames);
514 Py_CLEAR(u->u_freevars);
515 Py_CLEAR(u->u_cellvars);
516 Py_CLEAR(u->u_private);
517 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518}
519
520static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100521compiler_enter_scope(struct compiler *c, identifier name,
522 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
527 struct compiler_unit));
528 if (!u) {
529 PyErr_NoMemory();
530 return 0;
531 }
532 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100533 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 u->u_argcount = 0;
535 u->u_kwonlyargcount = 0;
536 u->u_ste = PySymtable_Lookup(c->c_st, key);
537 if (!u->u_ste) {
538 compiler_unit_free(u);
539 return 0;
540 }
541 Py_INCREF(name);
542 u->u_name = name;
543 u->u_varnames = list2dict(u->u_ste->ste_varnames);
544 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
545 if (!u->u_varnames || !u->u_cellvars) {
546 compiler_unit_free(u);
547 return 0;
548 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500549 if (u->u_ste->ste_needs_class_closure) {
550 /* Cook up a implicit __class__ cell. */
551 _Py_IDENTIFIER(__class__);
552 PyObject *tuple, *name, *zero;
553 int res;
554 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
555 assert(PyDict_Size(u->u_cellvars) == 0);
556 name = _PyUnicode_FromId(&PyId___class__);
557 if (!name) {
558 compiler_unit_free(u);
559 return 0;
560 }
561 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
562 if (!tuple) {
563 compiler_unit_free(u);
564 return 0;
565 }
566 zero = PyLong_FromLong(0);
567 if (!zero) {
568 Py_DECREF(tuple);
569 compiler_unit_free(u);
570 return 0;
571 }
572 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
573 Py_DECREF(tuple);
574 Py_DECREF(zero);
575 if (res < 0) {
576 compiler_unit_free(u);
577 return 0;
578 }
579 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
582 PyDict_Size(u->u_cellvars));
583 if (!u->u_freevars) {
584 compiler_unit_free(u);
585 return 0;
586 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 u->u_blocks = NULL;
589 u->u_nfblocks = 0;
590 u->u_firstlineno = lineno;
591 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000592 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 u->u_lineno_set = 0;
594 u->u_consts = PyDict_New();
595 if (!u->u_consts) {
596 compiler_unit_free(u);
597 return 0;
598 }
599 u->u_names = PyDict_New();
600 if (!u->u_names) {
601 compiler_unit_free(u);
602 return 0;
603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* Push the old compiler_unit on the stack. */
608 if (c->u) {
609 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
610 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
611 Py_XDECREF(capsule);
612 compiler_unit_free(u);
613 return 0;
614 }
615 Py_DECREF(capsule);
616 u->u_private = c->u->u_private;
617 Py_XINCREF(u->u_private);
618 }
619 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 c->c_nestlevel++;
622 if (compiler_use_new_block(c) == NULL)
623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626}
627
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000628static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629compiler_exit_scope(struct compiler *c)
630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 int n;
632 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 c->c_nestlevel--;
635 compiler_unit_free(c->u);
636 /* Restore c->u to the parent unit. */
637 n = PyList_GET_SIZE(c->c_stack) - 1;
638 if (n >= 0) {
639 capsule = PyList_GET_ITEM(c->c_stack, n);
640 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
641 assert(c->u);
642 /* we are deleting from a list so this really shouldn't fail */
643 if (PySequence_DelItem(c->c_stack, n) < 0)
644 Py_FatalError("compiler_exit_scope()");
645 compiler_unit_check(c->u);
646 }
647 else
648 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650}
651
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100652static PyObject *
653compiler_scope_qualname(struct compiler *c)
654{
655 Py_ssize_t stack_size, i;
656 _Py_static_string(dot, ".");
657 _Py_static_string(locals, "<locals>");
658 struct compiler_unit *u;
659 PyObject *capsule, *name, *seq, *dot_str, *locals_str;
660
661 u = c->u;
662 if (u->u_qualname != NULL) {
663 Py_INCREF(u->u_qualname);
664 return u->u_qualname;
665 }
666
667 seq = PyList_New(0);
668 if (seq == NULL)
669 return NULL;
670
671 stack_size = PyList_GET_SIZE(c->c_stack);
672 for (i = 0; i < stack_size; i++) {
673 capsule = PyList_GET_ITEM(c->c_stack, i);
674 u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
675 assert(u);
676 if (u->u_scope_type == COMPILER_SCOPE_MODULE)
677 continue;
678 if (PyList_Append(seq, u->u_name))
679 goto _error;
680 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION) {
681 locals_str = _PyUnicode_FromId(&locals);
682 if (locals_str == NULL)
683 goto _error;
684 if (PyList_Append(seq, locals_str))
685 goto _error;
686 }
687 }
688 u = c->u;
689 if (PyList_Append(seq, u->u_name))
690 goto _error;
691 dot_str = _PyUnicode_FromId(&dot);
692 if (dot_str == NULL)
693 goto _error;
694 name = PyUnicode_Join(dot_str, seq);
695 Py_DECREF(seq);
696 u->u_qualname = name;
697 Py_XINCREF(name);
698 return name;
699
700_error:
701 Py_XDECREF(seq);
702 return NULL;
703}
704
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705/* Allocate a new block and return a pointer to it.
706 Returns NULL on error.
707*/
708
709static basicblock *
710compiler_new_block(struct compiler *c)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 basicblock *b;
713 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 u = c->u;
716 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
717 if (b == NULL) {
718 PyErr_NoMemory();
719 return NULL;
720 }
721 memset((void *)b, 0, sizeof(basicblock));
722 /* Extend the singly linked list of blocks with new block. */
723 b->b_list = u->u_blocks;
724 u->u_blocks = b;
725 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726}
727
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000728static basicblock *
729compiler_use_new_block(struct compiler *c)
730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 basicblock *block = compiler_new_block(c);
732 if (block == NULL)
733 return NULL;
734 c->u->u_curblock = block;
735 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000736}
737
738static basicblock *
739compiler_next_block(struct compiler *c)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 basicblock *block = compiler_new_block(c);
742 if (block == NULL)
743 return NULL;
744 c->u->u_curblock->b_next = block;
745 c->u->u_curblock = block;
746 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747}
748
749static basicblock *
750compiler_use_next_block(struct compiler *c, basicblock *block)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 assert(block != NULL);
753 c->u->u_curblock->b_next = block;
754 c->u->u_curblock = block;
755 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756}
757
758/* Returns the offset of the next instruction in the current block's
759 b_instr array. Resizes the b_instr as necessary.
760 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000761*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000762
763static int
764compiler_next_instr(struct compiler *c, basicblock *b)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 assert(b != NULL);
767 if (b->b_instr == NULL) {
768 b->b_instr = (struct instr *)PyObject_Malloc(
769 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
770 if (b->b_instr == NULL) {
771 PyErr_NoMemory();
772 return -1;
773 }
774 b->b_ialloc = DEFAULT_BLOCK_SIZE;
775 memset((char *)b->b_instr, 0,
776 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
777 }
778 else if (b->b_iused == b->b_ialloc) {
779 struct instr *tmp;
780 size_t oldsize, newsize;
781 oldsize = b->b_ialloc * sizeof(struct instr);
782 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (oldsize > (PY_SIZE_MAX >> 1)) {
785 PyErr_NoMemory();
786 return -1;
787 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (newsize == 0) {
790 PyErr_NoMemory();
791 return -1;
792 }
793 b->b_ialloc <<= 1;
794 tmp = (struct instr *)PyObject_Realloc(
795 (void *)b->b_instr, newsize);
796 if (tmp == NULL) {
797 PyErr_NoMemory();
798 return -1;
799 }
800 b->b_instr = tmp;
801 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
802 }
803 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804}
805
Christian Heimes2202f872008-02-06 14:31:34 +0000806/* Set the i_lineno member of the instruction at offset off if the
807 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000808 already been set. If it has been set, the call has no effect.
809
Christian Heimes2202f872008-02-06 14:31:34 +0000810 The line number is reset in the following cases:
811 - when entering a new scope
812 - on each statement
813 - on each expression that start a new line
814 - before the "except" clause
815 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000816*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818static void
819compiler_set_lineno(struct compiler *c, int off)
820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 basicblock *b;
822 if (c->u->u_lineno_set)
823 return;
824 c->u->u_lineno_set = 1;
825 b = c->u->u_curblock;
826 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827}
828
829static int
830opcode_stack_effect(int opcode, int oparg)
831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 switch (opcode) {
833 case POP_TOP:
834 return -1;
835 case ROT_TWO:
836 case ROT_THREE:
837 return 0;
838 case DUP_TOP:
839 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000840 case DUP_TOP_TWO:
841 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 case UNARY_POSITIVE:
844 case UNARY_NEGATIVE:
845 case UNARY_NOT:
846 case UNARY_INVERT:
847 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 case SET_ADD:
850 case LIST_APPEND:
851 return -1;
852 case MAP_ADD:
853 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 case BINARY_POWER:
856 case BINARY_MULTIPLY:
857 case BINARY_MODULO:
858 case BINARY_ADD:
859 case BINARY_SUBTRACT:
860 case BINARY_SUBSCR:
861 case BINARY_FLOOR_DIVIDE:
862 case BINARY_TRUE_DIVIDE:
863 return -1;
864 case INPLACE_FLOOR_DIVIDE:
865 case INPLACE_TRUE_DIVIDE:
866 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 case INPLACE_ADD:
869 case INPLACE_SUBTRACT:
870 case INPLACE_MULTIPLY:
871 case INPLACE_MODULO:
872 return -1;
873 case STORE_SUBSCR:
874 return -3;
875 case STORE_MAP:
876 return -2;
877 case DELETE_SUBSCR:
878 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 case BINARY_LSHIFT:
881 case BINARY_RSHIFT:
882 case BINARY_AND:
883 case BINARY_XOR:
884 case BINARY_OR:
885 return -1;
886 case INPLACE_POWER:
887 return -1;
888 case GET_ITER:
889 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 case PRINT_EXPR:
892 return -1;
893 case LOAD_BUILD_CLASS:
894 return 1;
895 case INPLACE_LSHIFT:
896 case INPLACE_RSHIFT:
897 case INPLACE_AND:
898 case INPLACE_XOR:
899 case INPLACE_OR:
900 return -1;
901 case BREAK_LOOP:
902 return 0;
903 case SETUP_WITH:
904 return 7;
905 case WITH_CLEANUP:
906 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case RETURN_VALUE:
908 return -1;
909 case IMPORT_STAR:
910 return -1;
911 case YIELD_VALUE:
912 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500913 case YIELD_FROM:
914 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 case POP_BLOCK:
916 return 0;
917 case POP_EXCEPT:
918 return 0; /* -3 except if bad bytecode */
919 case END_FINALLY:
920 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case STORE_NAME:
923 return -1;
924 case DELETE_NAME:
925 return 0;
926 case UNPACK_SEQUENCE:
927 return oparg-1;
928 case UNPACK_EX:
929 return (oparg&0xFF) + (oparg>>8);
930 case FOR_ITER:
931 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case STORE_ATTR:
934 return -2;
935 case DELETE_ATTR:
936 return -1;
937 case STORE_GLOBAL:
938 return -1;
939 case DELETE_GLOBAL:
940 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case LOAD_CONST:
942 return 1;
943 case LOAD_NAME:
944 return 1;
945 case BUILD_TUPLE:
946 case BUILD_LIST:
947 case BUILD_SET:
948 return 1-oparg;
949 case BUILD_MAP:
950 return 1;
951 case LOAD_ATTR:
952 return 0;
953 case COMPARE_OP:
954 return -1;
955 case IMPORT_NAME:
956 return -1;
957 case IMPORT_FROM:
958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case JUMP_FORWARD:
961 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
962 case JUMP_IF_FALSE_OR_POP: /* "" */
963 case JUMP_ABSOLUTE:
964 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case POP_JUMP_IF_FALSE:
967 case POP_JUMP_IF_TRUE:
968 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case LOAD_GLOBAL:
971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 case CONTINUE_LOOP:
974 return 0;
975 case SETUP_LOOP:
976 return 0;
977 case SETUP_EXCEPT:
978 case SETUP_FINALLY:
979 return 6; /* can push 3 values for the new exception
980 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case LOAD_FAST:
983 return 1;
984 case STORE_FAST:
985 return -1;
986 case DELETE_FAST:
987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 case RAISE_VARARGS:
990 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000991#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case CALL_FUNCTION:
993 return -NARGS(oparg);
994 case CALL_FUNCTION_VAR:
995 case CALL_FUNCTION_KW:
996 return -NARGS(oparg)-1;
997 case CALL_FUNCTION_VAR_KW:
998 return -NARGS(oparg)-2;
999 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001000 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001002 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001003#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 case BUILD_SLICE:
1005 if (oparg == 3)
1006 return -2;
1007 else
1008 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 case LOAD_CLOSURE:
1011 return 1;
1012 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001013 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return 1;
1015 case STORE_DEREF:
1016 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001017 case DELETE_DEREF:
1018 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 default:
1020 fprintf(stderr, "opcode = %d\n", opcode);
1021 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 }
1024 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025}
1026
1027/* Add an opcode with no argument.
1028 Returns 0 on failure, 1 on success.
1029*/
1030
1031static int
1032compiler_addop(struct compiler *c, int opcode)
1033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 basicblock *b;
1035 struct instr *i;
1036 int off;
1037 off = compiler_next_instr(c, c->u->u_curblock);
1038 if (off < 0)
1039 return 0;
1040 b = c->u->u_curblock;
1041 i = &b->b_instr[off];
1042 i->i_opcode = opcode;
1043 i->i_hasarg = 0;
1044 if (opcode == RETURN_VALUE)
1045 b->b_return = 1;
1046 compiler_set_lineno(c, off);
1047 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048}
1049
1050static int
1051compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *t, *v;
1054 Py_ssize_t arg;
1055 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Serhiy Storchaka95949422013-08-27 19:40:23 +03001057 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1059 if (PyFloat_Check(o)) {
1060 d = PyFloat_AS_DOUBLE(o);
1061 /* all we need is to make the tuple different in either the 0.0
1062 * or -0.0 case from all others, just to avoid the "coercion".
1063 */
1064 if (d == 0.0 && copysign(1.0, d) < 0.0)
1065 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1066 else
1067 t = PyTuple_Pack(2, o, o->ob_type);
1068 }
1069 else if (PyComplex_Check(o)) {
1070 Py_complex z;
1071 int real_negzero, imag_negzero;
1072 /* For the complex case we must make complex(x, 0.)
1073 different from complex(x, -0.) and complex(0., y)
1074 different from complex(-0., y), for any x and y.
1075 All four complex zeros must be distinguished.*/
1076 z = PyComplex_AsCComplex(o);
1077 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1078 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1079 if (real_negzero && imag_negzero) {
1080 t = PyTuple_Pack(5, o, o->ob_type,
1081 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 else if (imag_negzero) {
1084 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 else if (real_negzero) {
1087 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1088 }
1089 else {
1090 t = PyTuple_Pack(2, o, o->ob_type);
1091 }
1092 }
1093 else {
1094 t = PyTuple_Pack(2, o, o->ob_type);
1095 }
1096 if (t == NULL)
1097 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 v = PyDict_GetItem(dict, t);
1100 if (!v) {
1101 if (PyErr_Occurred())
1102 return -1;
1103 arg = PyDict_Size(dict);
1104 v = PyLong_FromLong(arg);
1105 if (!v) {
1106 Py_DECREF(t);
1107 return -1;
1108 }
1109 if (PyDict_SetItem(dict, t, v) < 0) {
1110 Py_DECREF(t);
1111 Py_DECREF(v);
1112 return -1;
1113 }
1114 Py_DECREF(v);
1115 }
1116 else
1117 arg = PyLong_AsLong(v);
1118 Py_DECREF(t);
1119 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120}
1121
1122static int
1123compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125{
1126 int arg = compiler_add_o(c, dict, o);
1127 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001128 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 return compiler_addop_i(c, opcode, arg);
1130}
1131
1132static int
1133compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135{
1136 int arg;
1137 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1138 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 arg = compiler_add_o(c, dict, mangled);
1141 Py_DECREF(mangled);
1142 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001143 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 return compiler_addop_i(c, opcode, arg);
1145}
1146
1147/* Add an opcode with an integer argument.
1148 Returns 0 on failure, 1 on success.
1149*/
1150
1151static int
1152compiler_addop_i(struct compiler *c, int opcode, int oparg)
1153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 struct instr *i;
1155 int off;
1156 off = compiler_next_instr(c, c->u->u_curblock);
1157 if (off < 0)
1158 return 0;
1159 i = &c->u->u_curblock->b_instr[off];
1160 i->i_opcode = opcode;
1161 i->i_oparg = oparg;
1162 i->i_hasarg = 1;
1163 compiler_set_lineno(c, off);
1164 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165}
1166
1167static int
1168compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 struct instr *i;
1171 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 assert(b != NULL);
1174 off = compiler_next_instr(c, c->u->u_curblock);
1175 if (off < 0)
1176 return 0;
1177 i = &c->u->u_curblock->b_instr[off];
1178 i->i_opcode = opcode;
1179 i->i_target = b;
1180 i->i_hasarg = 1;
1181 if (absolute)
1182 i->i_jabs = 1;
1183 else
1184 i->i_jrel = 1;
1185 compiler_set_lineno(c, off);
1186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187}
1188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1190 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191 it as the current block. NEXT_BLOCK() also creates an implicit jump
1192 from the current block to the new block.
1193*/
1194
Thomas Wouters89f507f2006-12-13 04:49:30 +00001195/* The returns inside these macros make it impossible to decref objects
1196 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197*/
1198
1199
1200#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (compiler_use_new_block((C)) == NULL) \
1202 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203}
1204
1205#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (compiler_next_block((C)) == NULL) \
1207 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208}
1209
1210#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (!compiler_addop((C), (OP))) \
1212 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213}
1214
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001215#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (!compiler_addop((C), (OP))) { \
1217 compiler_exit_scope(c); \
1218 return 0; \
1219 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001220}
1221
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1224 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225}
1226
1227#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
1232#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (!compiler_addop_i((C), (OP), (O))) \
1234 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!compiler_addop_j((C), (OP), (O), 1)) \
1239 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240}
1241
1242#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (!compiler_addop_j((C), (OP), (O), 0)) \
1244 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245}
1246
1247/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1248 the ASDL name to synthesize the name of the C type and the visit function.
1249*/
1250
1251#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (!compiler_visit_ ## TYPE((C), (V))) \
1253 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254}
1255
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001256#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (!compiler_visit_ ## TYPE((C), (V))) { \
1258 compiler_exit_scope(c); \
1259 return 0; \
1260 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001261}
1262
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!compiler_visit_slice((C), (V), (CTX))) \
1265 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001266}
1267
1268#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 int _i; \
1270 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1271 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1272 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1273 if (!compiler_visit_ ## TYPE((C), elt)) \
1274 return 0; \
1275 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001278#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 int _i; \
1280 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1281 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1282 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1283 if (!compiler_visit_ ## TYPE((C), elt)) { \
1284 compiler_exit_scope(c); \
1285 return 0; \
1286 } \
1287 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001288}
1289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290static int
1291compiler_isdocstring(stmt_ty s)
1292{
1293 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001294 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 return s->v.Expr.value->kind == Str_kind;
1296}
1297
1298/* Compile a sequence of statements, checking for a docstring. */
1299
1300static int
1301compiler_body(struct compiler *c, asdl_seq *stmts)
1302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 int i = 0;
1304 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (!asdl_seq_LEN(stmts))
1307 return 1;
1308 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001309 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* don't generate docstrings if -OO */
1311 i = 1;
1312 VISIT(c, expr, st->v.Expr.value);
1313 if (!compiler_nameop(c, __doc__, Store))
1314 return 0;
1315 }
1316 for (; i < asdl_seq_LEN(stmts); i++)
1317 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1318 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319}
1320
1321static PyCodeObject *
1322compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 PyCodeObject *co;
1325 int addNone = 1;
1326 static PyObject *module;
1327 if (!module) {
1328 module = PyUnicode_InternFromString("<module>");
1329 if (!module)
1330 return NULL;
1331 }
1332 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001333 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return NULL;
1335 switch (mod->kind) {
1336 case Module_kind:
1337 if (!compiler_body(c, mod->v.Module.body)) {
1338 compiler_exit_scope(c);
1339 return 0;
1340 }
1341 break;
1342 case Interactive_kind:
1343 c->c_interactive = 1;
1344 VISIT_SEQ_IN_SCOPE(c, stmt,
1345 mod->v.Interactive.body);
1346 break;
1347 case Expression_kind:
1348 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1349 addNone = 0;
1350 break;
1351 case Suite_kind:
1352 PyErr_SetString(PyExc_SystemError,
1353 "suite should not be possible");
1354 return 0;
1355 default:
1356 PyErr_Format(PyExc_SystemError,
1357 "module kind %d should not be possible",
1358 mod->kind);
1359 return 0;
1360 }
1361 co = assemble(c, addNone);
1362 compiler_exit_scope(c);
1363 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001364}
1365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366/* The test for LOCAL must come before the test for FREE in order to
1367 handle classes where name is both local and free. The local var is
1368 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001369*/
1370
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371static int
1372get_ref_type(struct compiler *c, PyObject *name)
1373{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001374 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001375 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1376 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1377 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001378 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (scope == 0) {
1380 char buf[350];
1381 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001382 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 "symbols: %s\nlocals: %s\nglobals: %s",
1384 PyBytes_AS_STRING(name),
1385 PyBytes_AS_STRING(c->u->u_name),
1386 PyObject_REPR(c->u->u_ste->ste_id),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject_REPR(c->u->u_ste->ste_symbols),
1388 PyObject_REPR(c->u->u_varnames),
1389 PyObject_REPR(c->u->u_names)
1390 );
1391 Py_FatalError(buf);
1392 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395}
1396
1397static int
1398compiler_lookup_arg(PyObject *dict, PyObject *name)
1399{
1400 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001403 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001405 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001407 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001408 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409}
1410
1411static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001412compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001415 if (qualname == NULL)
1416 qualname = co->co_name;
1417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (free == 0) {
1419 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001420 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 ADDOP_I(c, MAKE_FUNCTION, args);
1422 return 1;
1423 }
1424 for (i = 0; i < free; ++i) {
1425 /* Bypass com_addop_varname because it will generate
1426 LOAD_DEREF but LOAD_CLOSURE is needed.
1427 */
1428 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1429 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /* Special case: If a class contains a method with a
1432 free variable that has the same name as a method,
1433 the name will be considered free *and* local in the
1434 class. It should be handled by the closure, as
1435 well as by the normal name loookup logic.
1436 */
1437 reftype = get_ref_type(c, name);
1438 if (reftype == CELL)
1439 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1440 else /* (reftype == FREE) */
1441 arg = compiler_lookup_arg(c->u->u_freevars, name);
1442 if (arg == -1) {
1443 fprintf(stderr,
1444 "lookup %s in %s %d %d\n"
1445 "freevars of %s: %s\n",
1446 PyObject_REPR(name),
1447 PyBytes_AS_STRING(c->u->u_name),
1448 reftype, arg,
1449 _PyUnicode_AsString(co->co_name),
1450 PyObject_REPR(co->co_freevars));
1451 Py_FatalError("compiler_make_closure()");
1452 }
1453 ADDOP_I(c, LOAD_CLOSURE, arg);
1454 }
1455 ADDOP_I(c, BUILD_TUPLE, free);
1456 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001457 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 ADDOP_I(c, MAKE_CLOSURE, args);
1459 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460}
1461
1462static int
1463compiler_decorators(struct compiler *c, asdl_seq* decos)
1464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!decos)
1468 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1471 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1472 }
1473 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
1476static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001477compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 int i, default_count = 0;
1481 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1482 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1483 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1484 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001485 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1486 if (!mangled)
1487 return -1;
1488 ADDOP_O(c, LOAD_CONST, mangled, consts);
1489 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (!compiler_visit_expr(c, default_)) {
1491 return -1;
1492 }
1493 default_count++;
1494 }
1495 }
1496 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001497}
1498
1499static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001500compiler_visit_argannotation(struct compiler *c, identifier id,
1501 expr_ty annotation, PyObject *names)
1502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (annotation) {
1504 VISIT(c, expr, annotation);
1505 if (PyList_Append(names, id))
1506 return -1;
1507 }
1508 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001509}
1510
1511static int
1512compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1513 PyObject *names)
1514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 int i, error;
1516 for (i = 0; i < asdl_seq_LEN(args); i++) {
1517 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1518 error = compiler_visit_argannotation(
1519 c,
1520 arg->arg,
1521 arg->annotation,
1522 names);
1523 if (error)
1524 return error;
1525 }
1526 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001527}
1528
1529static int
1530compiler_visit_annotations(struct compiler *c, arguments_ty args,
1531 expr_ty returns)
1532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 /* Push arg annotations and a list of the argument names. Return the #
1534 of items pushed. The expressions are evaluated out-of-order wrt the
1535 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1538 */
1539 static identifier return_str;
1540 PyObject *names;
1541 int len;
1542 names = PyList_New(0);
1543 if (!names)
1544 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (compiler_visit_argannotations(c, args->args, names))
1547 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001548 if (args->vararg && args->vararg->annotation &&
1549 compiler_visit_argannotation(c, args->vararg->arg,
1550 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 goto error;
1552 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1553 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001554 if (args->kwarg && args->kwarg->annotation &&
1555 compiler_visit_argannotation(c, args->kwarg->arg,
1556 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (!return_str) {
1560 return_str = PyUnicode_InternFromString("return");
1561 if (!return_str)
1562 goto error;
1563 }
1564 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1565 goto error;
1566 }
1567
1568 len = PyList_GET_SIZE(names);
1569 if (len > 65534) {
1570 /* len must fit in 16 bits, and len is incremented below */
1571 PyErr_SetString(PyExc_SyntaxError,
1572 "too many annotations");
1573 goto error;
1574 }
1575 if (len) {
1576 /* convert names to a tuple and place on stack */
1577 PyObject *elt;
1578 int i;
1579 PyObject *s = PyTuple_New(len);
1580 if (!s)
1581 goto error;
1582 for (i = 0; i < len; i++) {
1583 elt = PyList_GET_ITEM(names, i);
1584 Py_INCREF(elt);
1585 PyTuple_SET_ITEM(s, i, elt);
1586 }
1587 ADDOP_O(c, LOAD_CONST, s, consts);
1588 Py_DECREF(s);
1589 len++; /* include the just-pushed tuple */
1590 }
1591 Py_DECREF(names);
1592 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001593
1594error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 Py_DECREF(names);
1596 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001597}
1598
1599static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600compiler_function(struct compiler *c, stmt_ty s)
1601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001603 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 arguments_ty args = s->v.FunctionDef.args;
1605 expr_ty returns = s->v.FunctionDef.returns;
1606 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1607 stmt_ty st;
1608 int i, n, docstring, kw_default_count = 0, arglength;
1609 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (!compiler_decorators(c, decos))
1614 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001615 if (args->defaults)
1616 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (args->kwonlyargs) {
1618 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1619 args->kw_defaults);
1620 if (res < 0)
1621 return 0;
1622 kw_default_count = res;
1623 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 num_annotations = compiler_visit_annotations(c, args, returns);
1625 if (num_annotations < 0)
1626 return 0;
1627 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001628
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001629 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1630 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 s->lineno))
1632 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1635 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001636 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 first_const = st->v.Expr.value->v.Str.s;
1638 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1639 compiler_exit_scope(c);
1640 return 0;
1641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 c->u->u_argcount = asdl_seq_LEN(args->args);
1644 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1645 n = asdl_seq_LEN(s->v.FunctionDef.body);
1646 /* if there was a docstring, we need to skip the first statement */
1647 for (i = docstring; i < n; i++) {
1648 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1649 VISIT_IN_SCOPE(c, stmt, st);
1650 }
1651 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001652 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001654 if (qualname == NULL || co == NULL) {
1655 Py_XDECREF(qualname);
1656 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001658 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 arglength = asdl_seq_LEN(args->defaults);
1661 arglength |= kw_default_count << 8;
1662 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001663 compiler_make_closure(c, co, arglength, qualname);
1664 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* decorators */
1668 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1669 ADDOP_I(c, CALL_FUNCTION, 1);
1670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673}
1674
1675static int
1676compiler_class(struct compiler *c, stmt_ty s)
1677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyCodeObject *co;
1679 PyObject *str;
1680 int i;
1681 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 if (!compiler_decorators(c, decos))
1684 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 /* ultimately generate code for:
1687 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1688 where:
1689 <func> is a function/closure created from the class body;
1690 it has a single argument (__locals__) where the dict
1691 (or MutableSequence) representing the locals is passed
1692 <name> is the class name
1693 <bases> is the positional arguments and *varargs argument
1694 <keywords> is the keyword arguments and **kwds argument
1695 This borrows from compiler_call.
1696 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001699 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1700 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 return 0;
1702 /* this block represents what we do in the new scope */
1703 {
1704 /* use the class name for name mangling */
1705 Py_INCREF(s->v.ClassDef.name);
1706 Py_XDECREF(c->u->u_private);
1707 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 /* load (global) __name__ ... */
1709 str = PyUnicode_InternFromString("__name__");
1710 if (!str || !compiler_nameop(c, str, Load)) {
1711 Py_XDECREF(str);
1712 compiler_exit_scope(c);
1713 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001714 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 Py_DECREF(str);
1716 /* ... and store it as __module__ */
1717 str = PyUnicode_InternFromString("__module__");
1718 if (!str || !compiler_nameop(c, str, Store)) {
1719 Py_XDECREF(str);
1720 compiler_exit_scope(c);
1721 return 0;
1722 }
1723 Py_DECREF(str);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001724 /* store the __qualname__ */
1725 str = compiler_scope_qualname(c);
1726 if (!str) {
1727 compiler_exit_scope(c);
1728 return 0;
1729 }
1730 ADDOP_O(c, LOAD_CONST, str, consts);
1731 Py_DECREF(str);
1732 str = PyUnicode_InternFromString("__qualname__");
1733 if (!str || !compiler_nameop(c, str, Store)) {
1734 Py_XDECREF(str);
1735 compiler_exit_scope(c);
1736 return 0;
1737 }
1738 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* compile the body proper */
1740 if (!compiler_body(c, s->v.ClassDef.body)) {
1741 compiler_exit_scope(c);
1742 return 0;
1743 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001744 if (c->u->u_ste->ste_needs_class_closure) {
1745 /* return the (empty) __class__ cell */
1746 str = PyUnicode_InternFromString("__class__");
1747 if (str == NULL) {
1748 compiler_exit_scope(c);
1749 return 0;
1750 }
1751 i = compiler_lookup_arg(c->u->u_cellvars, str);
1752 Py_DECREF(str);
1753 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* Return the cell where to store __class__ */
1755 ADDOP_I(c, LOAD_CLOSURE, i);
1756 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001757 else {
1758 assert(PyDict_Size(c->u->u_cellvars) == 0);
1759 /* This happens when nobody references the cell. Return None. */
1760 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1763 /* create the code object */
1764 co = assemble(c, 1);
1765 }
1766 /* leave the new scope */
1767 compiler_exit_scope(c);
1768 if (co == NULL)
1769 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* 2. load the 'build_class' function */
1772 ADDOP(c, LOAD_BUILD_CLASS);
1773
1774 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001775 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 Py_DECREF(co);
1777
1778 /* 4. load class name */
1779 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1780
1781 /* 5. generate the rest of the code for the call */
1782 if (!compiler_call_helper(c, 2,
1783 s->v.ClassDef.bases,
1784 s->v.ClassDef.keywords,
1785 s->v.ClassDef.starargs,
1786 s->v.ClassDef.kwargs))
1787 return 0;
1788
1789 /* 6. apply decorators */
1790 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1791 ADDOP_I(c, CALL_FUNCTION, 1);
1792 }
1793
1794 /* 7. store into <name> */
1795 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1796 return 0;
1797 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798}
1799
1800static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001801compiler_ifexp(struct compiler *c, expr_ty e)
1802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 basicblock *end, *next;
1804
1805 assert(e->kind == IfExp_kind);
1806 end = compiler_new_block(c);
1807 if (end == NULL)
1808 return 0;
1809 next = compiler_new_block(c);
1810 if (next == NULL)
1811 return 0;
1812 VISIT(c, expr, e->v.IfExp.test);
1813 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1814 VISIT(c, expr, e->v.IfExp.body);
1815 ADDOP_JREL(c, JUMP_FORWARD, end);
1816 compiler_use_next_block(c, next);
1817 VISIT(c, expr, e->v.IfExp.orelse);
1818 compiler_use_next_block(c, end);
1819 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001820}
1821
1822static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823compiler_lambda(struct compiler *c, expr_ty e)
1824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001826 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 static identifier name;
1828 int kw_default_count = 0, arglength;
1829 arguments_ty args = e->v.Lambda.args;
1830 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (!name) {
1833 name = PyUnicode_InternFromString("<lambda>");
1834 if (!name)
1835 return 0;
1836 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001838 if (args->defaults)
1839 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (args->kwonlyargs) {
1841 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1842 args->kw_defaults);
1843 if (res < 0) return 0;
1844 kw_default_count = res;
1845 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001846 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION,
1847 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 /* Make None the first constant, so the lambda can't have a
1851 docstring. */
1852 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1853 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 c->u->u_argcount = asdl_seq_LEN(args->args);
1856 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1857 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1858 if (c->u->u_ste->ste_generator) {
1859 ADDOP_IN_SCOPE(c, POP_TOP);
1860 }
1861 else {
1862 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1863 }
1864 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001865 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001867 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 arglength = asdl_seq_LEN(args->defaults);
1871 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001872 compiler_make_closure(c, co, arglength, qualname);
1873 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 Py_DECREF(co);
1875
1876 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877}
1878
1879static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880compiler_if(struct compiler *c, stmt_ty s)
1881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 basicblock *end, *next;
1883 int constant;
1884 assert(s->kind == If_kind);
1885 end = compiler_new_block(c);
1886 if (end == NULL)
1887 return 0;
1888
Georg Brandl8334fd92010-12-04 10:26:46 +00001889 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* constant = 0: "if 0"
1891 * constant = 1: "if 1", "if 2", ...
1892 * constant = -1: rest */
1893 if (constant == 0) {
1894 if (s->v.If.orelse)
1895 VISIT_SEQ(c, stmt, s->v.If.orelse);
1896 } else if (constant == 1) {
1897 VISIT_SEQ(c, stmt, s->v.If.body);
1898 } else {
1899 if (s->v.If.orelse) {
1900 next = compiler_new_block(c);
1901 if (next == NULL)
1902 return 0;
1903 }
1904 else
1905 next = end;
1906 VISIT(c, expr, s->v.If.test);
1907 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1908 VISIT_SEQ(c, stmt, s->v.If.body);
1909 ADDOP_JREL(c, JUMP_FORWARD, end);
1910 if (s->v.If.orelse) {
1911 compiler_use_next_block(c, next);
1912 VISIT_SEQ(c, stmt, s->v.If.orelse);
1913 }
1914 }
1915 compiler_use_next_block(c, end);
1916 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917}
1918
1919static int
1920compiler_for(struct compiler *c, stmt_ty s)
1921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 start = compiler_new_block(c);
1925 cleanup = compiler_new_block(c);
1926 end = compiler_new_block(c);
1927 if (start == NULL || end == NULL || cleanup == NULL)
1928 return 0;
1929 ADDOP_JREL(c, SETUP_LOOP, end);
1930 if (!compiler_push_fblock(c, LOOP, start))
1931 return 0;
1932 VISIT(c, expr, s->v.For.iter);
1933 ADDOP(c, GET_ITER);
1934 compiler_use_next_block(c, start);
1935 ADDOP_JREL(c, FOR_ITER, cleanup);
1936 VISIT(c, expr, s->v.For.target);
1937 VISIT_SEQ(c, stmt, s->v.For.body);
1938 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1939 compiler_use_next_block(c, cleanup);
1940 ADDOP(c, POP_BLOCK);
1941 compiler_pop_fblock(c, LOOP, start);
1942 VISIT_SEQ(c, stmt, s->v.For.orelse);
1943 compiler_use_next_block(c, end);
1944 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945}
1946
1947static int
1948compiler_while(struct compiler *c, stmt_ty s)
1949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001951 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (constant == 0) {
1954 if (s->v.While.orelse)
1955 VISIT_SEQ(c, stmt, s->v.While.orelse);
1956 return 1;
1957 }
1958 loop = compiler_new_block(c);
1959 end = compiler_new_block(c);
1960 if (constant == -1) {
1961 anchor = compiler_new_block(c);
1962 if (anchor == NULL)
1963 return 0;
1964 }
1965 if (loop == NULL || end == NULL)
1966 return 0;
1967 if (s->v.While.orelse) {
1968 orelse = compiler_new_block(c);
1969 if (orelse == NULL)
1970 return 0;
1971 }
1972 else
1973 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 ADDOP_JREL(c, SETUP_LOOP, end);
1976 compiler_use_next_block(c, loop);
1977 if (!compiler_push_fblock(c, LOOP, loop))
1978 return 0;
1979 if (constant == -1) {
1980 VISIT(c, expr, s->v.While.test);
1981 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
1982 }
1983 VISIT_SEQ(c, stmt, s->v.While.body);
1984 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 /* XXX should the two POP instructions be in a separate block
1987 if there is no else clause ?
1988 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (constant == -1) {
1991 compiler_use_next_block(c, anchor);
1992 ADDOP(c, POP_BLOCK);
1993 }
1994 compiler_pop_fblock(c, LOOP, loop);
1995 if (orelse != NULL) /* what if orelse is just pass? */
1996 VISIT_SEQ(c, stmt, s->v.While.orelse);
1997 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000}
2001
2002static int
2003compiler_continue(struct compiler *c)
2004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2006 static const char IN_FINALLY_ERROR_MSG[] =
2007 "'continue' not supported inside 'finally' clause";
2008 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (!c->u->u_nfblocks)
2011 return compiler_error(c, LOOP_ERROR_MSG);
2012 i = c->u->u_nfblocks - 1;
2013 switch (c->u->u_fblock[i].fb_type) {
2014 case LOOP:
2015 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2016 break;
2017 case EXCEPT:
2018 case FINALLY_TRY:
2019 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2020 /* Prevent continue anywhere under a finally
2021 even if hidden in a sub-try or except. */
2022 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2023 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2024 }
2025 if (i == -1)
2026 return compiler_error(c, LOOP_ERROR_MSG);
2027 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2028 break;
2029 case FINALLY_END:
2030 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2031 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034}
2035
2036/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037
2038 SETUP_FINALLY L
2039 <code for body>
2040 POP_BLOCK
2041 LOAD_CONST <None>
2042 L: <code for finalbody>
2043 END_FINALLY
2044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002045 The special instructions use the block stack. Each block
2046 stack entry contains the instruction that created it (here
2047 SETUP_FINALLY), the level of the value stack at the time the
2048 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 Pushes the current value stack level and the label
2052 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 Pops en entry from the block stack, and pops the value
2055 stack until its level is the same as indicated on the
2056 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 Pops a variable number of entries from the *value* stack
2059 and re-raises the exception they specify. The number of
2060 entries popped depends on the (pseudo) exception type.
2061
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062 The block stack is unwound when an exception is raised:
2063 when a SETUP_FINALLY entry is found, the exception is pushed
2064 onto the value stack (and the exception condition is cleared),
2065 and the interpreter jumps to the label gotten from the block
2066 stack.
2067*/
2068
2069static int
2070compiler_try_finally(struct compiler *c, stmt_ty s)
2071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 basicblock *body, *end;
2073 body = compiler_new_block(c);
2074 end = compiler_new_block(c);
2075 if (body == NULL || end == NULL)
2076 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 ADDOP_JREL(c, SETUP_FINALLY, end);
2079 compiler_use_next_block(c, body);
2080 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2081 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002082 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2083 if (!compiler_try_except(c, s))
2084 return 0;
2085 }
2086 else {
2087 VISIT_SEQ(c, stmt, s->v.Try.body);
2088 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 ADDOP(c, POP_BLOCK);
2090 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2093 compiler_use_next_block(c, end);
2094 if (!compiler_push_fblock(c, FINALLY_END, end))
2095 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002096 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 ADDOP(c, END_FINALLY);
2098 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101}
2102
2103/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002104 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 (The contents of the value stack is shown in [], with the top
2106 at the right; 'tb' is trace-back info, 'val' the exception's
2107 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108
2109 Value stack Label Instruction Argument
2110 [] SETUP_EXCEPT L1
2111 [] <code for S>
2112 [] POP_BLOCK
2113 [] JUMP_FORWARD L0
2114
2115 [tb, val, exc] L1: DUP )
2116 [tb, val, exc, exc] <evaluate E1> )
2117 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2118 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2119 [tb, val, exc] POP
2120 [tb, val] <assign to V1> (or POP if no V1)
2121 [tb] POP
2122 [] <code for S1>
2123 JUMP_FORWARD L0
2124
2125 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 .............................etc.......................
2127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2129
2130 [] L0: <next statement>
2131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 Of course, parts are not generated if Vi or Ei is not present.
2133*/
2134static int
2135compiler_try_except(struct compiler *c, stmt_ty s)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 basicblock *body, *orelse, *except, *end;
2138 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 body = compiler_new_block(c);
2141 except = compiler_new_block(c);
2142 orelse = compiler_new_block(c);
2143 end = compiler_new_block(c);
2144 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2145 return 0;
2146 ADDOP_JREL(c, SETUP_EXCEPT, except);
2147 compiler_use_next_block(c, body);
2148 if (!compiler_push_fblock(c, EXCEPT, body))
2149 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002150 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 ADDOP(c, POP_BLOCK);
2152 compiler_pop_fblock(c, EXCEPT, body);
2153 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002154 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 compiler_use_next_block(c, except);
2156 for (i = 0; i < n; i++) {
2157 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002158 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (!handler->v.ExceptHandler.type && i < n-1)
2160 return compiler_error(c, "default 'except:' must be last");
2161 c->u->u_lineno_set = 0;
2162 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002163 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 except = compiler_new_block(c);
2165 if (except == NULL)
2166 return 0;
2167 if (handler->v.ExceptHandler.type) {
2168 ADDOP(c, DUP_TOP);
2169 VISIT(c, expr, handler->v.ExceptHandler.type);
2170 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2171 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2172 }
2173 ADDOP(c, POP_TOP);
2174 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002175 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002176
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002177 cleanup_end = compiler_new_block(c);
2178 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002179 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002180 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002181
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002182 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2183 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002185 /*
2186 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002187 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002188 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002189 try:
2190 # body
2191 finally:
2192 name = None
2193 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002194 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002196 /* second try: */
2197 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2198 compiler_use_next_block(c, cleanup_body);
2199 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2200 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002202 /* second # body */
2203 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2204 ADDOP(c, POP_BLOCK);
2205 ADDOP(c, POP_EXCEPT);
2206 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002208 /* finally: */
2209 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2210 compiler_use_next_block(c, cleanup_end);
2211 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2212 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002214 /* name = None */
2215 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2216 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002218 /* del name */
2219 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002221 ADDOP(c, END_FINALLY);
2222 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 }
2224 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002225 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002227 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002228 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230
Guido van Rossumb940e112007-01-10 16:19:56 +00002231 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002232 ADDOP(c, POP_TOP);
2233 compiler_use_next_block(c, cleanup_body);
2234 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2235 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002237 ADDOP(c, POP_EXCEPT);
2238 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 }
2240 ADDOP_JREL(c, JUMP_FORWARD, end);
2241 compiler_use_next_block(c, except);
2242 }
2243 ADDOP(c, END_FINALLY);
2244 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002245 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 compiler_use_next_block(c, end);
2247 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248}
2249
2250static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002251compiler_try(struct compiler *c, stmt_ty s) {
2252 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2253 return compiler_try_finally(c, s);
2254 else
2255 return compiler_try_except(c, s);
2256}
2257
2258
2259static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260compiler_import_as(struct compiler *c, identifier name, identifier asname)
2261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 /* The IMPORT_NAME opcode was already generated. This function
2263 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 If there is a dot in name, we need to split it and emit a
2266 LOAD_ATTR for each name.
2267 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2269 PyUnicode_GET_LENGTH(name), 1);
2270 if (dot == -2)
2271 return -1;
2272 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 Py_ssize_t pos = dot + 1;
2275 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 dot = PyUnicode_FindChar(name, '.', pos,
2278 PyUnicode_GET_LENGTH(name), 1);
2279 if (dot == -2)
2280 return -1;
2281 attr = PyUnicode_Substring(name, pos,
2282 (dot != -1) ? dot :
2283 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (!attr)
2285 return -1;
2286 ADDOP_O(c, LOAD_ATTR, attr, names);
2287 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002288 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 }
2290 }
2291 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292}
2293
2294static int
2295compiler_import(struct compiler *c, stmt_ty s)
2296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* The Import node stores a module name like a.b.c as a single
2298 string. This is convenient for all cases except
2299 import a.b.c as d
2300 where we need to parse that string to extract the individual
2301 module names.
2302 XXX Perhaps change the representation to make this case simpler?
2303 */
2304 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 for (i = 0; i < n; i++) {
2307 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2308 int r;
2309 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 level = PyLong_FromLong(0);
2312 if (level == NULL)
2313 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 ADDOP_O(c, LOAD_CONST, level, consts);
2316 Py_DECREF(level);
2317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2318 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 if (alias->asname) {
2321 r = compiler_import_as(c, alias->name, alias->asname);
2322 if (!r)
2323 return r;
2324 }
2325 else {
2326 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002327 Py_ssize_t dot = PyUnicode_FindChar(
2328 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002329 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002330 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002331 if (tmp == NULL)
2332 return 0;
2333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002335 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 Py_DECREF(tmp);
2337 }
2338 if (!r)
2339 return r;
2340 }
2341 }
2342 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343}
2344
2345static int
2346compiler_from_import(struct compiler *c, stmt_ty s)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 PyObject *names = PyTuple_New(n);
2351 PyObject *level;
2352 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (!empty_string) {
2355 empty_string = PyUnicode_FromString("");
2356 if (!empty_string)
2357 return 0;
2358 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (!names)
2361 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 level = PyLong_FromLong(s->v.ImportFrom.level);
2364 if (!level) {
2365 Py_DECREF(names);
2366 return 0;
2367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* build up the names */
2370 for (i = 0; i < n; i++) {
2371 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2372 Py_INCREF(alias->name);
2373 PyTuple_SET_ITEM(names, i, alias->name);
2374 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2377 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2378 Py_DECREF(level);
2379 Py_DECREF(names);
2380 return compiler_error(c, "from __future__ imports must occur "
2381 "at the beginning of the file");
2382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 ADDOP_O(c, LOAD_CONST, level, consts);
2385 Py_DECREF(level);
2386 ADDOP_O(c, LOAD_CONST, names, consts);
2387 Py_DECREF(names);
2388 if (s->v.ImportFrom.module) {
2389 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2390 }
2391 else {
2392 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2393 }
2394 for (i = 0; i < n; i++) {
2395 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2396 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002398 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 assert(n == 1);
2400 ADDOP(c, IMPORT_STAR);
2401 return 1;
2402 }
2403
2404 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2405 store_name = alias->name;
2406 if (alias->asname)
2407 store_name = alias->asname;
2408
2409 if (!compiler_nameop(c, store_name, Store)) {
2410 Py_DECREF(names);
2411 return 0;
2412 }
2413 }
2414 /* remove imported module */
2415 ADDOP(c, POP_TOP);
2416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417}
2418
2419static int
2420compiler_assert(struct compiler *c, stmt_ty s)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 static PyObject *assertion_error = NULL;
2423 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002424 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425
Georg Brandl8334fd92010-12-04 10:26:46 +00002426 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return 1;
2428 if (assertion_error == NULL) {
2429 assertion_error = PyUnicode_InternFromString("AssertionError");
2430 if (assertion_error == NULL)
2431 return 0;
2432 }
2433 if (s->v.Assert.test->kind == Tuple_kind &&
2434 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002435 msg = PyUnicode_FromString("assertion is always true, "
2436 "perhaps remove parentheses?");
2437 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002439 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2440 c->c_filename, c->u->u_lineno,
2441 NULL, NULL) == -1) {
2442 Py_DECREF(msg);
2443 return 0;
2444 }
2445 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
2447 VISIT(c, expr, s->v.Assert.test);
2448 end = compiler_new_block(c);
2449 if (end == NULL)
2450 return 0;
2451 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2452 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2453 if (s->v.Assert.msg) {
2454 VISIT(c, expr, s->v.Assert.msg);
2455 ADDOP_I(c, CALL_FUNCTION, 1);
2456 }
2457 ADDOP_I(c, RAISE_VARARGS, 1);
2458 compiler_use_next_block(c, end);
2459 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460}
2461
2462static int
2463compiler_visit_stmt(struct compiler *c, stmt_ty s)
2464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* Always assign a lineno to the next instruction for a stmt. */
2468 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002469 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 switch (s->kind) {
2473 case FunctionDef_kind:
2474 return compiler_function(c, s);
2475 case ClassDef_kind:
2476 return compiler_class(c, s);
2477 case Return_kind:
2478 if (c->u->u_ste->ste_type != FunctionBlock)
2479 return compiler_error(c, "'return' outside function");
2480 if (s->v.Return.value) {
2481 VISIT(c, expr, s->v.Return.value);
2482 }
2483 else
2484 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2485 ADDOP(c, RETURN_VALUE);
2486 break;
2487 case Delete_kind:
2488 VISIT_SEQ(c, expr, s->v.Delete.targets)
2489 break;
2490 case Assign_kind:
2491 n = asdl_seq_LEN(s->v.Assign.targets);
2492 VISIT(c, expr, s->v.Assign.value);
2493 for (i = 0; i < n; i++) {
2494 if (i < n - 1)
2495 ADDOP(c, DUP_TOP);
2496 VISIT(c, expr,
2497 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2498 }
2499 break;
2500 case AugAssign_kind:
2501 return compiler_augassign(c, s);
2502 case For_kind:
2503 return compiler_for(c, s);
2504 case While_kind:
2505 return compiler_while(c, s);
2506 case If_kind:
2507 return compiler_if(c, s);
2508 case Raise_kind:
2509 n = 0;
2510 if (s->v.Raise.exc) {
2511 VISIT(c, expr, s->v.Raise.exc);
2512 n++;
2513 if (s->v.Raise.cause) {
2514 VISIT(c, expr, s->v.Raise.cause);
2515 n++;
2516 }
2517 }
2518 ADDOP_I(c, RAISE_VARARGS, n);
2519 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002520 case Try_kind:
2521 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 case Assert_kind:
2523 return compiler_assert(c, s);
2524 case Import_kind:
2525 return compiler_import(c, s);
2526 case ImportFrom_kind:
2527 return compiler_from_import(c, s);
2528 case Global_kind:
2529 case Nonlocal_kind:
2530 break;
2531 case Expr_kind:
2532 if (c->c_interactive && c->c_nestlevel <= 1) {
2533 VISIT(c, expr, s->v.Expr.value);
2534 ADDOP(c, PRINT_EXPR);
2535 }
2536 else if (s->v.Expr.value->kind != Str_kind &&
2537 s->v.Expr.value->kind != Num_kind) {
2538 VISIT(c, expr, s->v.Expr.value);
2539 ADDOP(c, POP_TOP);
2540 }
2541 break;
2542 case Pass_kind:
2543 break;
2544 case Break_kind:
2545 if (!compiler_in_loop(c))
2546 return compiler_error(c, "'break' outside loop");
2547 ADDOP(c, BREAK_LOOP);
2548 break;
2549 case Continue_kind:
2550 return compiler_continue(c);
2551 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002552 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 }
2554 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555}
2556
2557static int
2558unaryop(unaryop_ty op)
2559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 switch (op) {
2561 case Invert:
2562 return UNARY_INVERT;
2563 case Not:
2564 return UNARY_NOT;
2565 case UAdd:
2566 return UNARY_POSITIVE;
2567 case USub:
2568 return UNARY_NEGATIVE;
2569 default:
2570 PyErr_Format(PyExc_SystemError,
2571 "unary op %d should not be possible", op);
2572 return 0;
2573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574}
2575
2576static int
2577binop(struct compiler *c, operator_ty op)
2578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 switch (op) {
2580 case Add:
2581 return BINARY_ADD;
2582 case Sub:
2583 return BINARY_SUBTRACT;
2584 case Mult:
2585 return BINARY_MULTIPLY;
2586 case Div:
2587 return BINARY_TRUE_DIVIDE;
2588 case Mod:
2589 return BINARY_MODULO;
2590 case Pow:
2591 return BINARY_POWER;
2592 case LShift:
2593 return BINARY_LSHIFT;
2594 case RShift:
2595 return BINARY_RSHIFT;
2596 case BitOr:
2597 return BINARY_OR;
2598 case BitXor:
2599 return BINARY_XOR;
2600 case BitAnd:
2601 return BINARY_AND;
2602 case FloorDiv:
2603 return BINARY_FLOOR_DIVIDE;
2604 default:
2605 PyErr_Format(PyExc_SystemError,
2606 "binary op %d should not be possible", op);
2607 return 0;
2608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609}
2610
2611static int
2612cmpop(cmpop_ty op)
2613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 switch (op) {
2615 case Eq:
2616 return PyCmp_EQ;
2617 case NotEq:
2618 return PyCmp_NE;
2619 case Lt:
2620 return PyCmp_LT;
2621 case LtE:
2622 return PyCmp_LE;
2623 case Gt:
2624 return PyCmp_GT;
2625 case GtE:
2626 return PyCmp_GE;
2627 case Is:
2628 return PyCmp_IS;
2629 case IsNot:
2630 return PyCmp_IS_NOT;
2631 case In:
2632 return PyCmp_IN;
2633 case NotIn:
2634 return PyCmp_NOT_IN;
2635 default:
2636 return PyCmp_BAD;
2637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638}
2639
2640static int
2641inplace_binop(struct compiler *c, operator_ty op)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 switch (op) {
2644 case Add:
2645 return INPLACE_ADD;
2646 case Sub:
2647 return INPLACE_SUBTRACT;
2648 case Mult:
2649 return INPLACE_MULTIPLY;
2650 case Div:
2651 return INPLACE_TRUE_DIVIDE;
2652 case Mod:
2653 return INPLACE_MODULO;
2654 case Pow:
2655 return INPLACE_POWER;
2656 case LShift:
2657 return INPLACE_LSHIFT;
2658 case RShift:
2659 return INPLACE_RSHIFT;
2660 case BitOr:
2661 return INPLACE_OR;
2662 case BitXor:
2663 return INPLACE_XOR;
2664 case BitAnd:
2665 return INPLACE_AND;
2666 case FloorDiv:
2667 return INPLACE_FLOOR_DIVIDE;
2668 default:
2669 PyErr_Format(PyExc_SystemError,
2670 "inplace binary op %d should not be possible", op);
2671 return 0;
2672 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673}
2674
2675static int
2676compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 int op, scope, arg;
2679 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyObject *dict = c->u->u_names;
2682 PyObject *mangled;
2683 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 mangled = _Py_Mangle(c->u->u_private, name);
2686 if (!mangled)
2687 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002688
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002689 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2690 PyUnicode_CompareWithASCIIString(name, "True") &&
2691 PyUnicode_CompareWithASCIIString(name, "False"));
2692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 op = 0;
2694 optype = OP_NAME;
2695 scope = PyST_GetScope(c->u->u_ste, mangled);
2696 switch (scope) {
2697 case FREE:
2698 dict = c->u->u_freevars;
2699 optype = OP_DEREF;
2700 break;
2701 case CELL:
2702 dict = c->u->u_cellvars;
2703 optype = OP_DEREF;
2704 break;
2705 case LOCAL:
2706 if (c->u->u_ste->ste_type == FunctionBlock)
2707 optype = OP_FAST;
2708 break;
2709 case GLOBAL_IMPLICIT:
2710 if (c->u->u_ste->ste_type == FunctionBlock &&
2711 !c->u->u_ste->ste_unoptimized)
2712 optype = OP_GLOBAL;
2713 break;
2714 case GLOBAL_EXPLICIT:
2715 optype = OP_GLOBAL;
2716 break;
2717 default:
2718 /* scope can be 0 */
2719 break;
2720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 switch (optype) {
2726 case OP_DEREF:
2727 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002728 case Load:
2729 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2730 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 case Store: op = STORE_DEREF; break;
2732 case AugLoad:
2733 case AugStore:
2734 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002735 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 case Param:
2737 default:
2738 PyErr_SetString(PyExc_SystemError,
2739 "param invalid for deref variable");
2740 return 0;
2741 }
2742 break;
2743 case OP_FAST:
2744 switch (ctx) {
2745 case Load: op = LOAD_FAST; break;
2746 case Store: op = STORE_FAST; break;
2747 case Del: op = DELETE_FAST; break;
2748 case AugLoad:
2749 case AugStore:
2750 break;
2751 case Param:
2752 default:
2753 PyErr_SetString(PyExc_SystemError,
2754 "param invalid for local variable");
2755 return 0;
2756 }
2757 ADDOP_O(c, op, mangled, varnames);
2758 Py_DECREF(mangled);
2759 return 1;
2760 case OP_GLOBAL:
2761 switch (ctx) {
2762 case Load: op = LOAD_GLOBAL; break;
2763 case Store: op = STORE_GLOBAL; break;
2764 case Del: op = DELETE_GLOBAL; break;
2765 case AugLoad:
2766 case AugStore:
2767 break;
2768 case Param:
2769 default:
2770 PyErr_SetString(PyExc_SystemError,
2771 "param invalid for global variable");
2772 return 0;
2773 }
2774 break;
2775 case OP_NAME:
2776 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002777 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 case Store: op = STORE_NAME; break;
2779 case Del: op = DELETE_NAME; break;
2780 case AugLoad:
2781 case AugStore:
2782 break;
2783 case Param:
2784 default:
2785 PyErr_SetString(PyExc_SystemError,
2786 "param invalid for name variable");
2787 return 0;
2788 }
2789 break;
2790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 assert(op);
2793 arg = compiler_add_o(c, dict, mangled);
2794 Py_DECREF(mangled);
2795 if (arg < 0)
2796 return 0;
2797 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798}
2799
2800static int
2801compiler_boolop(struct compiler *c, expr_ty e)
2802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 basicblock *end;
2804 int jumpi, i, n;
2805 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 assert(e->kind == BoolOp_kind);
2808 if (e->v.BoolOp.op == And)
2809 jumpi = JUMP_IF_FALSE_OR_POP;
2810 else
2811 jumpi = JUMP_IF_TRUE_OR_POP;
2812 end = compiler_new_block(c);
2813 if (end == NULL)
2814 return 0;
2815 s = e->v.BoolOp.values;
2816 n = asdl_seq_LEN(s) - 1;
2817 assert(n >= 0);
2818 for (i = 0; i < n; ++i) {
2819 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2820 ADDOP_JABS(c, jumpi, end);
2821 }
2822 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2823 compiler_use_next_block(c, end);
2824 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825}
2826
2827static int
2828compiler_list(struct compiler *c, expr_ty e)
2829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 int n = asdl_seq_LEN(e->v.List.elts);
2831 if (e->v.List.ctx == Store) {
2832 int i, seen_star = 0;
2833 for (i = 0; i < n; i++) {
2834 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2835 if (elt->kind == Starred_kind && !seen_star) {
2836 if ((i >= (1 << 8)) ||
2837 (n-i-1 >= (INT_MAX >> 8)))
2838 return compiler_error(c,
2839 "too many expressions in "
2840 "star-unpacking assignment");
2841 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2842 seen_star = 1;
2843 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2844 } else if (elt->kind == Starred_kind) {
2845 return compiler_error(c,
2846 "two starred expressions in assignment");
2847 }
2848 }
2849 if (!seen_star) {
2850 ADDOP_I(c, UNPACK_SEQUENCE, n);
2851 }
2852 }
2853 VISIT_SEQ(c, expr, e->v.List.elts);
2854 if (e->v.List.ctx == Load) {
2855 ADDOP_I(c, BUILD_LIST, n);
2856 }
2857 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858}
2859
2860static int
2861compiler_tuple(struct compiler *c, expr_ty e)
2862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 int n = asdl_seq_LEN(e->v.Tuple.elts);
2864 if (e->v.Tuple.ctx == Store) {
2865 int i, seen_star = 0;
2866 for (i = 0; i < n; i++) {
2867 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2868 if (elt->kind == Starred_kind && !seen_star) {
2869 if ((i >= (1 << 8)) ||
2870 (n-i-1 >= (INT_MAX >> 8)))
2871 return compiler_error(c,
2872 "too many expressions in "
2873 "star-unpacking assignment");
2874 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2875 seen_star = 1;
2876 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2877 } else if (elt->kind == Starred_kind) {
2878 return compiler_error(c,
2879 "two starred expressions in assignment");
2880 }
2881 }
2882 if (!seen_star) {
2883 ADDOP_I(c, UNPACK_SEQUENCE, n);
2884 }
2885 }
2886 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2887 if (e->v.Tuple.ctx == Load) {
2888 ADDOP_I(c, BUILD_TUPLE, n);
2889 }
2890 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891}
2892
2893static int
2894compiler_compare(struct compiler *c, expr_ty e)
2895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 int i, n;
2897 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2900 VISIT(c, expr, e->v.Compare.left);
2901 n = asdl_seq_LEN(e->v.Compare.ops);
2902 assert(n > 0);
2903 if (n > 1) {
2904 cleanup = compiler_new_block(c);
2905 if (cleanup == NULL)
2906 return 0;
2907 VISIT(c, expr,
2908 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2909 }
2910 for (i = 1; i < n; i++) {
2911 ADDOP(c, DUP_TOP);
2912 ADDOP(c, ROT_THREE);
2913 ADDOP_I(c, COMPARE_OP,
2914 cmpop((cmpop_ty)(asdl_seq_GET(
2915 e->v.Compare.ops, i - 1))));
2916 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2917 NEXT_BLOCK(c);
2918 if (i < (n - 1))
2919 VISIT(c, expr,
2920 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2921 }
2922 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2923 ADDOP_I(c, COMPARE_OP,
2924 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2925 if (n > 1) {
2926 basicblock *end = compiler_new_block(c);
2927 if (end == NULL)
2928 return 0;
2929 ADDOP_JREL(c, JUMP_FORWARD, end);
2930 compiler_use_next_block(c, cleanup);
2931 ADDOP(c, ROT_TWO);
2932 ADDOP(c, POP_TOP);
2933 compiler_use_next_block(c, end);
2934 }
2935 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936}
2937
2938static int
2939compiler_call(struct compiler *c, expr_ty e)
2940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 VISIT(c, expr, e->v.Call.func);
2942 return compiler_call_helper(c, 0,
2943 e->v.Call.args,
2944 e->v.Call.keywords,
2945 e->v.Call.starargs,
2946 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002947}
2948
2949/* shared code between compiler_call and compiler_class */
2950static int
2951compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 int n, /* Args already pushed */
2953 asdl_seq *args,
2954 asdl_seq *keywords,
2955 expr_ty starargs,
2956 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 n += asdl_seq_LEN(args);
2961 VISIT_SEQ(c, expr, args);
2962 if (keywords) {
2963 VISIT_SEQ(c, keyword, keywords);
2964 n |= asdl_seq_LEN(keywords) << 8;
2965 }
2966 if (starargs) {
2967 VISIT(c, expr, starargs);
2968 code |= 1;
2969 }
2970 if (kwargs) {
2971 VISIT(c, expr, kwargs);
2972 code |= 2;
2973 }
2974 switch (code) {
2975 case 0:
2976 ADDOP_I(c, CALL_FUNCTION, n);
2977 break;
2978 case 1:
2979 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2980 break;
2981 case 2:
2982 ADDOP_I(c, CALL_FUNCTION_KW, n);
2983 break;
2984 case 3:
2985 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2986 break;
2987 }
2988 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989}
2990
Nick Coghlan650f0d02007-04-15 12:05:43 +00002991
2992/* List and set comprehensions and generator expressions work by creating a
2993 nested function to perform the actual iteration. This means that the
2994 iteration variables don't leak into the current scope.
2995 The defined function is called immediately following its definition, with the
2996 result of that call being the result of the expression.
2997 The LC/SC version returns the populated container, while the GE version is
2998 flagged in symtable.c as a generator, so it returns the generator object
2999 when the function is called.
3000 This code *knows* that the loop cannot contain break, continue, or return,
3001 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3002
3003 Possible cleanups:
3004 - iterate over the generator sequence instead of using recursion
3005*/
3006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008compiler_comprehension_generator(struct compiler *c,
3009 asdl_seq *generators, int gen_index,
3010 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 /* generate code for the iterator, then each of the ifs,
3013 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 comprehension_ty gen;
3016 basicblock *start, *anchor, *skip, *if_cleanup;
3017 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 start = compiler_new_block(c);
3020 skip = compiler_new_block(c);
3021 if_cleanup = compiler_new_block(c);
3022 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3025 anchor == NULL)
3026 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 if (gen_index == 0) {
3031 /* Receive outermost iter as an implicit argument */
3032 c->u->u_argcount = 1;
3033 ADDOP_I(c, LOAD_FAST, 0);
3034 }
3035 else {
3036 /* Sub-iter - calculate on the fly */
3037 VISIT(c, expr, gen->iter);
3038 ADDOP(c, GET_ITER);
3039 }
3040 compiler_use_next_block(c, start);
3041 ADDOP_JREL(c, FOR_ITER, anchor);
3042 NEXT_BLOCK(c);
3043 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 /* XXX this needs to be cleaned up...a lot! */
3046 n = asdl_seq_LEN(gen->ifs);
3047 for (i = 0; i < n; i++) {
3048 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3049 VISIT(c, expr, e);
3050 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3051 NEXT_BLOCK(c);
3052 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (++gen_index < asdl_seq_LEN(generators))
3055 if (!compiler_comprehension_generator(c,
3056 generators, gen_index,
3057 elt, val, type))
3058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* only append after the last for generator */
3061 if (gen_index >= asdl_seq_LEN(generators)) {
3062 /* comprehension specific code */
3063 switch (type) {
3064 case COMP_GENEXP:
3065 VISIT(c, expr, elt);
3066 ADDOP(c, YIELD_VALUE);
3067 ADDOP(c, POP_TOP);
3068 break;
3069 case COMP_LISTCOMP:
3070 VISIT(c, expr, elt);
3071 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3072 break;
3073 case COMP_SETCOMP:
3074 VISIT(c, expr, elt);
3075 ADDOP_I(c, SET_ADD, gen_index + 1);
3076 break;
3077 case COMP_DICTCOMP:
3078 /* With 'd[k] = v', v is evaluated before k, so we do
3079 the same. */
3080 VISIT(c, expr, val);
3081 VISIT(c, expr, elt);
3082 ADDOP_I(c, MAP_ADD, gen_index + 1);
3083 break;
3084 default:
3085 return 0;
3086 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 compiler_use_next_block(c, skip);
3089 }
3090 compiler_use_next_block(c, if_cleanup);
3091 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3092 compiler_use_next_block(c, anchor);
3093
3094 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095}
3096
3097static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003098compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 PyCodeObject *co = NULL;
3102 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003103 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 outermost_iter = ((comprehension_ty)
3106 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003107
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003108 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3109 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 if (type != COMP_GENEXP) {
3113 int op;
3114 switch (type) {
3115 case COMP_LISTCOMP:
3116 op = BUILD_LIST;
3117 break;
3118 case COMP_SETCOMP:
3119 op = BUILD_SET;
3120 break;
3121 case COMP_DICTCOMP:
3122 op = BUILD_MAP;
3123 break;
3124 default:
3125 PyErr_Format(PyExc_SystemError,
3126 "unknown comprehension type %d", type);
3127 goto error_in_scope;
3128 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 ADDOP_I(c, op, 0);
3131 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 if (!compiler_comprehension_generator(c, generators, 0, elt,
3134 val, type))
3135 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 if (type != COMP_GENEXP) {
3138 ADDOP(c, RETURN_VALUE);
3139 }
3140
3141 co = assemble(c, 1);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003142 qualname = compiler_scope_qualname(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 compiler_exit_scope(c);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003144 if (qualname == NULL || co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 goto error;
3146
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003147 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003149 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 Py_DECREF(co);
3151
3152 VISIT(c, expr, outermost_iter);
3153 ADDOP(c, GET_ITER);
3154 ADDOP_I(c, CALL_FUNCTION, 1);
3155 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003156error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003158error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003159 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 Py_XDECREF(co);
3161 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003162}
3163
3164static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165compiler_genexp(struct compiler *c, expr_ty e)
3166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 static identifier name;
3168 if (!name) {
3169 name = PyUnicode_FromString("<genexpr>");
3170 if (!name)
3171 return 0;
3172 }
3173 assert(e->kind == GeneratorExp_kind);
3174 return compiler_comprehension(c, e, COMP_GENEXP, name,
3175 e->v.GeneratorExp.generators,
3176 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177}
3178
3179static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003180compiler_listcomp(struct compiler *c, expr_ty e)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 static identifier name;
3183 if (!name) {
3184 name = PyUnicode_FromString("<listcomp>");
3185 if (!name)
3186 return 0;
3187 }
3188 assert(e->kind == ListComp_kind);
3189 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3190 e->v.ListComp.generators,
3191 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003192}
3193
3194static int
3195compiler_setcomp(struct compiler *c, expr_ty e)
3196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 static identifier name;
3198 if (!name) {
3199 name = PyUnicode_FromString("<setcomp>");
3200 if (!name)
3201 return 0;
3202 }
3203 assert(e->kind == SetComp_kind);
3204 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3205 e->v.SetComp.generators,
3206 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003207}
3208
3209
3210static int
3211compiler_dictcomp(struct compiler *c, expr_ty e)
3212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 static identifier name;
3214 if (!name) {
3215 name = PyUnicode_FromString("<dictcomp>");
3216 if (!name)
3217 return 0;
3218 }
3219 assert(e->kind == DictComp_kind);
3220 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3221 e->v.DictComp.generators,
3222 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003223}
3224
3225
3226static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003227compiler_visit_keyword(struct compiler *c, keyword_ty k)
3228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3230 VISIT(c, expr, k->value);
3231 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232}
3233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235 whether they are true or false.
3236
3237 Return values: 1 for true, 0 for false, -1 for non-constant.
3238 */
3239
3240static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003241expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 char *id;
3244 switch (e->kind) {
3245 case Ellipsis_kind:
3246 return 1;
3247 case Num_kind:
3248 return PyObject_IsTrue(e->v.Num.n);
3249 case Str_kind:
3250 return PyObject_IsTrue(e->v.Str.s);
3251 case Name_kind:
3252 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003253 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003254 if (id && strcmp(id, "__debug__") == 0)
3255 return !c->c_optimize;
3256 return -1;
3257 case NameConstant_kind: {
3258 PyObject *o = e->v.NameConstant.value;
3259 if (o == Py_None)
3260 return 0;
3261 else if (o == Py_True)
3262 return 1;
3263 else if (o == Py_False)
3264 return 0;
3265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 default:
3267 return -1;
3268 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269}
3270
Guido van Rossumc2e20742006-02-27 22:32:47 +00003271/*
3272 Implements the with statement from PEP 343.
3273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003275
3276 with EXPR as VAR:
3277 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278
Guido van Rossumc2e20742006-02-27 22:32:47 +00003279 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280
Thomas Wouters477c8d52006-05-27 19:21:47 +00003281 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003282 exit = context.__exit__ # not calling it
3283 value = context.__enter__()
3284 try:
3285 VAR = value # if VAR present in the syntax
3286 BLOCK
3287 finally:
3288 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003290 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003292 exit(*exc)
3293 */
3294static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003295compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003296{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003297 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003298 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003299
3300 assert(s->kind == With_kind);
3301
Guido van Rossumc2e20742006-02-27 22:32:47 +00003302 block = compiler_new_block(c);
3303 finally = compiler_new_block(c);
3304 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003305 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003306
Thomas Wouters477c8d52006-05-27 19:21:47 +00003307 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003308 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003309 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003310
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003311 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003312 compiler_use_next_block(c, block);
3313 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003314 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003315 }
3316
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003317 if (item->optional_vars) {
3318 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003319 }
3320 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003322 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003323 }
3324
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003325 pos++;
3326 if (pos == asdl_seq_LEN(s->v.With.items))
3327 /* BLOCK code */
3328 VISIT_SEQ(c, stmt, s->v.With.body)
3329 else if (!compiler_with(c, s, pos))
3330 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003331
3332 /* End of try block; start the finally block */
3333 ADDOP(c, POP_BLOCK);
3334 compiler_pop_fblock(c, FINALLY_TRY, block);
3335
3336 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3337 compiler_use_next_block(c, finally);
3338 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003339 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003340
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003341 /* Finally block starts; context.__exit__ is on the stack under
3342 the exception or return information. Just issue our magic
3343 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003344 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003345
3346 /* Finally block ends. */
3347 ADDOP(c, END_FINALLY);
3348 compiler_pop_fblock(c, FINALLY_END, finally);
3349 return 1;
3350}
3351
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352static int
3353compiler_visit_expr(struct compiler *c, expr_ty e)
3354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 /* If expr e has a different line number than the last expr/stmt,
3358 set a new line number for the next instruction.
3359 */
3360 if (e->lineno > c->u->u_lineno) {
3361 c->u->u_lineno = e->lineno;
3362 c->u->u_lineno_set = 0;
3363 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003364 /* Updating the column offset is always harmless. */
3365 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 switch (e->kind) {
3367 case BoolOp_kind:
3368 return compiler_boolop(c, e);
3369 case BinOp_kind:
3370 VISIT(c, expr, e->v.BinOp.left);
3371 VISIT(c, expr, e->v.BinOp.right);
3372 ADDOP(c, binop(c, e->v.BinOp.op));
3373 break;
3374 case UnaryOp_kind:
3375 VISIT(c, expr, e->v.UnaryOp.operand);
3376 ADDOP(c, unaryop(e->v.UnaryOp.op));
3377 break;
3378 case Lambda_kind:
3379 return compiler_lambda(c, e);
3380 case IfExp_kind:
3381 return compiler_ifexp(c, e);
3382 case Dict_kind:
3383 n = asdl_seq_LEN(e->v.Dict.values);
3384 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3385 for (i = 0; i < n; i++) {
3386 VISIT(c, expr,
3387 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3388 VISIT(c, expr,
3389 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3390 ADDOP(c, STORE_MAP);
3391 }
3392 break;
3393 case Set_kind:
3394 n = asdl_seq_LEN(e->v.Set.elts);
3395 VISIT_SEQ(c, expr, e->v.Set.elts);
3396 ADDOP_I(c, BUILD_SET, n);
3397 break;
3398 case GeneratorExp_kind:
3399 return compiler_genexp(c, e);
3400 case ListComp_kind:
3401 return compiler_listcomp(c, e);
3402 case SetComp_kind:
3403 return compiler_setcomp(c, e);
3404 case DictComp_kind:
3405 return compiler_dictcomp(c, e);
3406 case Yield_kind:
3407 if (c->u->u_ste->ste_type != FunctionBlock)
3408 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003409 if (e->v.Yield.value) {
3410 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 }
3412 else {
3413 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3414 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003415 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003417 case YieldFrom_kind:
3418 if (c->u->u_ste->ste_type != FunctionBlock)
3419 return compiler_error(c, "'yield' outside function");
3420 VISIT(c, expr, e->v.YieldFrom.value);
3421 ADDOP(c, GET_ITER);
3422 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3423 ADDOP(c, YIELD_FROM);
3424 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 case Compare_kind:
3426 return compiler_compare(c, e);
3427 case Call_kind:
3428 return compiler_call(c, e);
3429 case Num_kind:
3430 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3431 break;
3432 case Str_kind:
3433 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3434 break;
3435 case Bytes_kind:
3436 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3437 break;
3438 case Ellipsis_kind:
3439 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3440 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003441 case NameConstant_kind:
3442 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3443 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 /* The following exprs can be assignment targets. */
3445 case Attribute_kind:
3446 if (e->v.Attribute.ctx != AugStore)
3447 VISIT(c, expr, e->v.Attribute.value);
3448 switch (e->v.Attribute.ctx) {
3449 case AugLoad:
3450 ADDOP(c, DUP_TOP);
3451 /* Fall through to load */
3452 case Load:
3453 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3454 break;
3455 case AugStore:
3456 ADDOP(c, ROT_TWO);
3457 /* Fall through to save */
3458 case Store:
3459 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3460 break;
3461 case Del:
3462 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3463 break;
3464 case Param:
3465 default:
3466 PyErr_SetString(PyExc_SystemError,
3467 "param invalid in attribute expression");
3468 return 0;
3469 }
3470 break;
3471 case Subscript_kind:
3472 switch (e->v.Subscript.ctx) {
3473 case AugLoad:
3474 VISIT(c, expr, e->v.Subscript.value);
3475 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3476 break;
3477 case Load:
3478 VISIT(c, expr, e->v.Subscript.value);
3479 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3480 break;
3481 case AugStore:
3482 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3483 break;
3484 case Store:
3485 VISIT(c, expr, e->v.Subscript.value);
3486 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3487 break;
3488 case Del:
3489 VISIT(c, expr, e->v.Subscript.value);
3490 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3491 break;
3492 case Param:
3493 default:
3494 PyErr_SetString(PyExc_SystemError,
3495 "param invalid in subscript expression");
3496 return 0;
3497 }
3498 break;
3499 case Starred_kind:
3500 switch (e->v.Starred.ctx) {
3501 case Store:
3502 /* In all legitimate cases, the Starred node was already replaced
3503 * by compiler_list/compiler_tuple. XXX: is that okay? */
3504 return compiler_error(c,
3505 "starred assignment target must be in a list or tuple");
3506 default:
3507 return compiler_error(c,
3508 "can use starred expression only as assignment target");
3509 }
3510 break;
3511 case Name_kind:
3512 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3513 /* child nodes of List and Tuple will have expr_context set */
3514 case List_kind:
3515 return compiler_list(c, e);
3516 case Tuple_kind:
3517 return compiler_tuple(c, e);
3518 }
3519 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520}
3521
3522static int
3523compiler_augassign(struct compiler *c, stmt_ty s)
3524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 expr_ty e = s->v.AugAssign.target;
3526 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 switch (e->kind) {
3531 case Attribute_kind:
3532 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3533 AugLoad, e->lineno, e->col_offset, c->c_arena);
3534 if (auge == NULL)
3535 return 0;
3536 VISIT(c, expr, auge);
3537 VISIT(c, expr, s->v.AugAssign.value);
3538 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3539 auge->v.Attribute.ctx = AugStore;
3540 VISIT(c, expr, auge);
3541 break;
3542 case Subscript_kind:
3543 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3544 AugLoad, e->lineno, e->col_offset, c->c_arena);
3545 if (auge == NULL)
3546 return 0;
3547 VISIT(c, expr, auge);
3548 VISIT(c, expr, s->v.AugAssign.value);
3549 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3550 auge->v.Subscript.ctx = AugStore;
3551 VISIT(c, expr, auge);
3552 break;
3553 case Name_kind:
3554 if (!compiler_nameop(c, e->v.Name.id, Load))
3555 return 0;
3556 VISIT(c, expr, s->v.AugAssign.value);
3557 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3558 return compiler_nameop(c, e->v.Name.id, Store);
3559 default:
3560 PyErr_Format(PyExc_SystemError,
3561 "invalid node type (%d) for augmented assignment",
3562 e->kind);
3563 return 0;
3564 }
3565 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566}
3567
3568static int
3569compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 struct fblockinfo *f;
3572 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3573 PyErr_SetString(PyExc_SystemError,
3574 "too many statically nested blocks");
3575 return 0;
3576 }
3577 f = &c->u->u_fblock[c->u->u_nfblocks++];
3578 f->fb_type = t;
3579 f->fb_block = b;
3580 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581}
3582
3583static void
3584compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 struct compiler_unit *u = c->u;
3587 assert(u->u_nfblocks > 0);
3588 u->u_nfblocks--;
3589 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3590 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591}
3592
Thomas Wouters89f507f2006-12-13 04:49:30 +00003593static int
3594compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 int i;
3596 struct compiler_unit *u = c->u;
3597 for (i = 0; i < u->u_nfblocks; ++i) {
3598 if (u->u_fblock[i].fb_type == LOOP)
3599 return 1;
3600 }
3601 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003602}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603/* Raises a SyntaxError and returns 0.
3604 If something goes wrong, a different exception may be raised.
3605*/
3606
3607static int
3608compiler_error(struct compiler *c, const char *errstr)
3609{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003610 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612
Victor Stinner14e461d2013-08-26 22:28:21 +02003613 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (!loc) {
3615 Py_INCREF(Py_None);
3616 loc = Py_None;
3617 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003618 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003619 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 if (!u)
3621 goto exit;
3622 v = Py_BuildValue("(zO)", errstr, u);
3623 if (!v)
3624 goto exit;
3625 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 Py_DECREF(loc);
3628 Py_XDECREF(u);
3629 Py_XDECREF(v);
3630 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631}
3632
3633static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634compiler_handle_subscr(struct compiler *c, const char *kind,
3635 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 /* XXX this code is duplicated */
3640 switch (ctx) {
3641 case AugLoad: /* fall through to Load */
3642 case Load: op = BINARY_SUBSCR; break;
3643 case AugStore:/* fall through to Store */
3644 case Store: op = STORE_SUBSCR; break;
3645 case Del: op = DELETE_SUBSCR; break;
3646 case Param:
3647 PyErr_Format(PyExc_SystemError,
3648 "invalid %s kind %d in subscript\n",
3649 kind, ctx);
3650 return 0;
3651 }
3652 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003653 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 }
3655 else if (ctx == AugStore) {
3656 ADDOP(c, ROT_THREE);
3657 }
3658 ADDOP(c, op);
3659 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660}
3661
3662static int
3663compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 int n = 2;
3666 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 /* only handles the cases where BUILD_SLICE is emitted */
3669 if (s->v.Slice.lower) {
3670 VISIT(c, expr, s->v.Slice.lower);
3671 }
3672 else {
3673 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3674 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 if (s->v.Slice.upper) {
3677 VISIT(c, expr, s->v.Slice.upper);
3678 }
3679 else {
3680 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3681 }
3682
3683 if (s->v.Slice.step) {
3684 n++;
3685 VISIT(c, expr, s->v.Slice.step);
3686 }
3687 ADDOP_I(c, BUILD_SLICE, n);
3688 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689}
3690
3691static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3693 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 switch (s->kind) {
3696 case Slice_kind:
3697 return compiler_slice(c, s, ctx);
3698 case Index_kind:
3699 VISIT(c, expr, s->v.Index.value);
3700 break;
3701 case ExtSlice_kind:
3702 default:
3703 PyErr_SetString(PyExc_SystemError,
3704 "extended slice invalid in nested slice");
3705 return 0;
3706 }
3707 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708}
3709
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710static int
3711compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 char * kindname = NULL;
3714 switch (s->kind) {
3715 case Index_kind:
3716 kindname = "index";
3717 if (ctx != AugStore) {
3718 VISIT(c, expr, s->v.Index.value);
3719 }
3720 break;
3721 case Slice_kind:
3722 kindname = "slice";
3723 if (ctx != AugStore) {
3724 if (!compiler_slice(c, s, ctx))
3725 return 0;
3726 }
3727 break;
3728 case ExtSlice_kind:
3729 kindname = "extended slice";
3730 if (ctx != AugStore) {
3731 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3732 for (i = 0; i < n; i++) {
3733 slice_ty sub = (slice_ty)asdl_seq_GET(
3734 s->v.ExtSlice.dims, i);
3735 if (!compiler_visit_nested_slice(c, sub, ctx))
3736 return 0;
3737 }
3738 ADDOP_I(c, BUILD_TUPLE, n);
3739 }
3740 break;
3741 default:
3742 PyErr_Format(PyExc_SystemError,
3743 "invalid subscript kind %d", s->kind);
3744 return 0;
3745 }
3746 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747}
3748
Thomas Wouters89f507f2006-12-13 04:49:30 +00003749/* End of the compiler section, beginning of the assembler section */
3750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751/* do depth-first search of basic block graph, starting with block.
3752 post records the block indices in post-order.
3753
3754 XXX must handle implicit jumps from one block to next
3755*/
3756
Thomas Wouters89f507f2006-12-13 04:49:30 +00003757struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 PyObject *a_bytecode; /* string containing bytecode */
3759 int a_offset; /* offset into bytecode */
3760 int a_nblocks; /* number of reachable blocks */
3761 basicblock **a_postorder; /* list of blocks in dfs postorder */
3762 PyObject *a_lnotab; /* string containing lnotab */
3763 int a_lnotab_off; /* offset into lnotab */
3764 int a_lineno; /* last lineno of emitted instruction */
3765 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003766};
3767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768static void
3769dfs(struct compiler *c, basicblock *b, struct assembler *a)
3770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 int i;
3772 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 if (b->b_seen)
3775 return;
3776 b->b_seen = 1;
3777 if (b->b_next != NULL)
3778 dfs(c, b->b_next, a);
3779 for (i = 0; i < b->b_iused; i++) {
3780 instr = &b->b_instr[i];
3781 if (instr->i_jrel || instr->i_jabs)
3782 dfs(c, instr->i_target, a);
3783 }
3784 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785}
3786
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003787static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 int i, target_depth;
3791 struct instr *instr;
3792 if (b->b_seen || b->b_startdepth >= depth)
3793 return maxdepth;
3794 b->b_seen = 1;
3795 b->b_startdepth = depth;
3796 for (i = 0; i < b->b_iused; i++) {
3797 instr = &b->b_instr[i];
3798 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3799 if (depth > maxdepth)
3800 maxdepth = depth;
3801 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3802 if (instr->i_jrel || instr->i_jabs) {
3803 target_depth = depth;
3804 if (instr->i_opcode == FOR_ITER) {
3805 target_depth = depth-2;
3806 } else if (instr->i_opcode == SETUP_FINALLY ||
3807 instr->i_opcode == SETUP_EXCEPT) {
3808 target_depth = depth+3;
3809 if (target_depth > maxdepth)
3810 maxdepth = target_depth;
3811 }
3812 maxdepth = stackdepth_walk(c, instr->i_target,
3813 target_depth, maxdepth);
3814 if (instr->i_opcode == JUMP_ABSOLUTE ||
3815 instr->i_opcode == JUMP_FORWARD) {
3816 goto out; /* remaining code is dead */
3817 }
3818 }
3819 }
3820 if (b->b_next)
3821 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 b->b_seen = 0;
3824 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825}
3826
3827/* Find the flow path that needs the largest stack. We assume that
3828 * cycles in the flow graph have no net effect on the stack depth.
3829 */
3830static int
3831stackdepth(struct compiler *c)
3832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 basicblock *b, *entryblock;
3834 entryblock = NULL;
3835 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3836 b->b_seen = 0;
3837 b->b_startdepth = INT_MIN;
3838 entryblock = b;
3839 }
3840 if (!entryblock)
3841 return 0;
3842 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843}
3844
3845static int
3846assemble_init(struct assembler *a, int nblocks, int firstlineno)
3847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 memset(a, 0, sizeof(struct assembler));
3849 a->a_lineno = firstlineno;
3850 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3851 if (!a->a_bytecode)
3852 return 0;
3853 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3854 if (!a->a_lnotab)
3855 return 0;
3856 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3857 PyErr_NoMemory();
3858 return 0;
3859 }
3860 a->a_postorder = (basicblock **)PyObject_Malloc(
3861 sizeof(basicblock *) * nblocks);
3862 if (!a->a_postorder) {
3863 PyErr_NoMemory();
3864 return 0;
3865 }
3866 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867}
3868
3869static void
3870assemble_free(struct assembler *a)
3871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 Py_XDECREF(a->a_bytecode);
3873 Py_XDECREF(a->a_lnotab);
3874 if (a->a_postorder)
3875 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876}
3877
3878/* Return the size of a basic block in bytes. */
3879
3880static int
3881instrsize(struct instr *instr)
3882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 if (!instr->i_hasarg)
3884 return 1; /* 1 byte for the opcode*/
3885 if (instr->i_oparg > 0xffff)
3886 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3887 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888}
3889
3890static int
3891blocksize(basicblock *b)
3892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 int i;
3894 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 for (i = 0; i < b->b_iused; i++)
3897 size += instrsize(&b->b_instr[i]);
3898 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899}
3900
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003901/* Appends a pair to the end of the line number table, a_lnotab, representing
3902 the instruction's bytecode offset and line number. See
3903 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003904
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003905static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 int d_bytecode, d_lineno;
3909 int len;
3910 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 d_bytecode = a->a_offset - a->a_lineno_off;
3913 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 assert(d_bytecode >= 0);
3916 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 if(d_bytecode == 0 && d_lineno == 0)
3919 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 if (d_bytecode > 255) {
3922 int j, nbytes, ncodes = d_bytecode / 255;
3923 nbytes = a->a_lnotab_off + 2 * ncodes;
3924 len = PyBytes_GET_SIZE(a->a_lnotab);
3925 if (nbytes >= len) {
3926 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3927 len = nbytes;
3928 else if (len <= INT_MAX / 2)
3929 len *= 2;
3930 else {
3931 PyErr_NoMemory();
3932 return 0;
3933 }
3934 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3935 return 0;
3936 }
3937 lnotab = (unsigned char *)
3938 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3939 for (j = 0; j < ncodes; j++) {
3940 *lnotab++ = 255;
3941 *lnotab++ = 0;
3942 }
3943 d_bytecode -= ncodes * 255;
3944 a->a_lnotab_off += ncodes * 2;
3945 }
3946 assert(d_bytecode <= 255);
3947 if (d_lineno > 255) {
3948 int j, nbytes, ncodes = d_lineno / 255;
3949 nbytes = a->a_lnotab_off + 2 * ncodes;
3950 len = PyBytes_GET_SIZE(a->a_lnotab);
3951 if (nbytes >= len) {
3952 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3953 len = nbytes;
3954 else if (len <= INT_MAX / 2)
3955 len *= 2;
3956 else {
3957 PyErr_NoMemory();
3958 return 0;
3959 }
3960 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3961 return 0;
3962 }
3963 lnotab = (unsigned char *)
3964 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3965 *lnotab++ = d_bytecode;
3966 *lnotab++ = 255;
3967 d_bytecode = 0;
3968 for (j = 1; j < ncodes; j++) {
3969 *lnotab++ = 0;
3970 *lnotab++ = 255;
3971 }
3972 d_lineno -= ncodes * 255;
3973 a->a_lnotab_off += ncodes * 2;
3974 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 len = PyBytes_GET_SIZE(a->a_lnotab);
3977 if (a->a_lnotab_off + 2 >= len) {
3978 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
3979 return 0;
3980 }
3981 lnotab = (unsigned char *)
3982 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 a->a_lnotab_off += 2;
3985 if (d_bytecode) {
3986 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003987 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 }
3989 else { /* First line of a block; def stmt, etc. */
3990 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02003991 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 }
3993 a->a_lineno = i->i_lineno;
3994 a->a_lineno_off = a->a_offset;
3995 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003996}
3997
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003998/* assemble_emit()
3999 Extend the bytecode with a new instruction.
4000 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004001*/
4002
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004003static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004004assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 int size, arg = 0, ext = 0;
4007 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4008 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 size = instrsize(i);
4011 if (i->i_hasarg) {
4012 arg = i->i_oparg;
4013 ext = arg >> 16;
4014 }
4015 if (i->i_lineno && !assemble_lnotab(a, i))
4016 return 0;
4017 if (a->a_offset + size >= len) {
4018 if (len > PY_SSIZE_T_MAX / 2)
4019 return 0;
4020 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4021 return 0;
4022 }
4023 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4024 a->a_offset += size;
4025 if (size == 6) {
4026 assert(i->i_hasarg);
4027 *code++ = (char)EXTENDED_ARG;
4028 *code++ = ext & 0xff;
4029 *code++ = ext >> 8;
4030 arg &= 0xffff;
4031 }
4032 *code++ = i->i_opcode;
4033 if (i->i_hasarg) {
4034 assert(size == 3 || size == 6);
4035 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004036 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 }
4038 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004039}
4040
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004041static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004042assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 basicblock *b;
4045 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4046 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 /* Compute the size of each block and fixup jump args.
4049 Replace block pointer with position in bytecode. */
4050 do {
4051 totsize = 0;
4052 for (i = a->a_nblocks - 1; i >= 0; i--) {
4053 b = a->a_postorder[i];
4054 bsize = blocksize(b);
4055 b->b_offset = totsize;
4056 totsize += bsize;
4057 }
4058 last_extended_arg_count = extended_arg_count;
4059 extended_arg_count = 0;
4060 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4061 bsize = b->b_offset;
4062 for (i = 0; i < b->b_iused; i++) {
4063 struct instr *instr = &b->b_instr[i];
4064 /* Relative jumps are computed relative to
4065 the instruction pointer after fetching
4066 the jump instruction.
4067 */
4068 bsize += instrsize(instr);
4069 if (instr->i_jabs)
4070 instr->i_oparg = instr->i_target->b_offset;
4071 else if (instr->i_jrel) {
4072 int delta = instr->i_target->b_offset - bsize;
4073 instr->i_oparg = delta;
4074 }
4075 else
4076 continue;
4077 if (instr->i_oparg > 0xffff)
4078 extended_arg_count++;
4079 }
4080 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 /* XXX: This is an awful hack that could hurt performance, but
4083 on the bright side it should work until we come up
4084 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 The issue is that in the first loop blocksize() is called
4087 which calls instrsize() which requires i_oparg be set
4088 appropriately. There is a bootstrap problem because
4089 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 So we loop until we stop seeing new EXTENDED_ARGs.
4092 The only EXTENDED_ARGs that could be popping up are
4093 ones in jump instructions. So this should converge
4094 fairly quickly.
4095 */
4096 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004097}
4098
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004099static PyObject *
4100dict_keys_inorder(PyObject *dict, int offset)
4101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 PyObject *tuple, *k, *v;
4103 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 tuple = PyTuple_New(size);
4106 if (tuple == NULL)
4107 return NULL;
4108 while (PyDict_Next(dict, &pos, &k, &v)) {
4109 i = PyLong_AS_LONG(v);
4110 /* The keys of the dictionary are tuples. (see compiler_add_o)
4111 The object we want is always first, though. */
4112 k = PyTuple_GET_ITEM(k, 0);
4113 Py_INCREF(k);
4114 assert((i - offset) < size);
4115 assert((i - offset) >= 0);
4116 PyTuple_SET_ITEM(tuple, i - offset, k);
4117 }
4118 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004119}
4120
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004121static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 PySTEntryObject *ste = c->u->u_ste;
4125 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004127 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 if (!ste->ste_unoptimized)
4129 flags |= CO_OPTIMIZED;
4130 if (ste->ste_nested)
4131 flags |= CO_NESTED;
4132 if (ste->ste_generator)
4133 flags |= CO_GENERATOR;
4134 if (ste->ste_varargs)
4135 flags |= CO_VARARGS;
4136 if (ste->ste_varkeywords)
4137 flags |= CO_VARKEYWORDS;
4138 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 /* (Only) inherit compilerflags in PyCF_MASK */
4141 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 n = PyDict_Size(c->u->u_freevars);
4144 if (n < 0)
4145 return -1;
4146 if (n == 0) {
4147 n = PyDict_Size(c->u->u_cellvars);
4148 if (n < 0)
4149 return -1;
4150 if (n == 0) {
4151 flags |= CO_NOFREE;
4152 }
4153 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004156}
4157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158static PyCodeObject *
4159makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 PyObject *tmp;
4162 PyCodeObject *co = NULL;
4163 PyObject *consts = NULL;
4164 PyObject *names = NULL;
4165 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 PyObject *name = NULL;
4167 PyObject *freevars = NULL;
4168 PyObject *cellvars = NULL;
4169 PyObject *bytecode = NULL;
4170 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 tmp = dict_keys_inorder(c->u->u_consts, 0);
4173 if (!tmp)
4174 goto error;
4175 consts = PySequence_List(tmp); /* optimize_code requires a list */
4176 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 names = dict_keys_inorder(c->u->u_names, 0);
4179 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4180 if (!consts || !names || !varnames)
4181 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4184 if (!cellvars)
4185 goto error;
4186 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4187 if (!freevars)
4188 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 nlocals = PyDict_Size(c->u->u_varnames);
4190 flags = compute_code_flags(c);
4191 if (flags < 0)
4192 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4195 if (!bytecode)
4196 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4199 if (!tmp)
4200 goto error;
4201 Py_DECREF(consts);
4202 consts = tmp;
4203
4204 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4205 nlocals, stackdepth(c), flags,
4206 bytecode, consts, names, varnames,
4207 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004208 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 c->u->u_firstlineno,
4210 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 Py_XDECREF(consts);
4213 Py_XDECREF(names);
4214 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004215 Py_XDECREF(name);
4216 Py_XDECREF(freevars);
4217 Py_XDECREF(cellvars);
4218 Py_XDECREF(bytecode);
4219 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004220}
4221
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004222
4223/* For debugging purposes only */
4224#if 0
4225static void
4226dump_instr(const struct instr *i)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 const char *jrel = i->i_jrel ? "jrel " : "";
4229 const char *jabs = i->i_jabs ? "jabs " : "";
4230 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 *arg = '\0';
4233 if (i->i_hasarg)
4234 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4237 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004238}
4239
4240static void
4241dump_basicblock(const basicblock *b)
4242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 const char *seen = b->b_seen ? "seen " : "";
4244 const char *b_return = b->b_return ? "return " : "";
4245 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4246 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4247 if (b->b_instr) {
4248 int i;
4249 for (i = 0; i < b->b_iused; i++) {
4250 fprintf(stderr, " [%02d] ", i);
4251 dump_instr(b->b_instr + i);
4252 }
4253 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004254}
4255#endif
4256
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257static PyCodeObject *
4258assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 basicblock *b, *entryblock;
4261 struct assembler a;
4262 int i, j, nblocks;
4263 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 /* Make sure every block that falls off the end returns None.
4266 XXX NEXT_BLOCK() isn't quite right, because if the last
4267 block ends with a jump or return b_next shouldn't set.
4268 */
4269 if (!c->u->u_curblock->b_return) {
4270 NEXT_BLOCK(c);
4271 if (addNone)
4272 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4273 ADDOP(c, RETURN_VALUE);
4274 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 nblocks = 0;
4277 entryblock = NULL;
4278 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4279 nblocks++;
4280 entryblock = b;
4281 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 /* Set firstlineno if it wasn't explicitly set. */
4284 if (!c->u->u_firstlineno) {
4285 if (entryblock && entryblock->b_instr)
4286 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4287 else
4288 c->u->u_firstlineno = 1;
4289 }
4290 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4291 goto error;
4292 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 /* Can't modify the bytecode after computing jump offsets. */
4295 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 /* Emit code in reverse postorder from dfs. */
4298 for (i = a.a_nblocks - 1; i >= 0; i--) {
4299 b = a.a_postorder[i];
4300 for (j = 0; j < b->b_iused; j++)
4301 if (!assemble_emit(&a, &b->b_instr[j]))
4302 goto error;
4303 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4306 goto error;
4307 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4308 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004312 assemble_free(&a);
4313 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004314}
Georg Brandl8334fd92010-12-04 10:26:46 +00004315
4316#undef PyAST_Compile
4317PyAPI_FUNC(PyCodeObject *)
4318PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4319 PyArena *arena)
4320{
4321 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4322}
4323
4324