blob: 8b00211c9fd07346438395418d4660d69a7e9a20 [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,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040097 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +010098 COMPILER_SCOPE_COMPREHENSION,
99};
100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000101/* The following items change on entry and exit of code blocks.
102 They must be saved and restored when returning to a block.
103*/
104struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400108 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100109 int u_scope_type;
110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 /* The following fields are dicts that map objects to
112 the index of them in co_XXX. The index is used as
113 the argument for opcodes that refer to those collections.
114 */
115 PyObject *u_consts; /* all constants */
116 PyObject *u_names; /* all names */
117 PyObject *u_varnames; /* local variables */
118 PyObject *u_cellvars; /* cell variables */
119 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 int u_argcount; /* number of arguments for block */
124 int u_kwonlyargcount; /* number of keyword only arguments for block */
125 /* Pointer to the most recently allocated block. By following b_list
126 members, you can reach all early allocated blocks. */
127 basicblock *u_blocks;
128 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 int u_nfblocks;
131 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int u_firstlineno; /* the first lineno of the block */
134 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000135 int u_col_offset; /* the offset of the current stmt */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int u_lineno_set; /* boolean to indicate whether instr
137 has been generated with current lineno */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138};
139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000145
146Note that we don't track recursion levels during compilation - the
147task of detecting and rejecting excessive levels of nesting is
148handled by the symbol analysis pass.
149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150*/
151
152struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200153 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 struct symtable *c_st;
155 PyFutureFeatures *c_future; /* pointer to module's __future__ */
156 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157
Georg Brandl8334fd92010-12-04 10:26:46 +0000158 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int c_interactive; /* true if in interactive mode */
160 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 struct compiler_unit *u; /* compiler state for current block */
163 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
164 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000165};
166
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100167static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168static void compiler_free(struct compiler *);
169static basicblock *compiler_new_block(struct compiler *);
170static int compiler_next_instr(struct compiler *, basicblock *);
171static int compiler_addop(struct compiler *, int);
172static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
173static int compiler_addop_i(struct compiler *, int, int);
174static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175static basicblock *compiler_use_new_block(struct compiler *);
176static int compiler_error(struct compiler *, const char *);
177static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
178
179static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
180static int compiler_visit_stmt(struct compiler *, stmt_ty);
181static int compiler_visit_keyword(struct compiler *, keyword_ty);
182static int compiler_visit_expr(struct compiler *, expr_ty);
183static int compiler_augassign(struct compiler *, stmt_ty);
184static int compiler_visit_slice(struct compiler *, slice_ty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 expr_context_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186
187static int compiler_push_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189static void compiler_pop_fblock(struct compiler *, enum fblocktype,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191/* Returns true if there is a loop on the fblock stack. */
192static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
194static int inplace_binop(struct compiler *, operator_ty);
Georg Brandl8334fd92010-12-04 10:26:46 +0000195static int expr_constant(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500197static int compiler_with(struct compiler *, stmt_ty, int);
Guido van Rossum52cc1d82007-03-18 15:41:51 +0000198static int compiler_call_helper(struct compiler *c, int n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 asdl_seq *args,
200 asdl_seq *keywords,
201 expr_ty starargs,
202 expr_ty kwargs);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500203static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400204static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000205
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206static PyCodeObject *assemble(struct compiler *, int addNone);
207static PyObject *__doc__;
208
Benjamin Petersonb173f782009-05-05 22:31:58 +0000209#define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit"
210
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 /* Name mangling: __private becomes _classname__private.
215 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200216 PyObject *result;
217 size_t nlen, plen, ipriv;
218 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200220 PyUnicode_READ_CHAR(ident, 0) != '_' ||
221 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_INCREF(ident);
223 return ident;
224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200225 nlen = PyUnicode_GET_LENGTH(ident);
226 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 The only time a name with a dot can occur is when
230 we are compiling an import statement that has a
231 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 TODO(jhylton): Decide whether we want to support
234 mangling of the module name, e.g. __M.X.
235 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200236 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
237 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
238 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_INCREF(ident);
240 return ident; /* Don't mangle __whatever__ */
241 }
242 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200243 ipriv = 0;
244 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
245 ipriv++;
246 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_INCREF(ident);
248 return ident; /* Don't mangle if class is just underscores */
249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200250 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000251
Antoine Pitrou55bff892013-04-06 21:21:04 +0200252 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
253 PyErr_SetString(PyExc_OverflowError,
254 "private identifier too large to be mangled");
255 return NULL;
256 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200258 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
259 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
260 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
261
262 result = PyUnicode_New(1 + nlen + plen, maxchar);
263 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
266 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200267 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
268 Py_DECREF(result);
269 return NULL;
270 }
271 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
272 Py_DECREF(result);
273 return NULL;
274 }
Victor Stinner8f825062012-04-27 13:55:39 +0200275 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000277}
278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279static int
280compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 c->c_stack = PyList_New(0);
285 if (!c->c_stack)
286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289}
290
291PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200292PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
293 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 struct compiler c;
296 PyCodeObject *co = NULL;
297 PyCompilerFlags local_flags;
298 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (!__doc__) {
301 __doc__ = PyUnicode_InternFromString("__doc__");
302 if (!__doc__)
303 return NULL;
304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (!compiler_init(&c))
307 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200308 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 c.c_filename = filename;
310 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200311 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (c.c_future == NULL)
313 goto finally;
314 if (!flags) {
315 local_flags.cf_flags = 0;
316 flags = &local_flags;
317 }
318 merged = c.c_future->ff_features | flags->cf_flags;
319 c.c_future->ff_features = merged;
320 flags->cf_flags = merged;
321 c.c_flags = flags;
Georg Brandl8334fd92010-12-04 10:26:46 +0000322 c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324
Victor Stinner14e461d2013-08-26 22:28:21 +0200325 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (c.c_st == NULL) {
327 if (!PyErr_Occurred())
328 PyErr_SetString(PyExc_SystemError, "no symtable");
329 goto finally;
330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333
Thomas Wouters1175c432006-02-27 22:49:54 +0000334 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 compiler_free(&c);
336 assert(co || PyErr_Occurred());
337 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338}
339
340PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200341PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
342 int optimize, PyArena *arena)
343{
344 PyObject *filename;
345 PyCodeObject *co;
346 filename = PyUnicode_DecodeFSDefault(filename_str);
347 if (filename == NULL)
348 return NULL;
349 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
350 Py_DECREF(filename);
351 return co;
352
353}
354
355PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356PyNode_Compile(struct _node *n, const char *filename)
357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyCodeObject *co = NULL;
359 mod_ty mod;
360 PyArena *arena = PyArena_New();
361 if (!arena)
362 return NULL;
363 mod = PyAST_FromNode(n, NULL, filename, arena);
364 if (mod)
365 co = PyAST_Compile(mod, filename, NULL, arena);
366 PyArena_Free(arena);
367 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000368}
369
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000370static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (c->c_st)
374 PySymtable_Free(c->c_st);
375 if (c->c_future)
376 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200377 Py_XDECREF(c->c_filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000379}
380
Guido van Rossum79f25d91997-04-29 20:08:16 +0000381static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_ssize_t i, n;
385 PyObject *v, *k;
386 PyObject *dict = PyDict_New();
387 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 n = PyList_Size(list);
390 for (i = 0; i < n; i++) {
391 v = PyLong_FromLong(i);
392 if (!v) {
393 Py_DECREF(dict);
394 return NULL;
395 }
396 k = PyList_GET_ITEM(list, i);
397 k = PyTuple_Pack(2, k, k->ob_type);
398 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
399 Py_XDECREF(k);
400 Py_DECREF(v);
401 Py_DECREF(dict);
402 return NULL;
403 }
404 Py_DECREF(k);
405 Py_DECREF(v);
406 }
407 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408}
409
410/* Return new dict containing names from src that match scope(s).
411
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000412src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000414values are integers, starting at offset and increasing by one for
415each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000416*/
417
418static PyObject *
419dictbytype(PyObject *src, int scope_type, int flag, int offset)
420{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700421 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500423 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 assert(offset >= 0);
426 if (dest == NULL)
427 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000428
Meador Inge2ca63152012-07-18 14:20:11 -0500429 /* Sort the keys so that we have a deterministic order on the indexes
430 saved in the returned dictionary. These indexes are used as indexes
431 into the free and cell var storage. Therefore if they aren't
432 deterministic, then the generated bytecode is not deterministic.
433 */
434 sorted_keys = PyDict_Keys(src);
435 if (sorted_keys == NULL)
436 return NULL;
437 if (PyList_Sort(sorted_keys) != 0) {
438 Py_DECREF(sorted_keys);
439 return NULL;
440 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500441 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500442
443 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 /* XXX this should probably be a macro in symtable.h */
445 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500446 k = PyList_GET_ITEM(sorted_keys, key_i);
447 v = PyDict_GetItem(src, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 assert(PyLong_Check(v));
449 vi = PyLong_AS_LONG(v);
450 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (scope == scope_type || vi & flag) {
453 PyObject *tuple, *item = PyLong_FromLong(i);
454 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500455 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_DECREF(dest);
457 return NULL;
458 }
459 i++;
460 tuple = PyTuple_Pack(2, k, k->ob_type);
461 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500462 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 Py_DECREF(item);
464 Py_DECREF(dest);
465 Py_XDECREF(tuple);
466 return NULL;
467 }
468 Py_DECREF(item);
469 Py_DECREF(tuple);
470 }
471 }
Meador Inge2ca63152012-07-18 14:20:11 -0500472 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000474}
475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476static void
477compiler_unit_check(struct compiler_unit *u)
478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 basicblock *block;
480 for (block = u->u_blocks; block != NULL; block = block->b_list) {
481 assert((void *)block != (void *)0xcbcbcbcb);
482 assert((void *)block != (void *)0xfbfbfbfb);
483 assert((void *)block != (void *)0xdbdbdbdb);
484 if (block->b_instr != NULL) {
485 assert(block->b_ialloc > 0);
486 assert(block->b_iused > 0);
487 assert(block->b_ialloc >= block->b_iused);
488 }
489 else {
490 assert (block->b_iused == 0);
491 assert (block->b_ialloc == 0);
492 }
493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000494}
495
496static void
497compiler_unit_free(struct compiler_unit *u)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 compiler_unit_check(u);
502 b = u->u_blocks;
503 while (b != NULL) {
504 if (b->b_instr)
505 PyObject_Free((void *)b->b_instr);
506 next = b->b_list;
507 PyObject_Free((void *)b);
508 b = next;
509 }
510 Py_CLEAR(u->u_ste);
511 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400512 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_CLEAR(u->u_consts);
514 Py_CLEAR(u->u_names);
515 Py_CLEAR(u->u_varnames);
516 Py_CLEAR(u->u_freevars);
517 Py_CLEAR(u->u_cellvars);
518 Py_CLEAR(u->u_private);
519 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000520}
521
522static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100523compiler_enter_scope(struct compiler *c, identifier name,
524 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
529 struct compiler_unit));
530 if (!u) {
531 PyErr_NoMemory();
532 return 0;
533 }
534 memset(u, 0, sizeof(struct compiler_unit));
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100535 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 u->u_argcount = 0;
537 u->u_kwonlyargcount = 0;
538 u->u_ste = PySymtable_Lookup(c->c_st, key);
539 if (!u->u_ste) {
540 compiler_unit_free(u);
541 return 0;
542 }
543 Py_INCREF(name);
544 u->u_name = name;
545 u->u_varnames = list2dict(u->u_ste->ste_varnames);
546 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
547 if (!u->u_varnames || !u->u_cellvars) {
548 compiler_unit_free(u);
549 return 0;
550 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500551 if (u->u_ste->ste_needs_class_closure) {
552 /* Cook up a implicit __class__ cell. */
553 _Py_IDENTIFIER(__class__);
554 PyObject *tuple, *name, *zero;
555 int res;
556 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
557 assert(PyDict_Size(u->u_cellvars) == 0);
558 name = _PyUnicode_FromId(&PyId___class__);
559 if (!name) {
560 compiler_unit_free(u);
561 return 0;
562 }
563 tuple = PyTuple_Pack(2, name, Py_TYPE(name));
564 if (!tuple) {
565 compiler_unit_free(u);
566 return 0;
567 }
568 zero = PyLong_FromLong(0);
569 if (!zero) {
570 Py_DECREF(tuple);
571 compiler_unit_free(u);
572 return 0;
573 }
574 res = PyDict_SetItem(u->u_cellvars, tuple, zero);
575 Py_DECREF(tuple);
576 Py_DECREF(zero);
577 if (res < 0) {
578 compiler_unit_free(u);
579 return 0;
580 }
581 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
584 PyDict_Size(u->u_cellvars));
585 if (!u->u_freevars) {
586 compiler_unit_free(u);
587 return 0;
588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 u->u_blocks = NULL;
591 u->u_nfblocks = 0;
592 u->u_firstlineno = lineno;
593 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000594 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 u->u_lineno_set = 0;
596 u->u_consts = PyDict_New();
597 if (!u->u_consts) {
598 compiler_unit_free(u);
599 return 0;
600 }
601 u->u_names = PyDict_New();
602 if (!u->u_names) {
603 compiler_unit_free(u);
604 return 0;
605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Push the old compiler_unit on the stack. */
610 if (c->u) {
611 PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
612 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
613 Py_XDECREF(capsule);
614 compiler_unit_free(u);
615 return 0;
616 }
617 Py_DECREF(capsule);
618 u->u_private = c->u->u_private;
619 Py_XINCREF(u->u_private);
620 }
621 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 c->c_nestlevel++;
624 if (compiler_use_new_block(c) == NULL)
625 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400627 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
628 if (!compiler_set_qualname(c))
629 return 0;
630 }
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633}
634
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000635static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636compiler_exit_scope(struct compiler *c)
637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 int n;
639 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 c->c_nestlevel--;
642 compiler_unit_free(c->u);
643 /* Restore c->u to the parent unit. */
644 n = PyList_GET_SIZE(c->c_stack) - 1;
645 if (n >= 0) {
646 capsule = PyList_GET_ITEM(c->c_stack, n);
647 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
648 assert(c->u);
649 /* we are deleting from a list so this really shouldn't fail */
650 if (PySequence_DelItem(c->c_stack, n) < 0)
651 Py_FatalError("compiler_exit_scope()");
652 compiler_unit_check(c->u);
653 }
654 else
655 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400659static int
660compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100661{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100662 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400663 _Py_static_string(dot_locals, ".<locals>");
664 Py_ssize_t stack_size;
665 struct compiler_unit *u = c->u;
666 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100667
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400668 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100669 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400670 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400671 if (stack_size > 1) {
672 int scope, force_global = 0;
673 struct compiler_unit *parent;
674 PyObject *mangled, *capsule;
675
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400676 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400677 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
678 assert(parent);
679
680 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) {
681 assert(u->u_name);
682 mangled = _Py_Mangle(parent->u_private, u->u_name);
683 if (!mangled)
684 return 0;
685 scope = PyST_GetScope(parent->u_ste, mangled);
686 Py_DECREF(mangled);
687 assert(scope != GLOBAL_IMPLICIT);
688 if (scope == GLOBAL_EXPLICIT)
689 force_global = 1;
690 }
691
692 if (!force_global) {
693 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
694 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
695 dot_locals_str = _PyUnicode_FromId(&dot_locals);
696 if (dot_locals_str == NULL)
697 return 0;
698 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
699 if (base == NULL)
700 return 0;
701 }
702 else {
703 Py_INCREF(parent->u_qualname);
704 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400705 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 }
707 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 if (base != NULL) {
710 dot_str = _PyUnicode_FromId(&dot);
711 if (dot_str == NULL) {
712 Py_DECREF(base);
713 return 0;
714 }
715 name = PyUnicode_Concat(base, dot_str);
716 Py_DECREF(base);
717 if (name == NULL)
718 return 0;
719 PyUnicode_Append(&name, u->u_name);
720 if (name == NULL)
721 return 0;
722 }
723 else {
724 Py_INCREF(u->u_name);
725 name = u->u_name;
726 }
727 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100728
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100730}
731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732/* Allocate a new block and return a pointer to it.
733 Returns NULL on error.
734*/
735
736static basicblock *
737compiler_new_block(struct compiler *c)
738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 basicblock *b;
740 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 u = c->u;
743 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
744 if (b == NULL) {
745 PyErr_NoMemory();
746 return NULL;
747 }
748 memset((void *)b, 0, sizeof(basicblock));
749 /* Extend the singly linked list of blocks with new block. */
750 b->b_list = u->u_blocks;
751 u->u_blocks = b;
752 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753}
754
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000755static basicblock *
756compiler_use_new_block(struct compiler *c)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 basicblock *block = compiler_new_block(c);
759 if (block == NULL)
760 return NULL;
761 c->u->u_curblock = block;
762 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000763}
764
765static basicblock *
766compiler_next_block(struct compiler *c)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 basicblock *block = compiler_new_block(c);
769 if (block == NULL)
770 return NULL;
771 c->u->u_curblock->b_next = block;
772 c->u->u_curblock = block;
773 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774}
775
776static basicblock *
777compiler_use_next_block(struct compiler *c, basicblock *block)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 assert(block != NULL);
780 c->u->u_curblock->b_next = block;
781 c->u->u_curblock = block;
782 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783}
784
785/* Returns the offset of the next instruction in the current block's
786 b_instr array. Resizes the b_instr as necessary.
787 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000788*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789
790static int
791compiler_next_instr(struct compiler *c, basicblock *b)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(b != NULL);
794 if (b->b_instr == NULL) {
795 b->b_instr = (struct instr *)PyObject_Malloc(
796 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
797 if (b->b_instr == NULL) {
798 PyErr_NoMemory();
799 return -1;
800 }
801 b->b_ialloc = DEFAULT_BLOCK_SIZE;
802 memset((char *)b->b_instr, 0,
803 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
804 }
805 else if (b->b_iused == b->b_ialloc) {
806 struct instr *tmp;
807 size_t oldsize, newsize;
808 oldsize = b->b_ialloc * sizeof(struct instr);
809 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (oldsize > (PY_SIZE_MAX >> 1)) {
812 PyErr_NoMemory();
813 return -1;
814 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (newsize == 0) {
817 PyErr_NoMemory();
818 return -1;
819 }
820 b->b_ialloc <<= 1;
821 tmp = (struct instr *)PyObject_Realloc(
822 (void *)b->b_instr, newsize);
823 if (tmp == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 b->b_instr = tmp;
828 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
829 }
830 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831}
832
Christian Heimes2202f872008-02-06 14:31:34 +0000833/* Set the i_lineno member of the instruction at offset off if the
834 line number for the current expression/statement has not
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835 already been set. If it has been set, the call has no effect.
836
Christian Heimes2202f872008-02-06 14:31:34 +0000837 The line number is reset in the following cases:
838 - when entering a new scope
839 - on each statement
840 - on each expression that start a new line
841 - before the "except" clause
842 - before the "for" and "while" expressions
Thomas Wouters89f507f2006-12-13 04:49:30 +0000843*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000845static void
846compiler_set_lineno(struct compiler *c, int off)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 basicblock *b;
849 if (c->u->u_lineno_set)
850 return;
851 c->u->u_lineno_set = 1;
852 b = c->u->u_curblock;
853 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000854}
855
856static int
857opcode_stack_effect(int opcode, int oparg)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 switch (opcode) {
860 case POP_TOP:
861 return -1;
862 case ROT_TWO:
863 case ROT_THREE:
864 return 0;
865 case DUP_TOP:
866 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000867 case DUP_TOP_TWO:
868 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 case UNARY_POSITIVE:
871 case UNARY_NEGATIVE:
872 case UNARY_NOT:
873 case UNARY_INVERT:
874 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 case SET_ADD:
877 case LIST_APPEND:
878 return -1;
879 case MAP_ADD:
880 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 case BINARY_POWER:
883 case BINARY_MULTIPLY:
884 case BINARY_MODULO:
885 case BINARY_ADD:
886 case BINARY_SUBTRACT:
887 case BINARY_SUBSCR:
888 case BINARY_FLOOR_DIVIDE:
889 case BINARY_TRUE_DIVIDE:
890 return -1;
891 case INPLACE_FLOOR_DIVIDE:
892 case INPLACE_TRUE_DIVIDE:
893 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 case INPLACE_ADD:
896 case INPLACE_SUBTRACT:
897 case INPLACE_MULTIPLY:
898 case INPLACE_MODULO:
899 return -1;
900 case STORE_SUBSCR:
901 return -3;
902 case STORE_MAP:
903 return -2;
904 case DELETE_SUBSCR:
905 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 case BINARY_LSHIFT:
908 case BINARY_RSHIFT:
909 case BINARY_AND:
910 case BINARY_XOR:
911 case BINARY_OR:
912 return -1;
913 case INPLACE_POWER:
914 return -1;
915 case GET_ITER:
916 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 case PRINT_EXPR:
919 return -1;
920 case LOAD_BUILD_CLASS:
921 return 1;
922 case INPLACE_LSHIFT:
923 case INPLACE_RSHIFT:
924 case INPLACE_AND:
925 case INPLACE_XOR:
926 case INPLACE_OR:
927 return -1;
928 case BREAK_LOOP:
929 return 0;
930 case SETUP_WITH:
931 return 7;
932 case WITH_CLEANUP:
933 return -1; /* XXX Sometimes more */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case RETURN_VALUE:
935 return -1;
936 case IMPORT_STAR:
937 return -1;
938 case YIELD_VALUE:
939 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500940 case YIELD_FROM:
941 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case POP_BLOCK:
943 return 0;
944 case POP_EXCEPT:
945 return 0; /* -3 except if bad bytecode */
946 case END_FINALLY:
947 return -1; /* or -2 or -3 if exception occurred */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case STORE_NAME:
950 return -1;
951 case DELETE_NAME:
952 return 0;
953 case UNPACK_SEQUENCE:
954 return oparg-1;
955 case UNPACK_EX:
956 return (oparg&0xFF) + (oparg>>8);
957 case FOR_ITER:
958 return 1; /* or -1, at end of iterator */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case STORE_ATTR:
961 return -2;
962 case DELETE_ATTR:
963 return -1;
964 case STORE_GLOBAL:
965 return -1;
966 case DELETE_GLOBAL:
967 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 case LOAD_CONST:
969 return 1;
970 case LOAD_NAME:
971 return 1;
972 case BUILD_TUPLE:
973 case BUILD_LIST:
974 case BUILD_SET:
975 return 1-oparg;
976 case BUILD_MAP:
977 return 1;
978 case LOAD_ATTR:
979 return 0;
980 case COMPARE_OP:
981 return -1;
982 case IMPORT_NAME:
983 return -1;
984 case IMPORT_FROM:
985 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case JUMP_FORWARD:
988 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
989 case JUMP_IF_FALSE_OR_POP: /* "" */
990 case JUMP_ABSOLUTE:
991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case POP_JUMP_IF_FALSE:
994 case POP_JUMP_IF_TRUE:
995 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case LOAD_GLOBAL:
998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 case CONTINUE_LOOP:
1001 return 0;
1002 case SETUP_LOOP:
1003 return 0;
1004 case SETUP_EXCEPT:
1005 case SETUP_FINALLY:
1006 return 6; /* can push 3 values for the new exception
1007 + 3 others for the previous exception state */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 case LOAD_FAST:
1010 return 1;
1011 case STORE_FAST:
1012 return -1;
1013 case DELETE_FAST:
1014 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 case RAISE_VARARGS:
1017 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +00001018#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case CALL_FUNCTION:
1020 return -NARGS(oparg);
1021 case CALL_FUNCTION_VAR:
1022 case CALL_FUNCTION_KW:
1023 return -NARGS(oparg)-1;
1024 case CALL_FUNCTION_VAR_KW:
1025 return -NARGS(oparg)-2;
1026 case MAKE_FUNCTION:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001027 return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case MAKE_CLOSURE:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001029 return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001030#undef NARGS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 case BUILD_SLICE:
1032 if (oparg == 3)
1033 return -2;
1034 else
1035 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case LOAD_CLOSURE:
1038 return 1;
1039 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001040 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return 1;
1042 case STORE_DEREF:
1043 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001044 case DELETE_DEREF:
1045 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 default:
1047 fprintf(stderr, "opcode = %d\n", opcode);
1048 Py_FatalError("opcode_stack_effect()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 }
1051 return 0; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052}
1053
1054/* Add an opcode with no argument.
1055 Returns 0 on failure, 1 on success.
1056*/
1057
1058static int
1059compiler_addop(struct compiler *c, int opcode)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 basicblock *b;
1062 struct instr *i;
1063 int off;
1064 off = compiler_next_instr(c, c->u->u_curblock);
1065 if (off < 0)
1066 return 0;
1067 b = c->u->u_curblock;
1068 i = &b->b_instr[off];
1069 i->i_opcode = opcode;
1070 i->i_hasarg = 0;
1071 if (opcode == RETURN_VALUE)
1072 b->b_return = 1;
1073 compiler_set_lineno(c, off);
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075}
1076
1077static int
1078compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *t, *v;
1081 Py_ssize_t arg;
1082 double d;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083
Serhiy Storchaka95949422013-08-27 19:40:23 +03001084 /* necessary to make sure types aren't coerced (e.g., float and complex) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1086 if (PyFloat_Check(o)) {
1087 d = PyFloat_AS_DOUBLE(o);
1088 /* all we need is to make the tuple different in either the 0.0
1089 * or -0.0 case from all others, just to avoid the "coercion".
1090 */
1091 if (d == 0.0 && copysign(1.0, d) < 0.0)
1092 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1093 else
1094 t = PyTuple_Pack(2, o, o->ob_type);
1095 }
1096 else if (PyComplex_Check(o)) {
1097 Py_complex z;
1098 int real_negzero, imag_negzero;
1099 /* For the complex case we must make complex(x, 0.)
1100 different from complex(x, -0.) and complex(0., y)
1101 different from complex(-0., y), for any x and y.
1102 All four complex zeros must be distinguished.*/
1103 z = PyComplex_AsCComplex(o);
1104 real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
1105 imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
1106 if (real_negzero && imag_negzero) {
1107 t = PyTuple_Pack(5, o, o->ob_type,
1108 Py_None, Py_None, Py_None);
Christian Heimes400adb02008-02-01 08:12:03 +00001109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 else if (imag_negzero) {
1111 t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
Guido van Rossum04110fb2007-08-24 16:32:05 +00001112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 else if (real_negzero) {
1114 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1115 }
1116 else {
1117 t = PyTuple_Pack(2, o, o->ob_type);
1118 }
1119 }
1120 else {
1121 t = PyTuple_Pack(2, o, o->ob_type);
1122 }
1123 if (t == NULL)
1124 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 v = PyDict_GetItem(dict, t);
1127 if (!v) {
1128 if (PyErr_Occurred())
1129 return -1;
1130 arg = PyDict_Size(dict);
1131 v = PyLong_FromLong(arg);
1132 if (!v) {
1133 Py_DECREF(t);
1134 return -1;
1135 }
1136 if (PyDict_SetItem(dict, t, v) < 0) {
1137 Py_DECREF(t);
1138 Py_DECREF(v);
1139 return -1;
1140 }
1141 Py_DECREF(v);
1142 }
1143 else
1144 arg = PyLong_AsLong(v);
1145 Py_DECREF(t);
1146 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147}
1148
1149static int
1150compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152{
1153 int arg = compiler_add_o(c, dict, o);
1154 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return compiler_addop_i(c, opcode, arg);
1157}
1158
1159static int
1160compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162{
1163 int arg;
1164 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1165 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 arg = compiler_add_o(c, dict, mangled);
1168 Py_DECREF(mangled);
1169 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001170 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171 return compiler_addop_i(c, opcode, arg);
1172}
1173
1174/* Add an opcode with an integer argument.
1175 Returns 0 on failure, 1 on success.
1176*/
1177
1178static int
1179compiler_addop_i(struct compiler *c, int opcode, int oparg)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 struct instr *i;
1182 int off;
1183 off = compiler_next_instr(c, c->u->u_curblock);
1184 if (off < 0)
1185 return 0;
1186 i = &c->u->u_curblock->b_instr[off];
1187 i->i_opcode = opcode;
1188 i->i_oparg = oparg;
1189 i->i_hasarg = 1;
1190 compiler_set_lineno(c, off);
1191 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192}
1193
1194static int
1195compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 struct instr *i;
1198 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 assert(b != NULL);
1201 off = compiler_next_instr(c, c->u->u_curblock);
1202 if (off < 0)
1203 return 0;
1204 i = &c->u->u_curblock->b_instr[off];
1205 i->i_opcode = opcode;
1206 i->i_target = b;
1207 i->i_hasarg = 1;
1208 if (absolute)
1209 i->i_jabs = 1;
1210 else
1211 i->i_jrel = 1;
1212 compiler_set_lineno(c, off);
1213 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214}
1215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1217 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 it as the current block. NEXT_BLOCK() also creates an implicit jump
1219 from the current block to the new block.
1220*/
1221
Thomas Wouters89f507f2006-12-13 04:49:30 +00001222/* The returns inside these macros make it impossible to decref objects
1223 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224*/
1225
1226
1227#define NEW_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (compiler_use_new_block((C)) == NULL) \
1229 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230}
1231
1232#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (compiler_next_block((C)) == NULL) \
1234 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235}
1236
1237#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!compiler_addop((C), (OP))) \
1239 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001240}
1241
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001242#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (!compiler_addop((C), (OP))) { \
1244 compiler_exit_scope(c); \
1245 return 0; \
1246 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001247}
1248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001249#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1251 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1256 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257}
1258
1259#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (!compiler_addop_i((C), (OP), (O))) \
1261 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262}
1263
1264#define ADDOP_JABS(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (!compiler_addop_j((C), (OP), (O), 1)) \
1266 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267}
1268
1269#define ADDOP_JREL(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!compiler_addop_j((C), (OP), (O), 0)) \
1271 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272}
1273
1274/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1275 the ASDL name to synthesize the name of the C type and the visit function.
1276*/
1277
1278#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!compiler_visit_ ## TYPE((C), (V))) \
1280 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281}
1282
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001283#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (!compiler_visit_ ## TYPE((C), (V))) { \
1285 compiler_exit_scope(c); \
1286 return 0; \
1287 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001288}
1289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (!compiler_visit_slice((C), (V), (CTX))) \
1292 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293}
1294
1295#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 int _i; \
1297 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1298 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1299 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1300 if (!compiler_visit_ ## TYPE((C), elt)) \
1301 return 0; \
1302 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303}
1304
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001305#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 int _i; \
1307 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
1308 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1309 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1310 if (!compiler_visit_ ## TYPE((C), elt)) { \
1311 compiler_exit_scope(c); \
1312 return 0; \
1313 } \
1314 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001315}
1316
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001317static int
1318compiler_isdocstring(stmt_ty s)
1319{
1320 if (s->kind != Expr_kind)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 return s->v.Expr.value->kind == Str_kind;
1323}
1324
1325/* Compile a sequence of statements, checking for a docstring. */
1326
1327static int
1328compiler_body(struct compiler *c, asdl_seq *stmts)
1329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 int i = 0;
1331 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (!asdl_seq_LEN(stmts))
1334 return 1;
1335 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandl8334fd92010-12-04 10:26:46 +00001336 if (compiler_isdocstring(st) && c->c_optimize < 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* don't generate docstrings if -OO */
1338 i = 1;
1339 VISIT(c, expr, st->v.Expr.value);
1340 if (!compiler_nameop(c, __doc__, Store))
1341 return 0;
1342 }
1343 for (; i < asdl_seq_LEN(stmts); i++)
1344 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
1345 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346}
1347
1348static PyCodeObject *
1349compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyCodeObject *co;
1352 int addNone = 1;
1353 static PyObject *module;
1354 if (!module) {
1355 module = PyUnicode_InternFromString("<module>");
1356 if (!module)
1357 return NULL;
1358 }
1359 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001360 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return NULL;
1362 switch (mod->kind) {
1363 case Module_kind:
1364 if (!compiler_body(c, mod->v.Module.body)) {
1365 compiler_exit_scope(c);
1366 return 0;
1367 }
1368 break;
1369 case Interactive_kind:
1370 c->c_interactive = 1;
1371 VISIT_SEQ_IN_SCOPE(c, stmt,
1372 mod->v.Interactive.body);
1373 break;
1374 case Expression_kind:
1375 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1376 addNone = 0;
1377 break;
1378 case Suite_kind:
1379 PyErr_SetString(PyExc_SystemError,
1380 "suite should not be possible");
1381 return 0;
1382 default:
1383 PyErr_Format(PyExc_SystemError,
1384 "module kind %d should not be possible",
1385 mod->kind);
1386 return 0;
1387 }
1388 co = assemble(c, addNone);
1389 compiler_exit_scope(c);
1390 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001391}
1392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393/* The test for LOCAL must come before the test for FREE in order to
1394 handle classes where name is both local and free. The local var is
1395 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001396*/
1397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398static int
1399get_ref_type(struct compiler *c, PyObject *name)
1400{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001401 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001402 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
1403 !PyUnicode_CompareWithASCIIString(name, "__class__"))
1404 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001405 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (scope == 0) {
1407 char buf[350];
1408 PyOS_snprintf(buf, sizeof(buf),
Victor Stinner14e461d2013-08-26 22:28:21 +02001409 "unknown scope for %.100s in %.100s(%s)\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 "symbols: %s\nlocals: %s\nglobals: %s",
1411 PyBytes_AS_STRING(name),
1412 PyBytes_AS_STRING(c->u->u_name),
1413 PyObject_REPR(c->u->u_ste->ste_id),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject_REPR(c->u->u_ste->ste_symbols),
1415 PyObject_REPR(c->u->u_varnames),
1416 PyObject_REPR(c->u->u_names)
1417 );
1418 Py_FatalError(buf);
1419 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422}
1423
1424static int
1425compiler_lookup_arg(PyObject *dict, PyObject *name)
1426{
1427 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429 if (k == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001430 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001432 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001434 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001435 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436}
1437
1438static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001439compiler_make_closure(struct compiler *c, PyCodeObject *co, int args, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 int i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001442 if (qualname == NULL)
1443 qualname = co->co_name;
1444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (free == 0) {
1446 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001447 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 ADDOP_I(c, MAKE_FUNCTION, args);
1449 return 1;
1450 }
1451 for (i = 0; i < free; ++i) {
1452 /* Bypass com_addop_varname because it will generate
1453 LOAD_DEREF but LOAD_CLOSURE is needed.
1454 */
1455 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1456 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* Special case: If a class contains a method with a
1459 free variable that has the same name as a method,
1460 the name will be considered free *and* local in the
1461 class. It should be handled by the closure, as
1462 well as by the normal name loookup logic.
1463 */
1464 reftype = get_ref_type(c, name);
1465 if (reftype == CELL)
1466 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1467 else /* (reftype == FREE) */
1468 arg = compiler_lookup_arg(c->u->u_freevars, name);
1469 if (arg == -1) {
1470 fprintf(stderr,
1471 "lookup %s in %s %d %d\n"
1472 "freevars of %s: %s\n",
1473 PyObject_REPR(name),
1474 PyBytes_AS_STRING(c->u->u_name),
1475 reftype, arg,
1476 _PyUnicode_AsString(co->co_name),
1477 PyObject_REPR(co->co_freevars));
1478 Py_FatalError("compiler_make_closure()");
1479 }
1480 ADDOP_I(c, LOAD_CLOSURE, arg);
1481 }
1482 ADDOP_I(c, BUILD_TUPLE, free);
1483 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001484 ADDOP_O(c, LOAD_CONST, qualname, consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 ADDOP_I(c, MAKE_CLOSURE, args);
1486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487}
1488
1489static int
1490compiler_decorators(struct compiler *c, asdl_seq* decos)
1491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (!decos)
1495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1498 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1499 }
1500 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
1503static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001504compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 asdl_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 int i, default_count = 0;
1508 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1509 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1510 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1511 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001512 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
1513 if (!mangled)
1514 return -1;
1515 ADDOP_O(c, LOAD_CONST, mangled, consts);
1516 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (!compiler_visit_expr(c, default_)) {
1518 return -1;
1519 }
1520 default_count++;
1521 }
1522 }
1523 return default_count;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001524}
1525
1526static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001527compiler_visit_argannotation(struct compiler *c, identifier id,
1528 expr_ty annotation, PyObject *names)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (annotation) {
1531 VISIT(c, expr, annotation);
1532 if (PyList_Append(names, id))
1533 return -1;
1534 }
1535 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001536}
1537
1538static int
1539compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1540 PyObject *names)
1541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 int i, error;
1543 for (i = 0; i < asdl_seq_LEN(args); i++) {
1544 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1545 error = compiler_visit_argannotation(
1546 c,
1547 arg->arg,
1548 arg->annotation,
1549 names);
1550 if (error)
1551 return error;
1552 }
1553 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00001554}
1555
1556static int
1557compiler_visit_annotations(struct compiler *c, arguments_ty args,
1558 expr_ty returns)
1559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* Push arg annotations and a list of the argument names. Return the #
1561 of items pushed. The expressions are evaluated out-of-order wrt the
1562 source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1565 */
1566 static identifier return_str;
1567 PyObject *names;
1568 int len;
1569 names = PyList_New(0);
1570 if (!names)
1571 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (compiler_visit_argannotations(c, args->args, names))
1574 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001575 if (args->vararg && args->vararg->annotation &&
1576 compiler_visit_argannotation(c, args->vararg->arg,
1577 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 goto error;
1579 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1580 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07001581 if (args->kwarg && args->kwarg->annotation &&
1582 compiler_visit_argannotation(c, args->kwarg->arg,
1583 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (!return_str) {
1587 return_str = PyUnicode_InternFromString("return");
1588 if (!return_str)
1589 goto error;
1590 }
1591 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1592 goto error;
1593 }
1594
1595 len = PyList_GET_SIZE(names);
1596 if (len > 65534) {
1597 /* len must fit in 16 bits, and len is incremented below */
1598 PyErr_SetString(PyExc_SyntaxError,
1599 "too many annotations");
1600 goto error;
1601 }
1602 if (len) {
1603 /* convert names to a tuple and place on stack */
1604 PyObject *elt;
1605 int i;
1606 PyObject *s = PyTuple_New(len);
1607 if (!s)
1608 goto error;
1609 for (i = 0; i < len; i++) {
1610 elt = PyList_GET_ITEM(names, i);
1611 Py_INCREF(elt);
1612 PyTuple_SET_ITEM(s, i, elt);
1613 }
1614 ADDOP_O(c, LOAD_CONST, s, consts);
1615 Py_DECREF(s);
1616 len++; /* include the just-pushed tuple */
1617 }
1618 Py_DECREF(names);
1619 return len;
Neal Norwitzc1505362006-12-28 06:47:50 +00001620
1621error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 Py_DECREF(names);
1623 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00001624}
1625
1626static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627compiler_function(struct compiler *c, stmt_ty s)
1628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001630 PyObject *qualname, *first_const = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 arguments_ty args = s->v.FunctionDef.args;
1632 expr_ty returns = s->v.FunctionDef.returns;
1633 asdl_seq* decos = s->v.FunctionDef.decorator_list;
1634 stmt_ty st;
1635 int i, n, docstring, kw_default_count = 0, arglength;
1636 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 assert(s->kind == FunctionDef_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (!compiler_decorators(c, decos))
1641 return 0;
Benjamin Peterson1ef876c2013-02-10 09:29:59 -05001642 if (args->defaults)
1643 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 if (args->kwonlyargs) {
1645 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1646 args->kw_defaults);
1647 if (res < 0)
1648 return 0;
1649 kw_default_count = res;
1650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 num_annotations = compiler_visit_annotations(c, args, returns);
1652 if (num_annotations < 0)
1653 return 0;
1654 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001655
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001656 if (!compiler_enter_scope(c, s->v.FunctionDef.name,
1657 COMPILER_SCOPE_FUNCTION, (void *)s,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 s->lineno))
1659 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
1662 docstring = compiler_isdocstring(st);
Georg Brandl8334fd92010-12-04 10:26:46 +00001663 if (docstring && c->c_optimize < 2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 first_const = st->v.Expr.value->v.Str.s;
1665 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
1666 compiler_exit_scope(c);
1667 return 0;
1668 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 c->u->u_argcount = asdl_seq_LEN(args->args);
1671 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1672 n = asdl_seq_LEN(s->v.FunctionDef.body);
1673 /* if there was a docstring, we need to skip the first statement */
1674 for (i = docstring; i < n; i++) {
1675 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1676 VISIT_IN_SCOPE(c, stmt, st);
1677 }
1678 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001679 qualname = c->u->u_qualname;
1680 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001682 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001683 Py_XDECREF(qualname);
1684 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 arglength = asdl_seq_LEN(args->defaults);
1689 arglength |= kw_default_count << 8;
1690 arglength |= num_annotations << 16;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001691 compiler_make_closure(c, co, arglength, qualname);
1692 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* decorators */
1696 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1697 ADDOP_I(c, CALL_FUNCTION, 1);
1698 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 return compiler_nameop(c, s->v.FunctionDef.name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701}
1702
1703static int
1704compiler_class(struct compiler *c, stmt_ty s)
1705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyCodeObject *co;
1707 PyObject *str;
1708 int i;
1709 asdl_seq* decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (!compiler_decorators(c, decos))
1712 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* ultimately generate code for:
1715 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1716 where:
1717 <func> is a function/closure created from the class body;
1718 it has a single argument (__locals__) where the dict
1719 (or MutableSequence) representing the locals is passed
1720 <name> is the class name
1721 <bases> is the positional arguments and *varargs argument
1722 <keywords> is the keyword arguments and **kwds argument
1723 This borrows from compiler_call.
1724 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001727 if (!compiler_enter_scope(c, s->v.ClassDef.name,
1728 COMPILER_SCOPE_CLASS, (void *)s, s->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 return 0;
1730 /* this block represents what we do in the new scope */
1731 {
1732 /* use the class name for name mangling */
1733 Py_INCREF(s->v.ClassDef.name);
1734 Py_XDECREF(c->u->u_private);
1735 c->u->u_private = s->v.ClassDef.name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* load (global) __name__ ... */
1737 str = PyUnicode_InternFromString("__name__");
1738 if (!str || !compiler_nameop(c, str, Load)) {
1739 Py_XDECREF(str);
1740 compiler_exit_scope(c);
1741 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 Py_DECREF(str);
1744 /* ... and store it as __module__ */
1745 str = PyUnicode_InternFromString("__module__");
1746 if (!str || !compiler_nameop(c, str, Store)) {
1747 Py_XDECREF(str);
1748 compiler_exit_scope(c);
1749 return 0;
1750 }
1751 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001752 assert(c->u->u_qualname);
1753 ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001754 str = PyUnicode_InternFromString("__qualname__");
1755 if (!str || !compiler_nameop(c, str, Store)) {
1756 Py_XDECREF(str);
1757 compiler_exit_scope(c);
1758 return 0;
1759 }
1760 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* compile the body proper */
1762 if (!compiler_body(c, s->v.ClassDef.body)) {
1763 compiler_exit_scope(c);
1764 return 0;
1765 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001766 if (c->u->u_ste->ste_needs_class_closure) {
1767 /* return the (empty) __class__ cell */
1768 str = PyUnicode_InternFromString("__class__");
1769 if (str == NULL) {
1770 compiler_exit_scope(c);
1771 return 0;
1772 }
1773 i = compiler_lookup_arg(c->u->u_cellvars, str);
1774 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01001775 if (i < 0) {
1776 compiler_exit_scope(c);
1777 return 0;
1778 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001779 assert(i == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* Return the cell where to store __class__ */
1781 ADDOP_I(c, LOAD_CLOSURE, i);
1782 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05001783 else {
1784 assert(PyDict_Size(c->u->u_cellvars) == 0);
1785 /* This happens when nobody references the cell. Return None. */
1786 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1789 /* create the code object */
1790 co = assemble(c, 1);
1791 }
1792 /* leave the new scope */
1793 compiler_exit_scope(c);
1794 if (co == NULL)
1795 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* 2. load the 'build_class' function */
1798 ADDOP(c, LOAD_BUILD_CLASS);
1799
1800 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001801 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 Py_DECREF(co);
1803
1804 /* 4. load class name */
1805 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1806
1807 /* 5. generate the rest of the code for the call */
1808 if (!compiler_call_helper(c, 2,
1809 s->v.ClassDef.bases,
1810 s->v.ClassDef.keywords,
1811 s->v.ClassDef.starargs,
1812 s->v.ClassDef.kwargs))
1813 return 0;
1814
1815 /* 6. apply decorators */
1816 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1817 ADDOP_I(c, CALL_FUNCTION, 1);
1818 }
1819
1820 /* 7. store into <name> */
1821 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1822 return 0;
1823 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824}
1825
1826static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001827compiler_ifexp(struct compiler *c, expr_ty e)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 basicblock *end, *next;
1830
1831 assert(e->kind == IfExp_kind);
1832 end = compiler_new_block(c);
1833 if (end == NULL)
1834 return 0;
1835 next = compiler_new_block(c);
1836 if (next == NULL)
1837 return 0;
1838 VISIT(c, expr, e->v.IfExp.test);
1839 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1840 VISIT(c, expr, e->v.IfExp.body);
1841 ADDOP_JREL(c, JUMP_FORWARD, end);
1842 compiler_use_next_block(c, next);
1843 VISIT(c, expr, e->v.IfExp.orelse);
1844 compiler_use_next_block(c, end);
1845 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001846}
1847
1848static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849compiler_lambda(struct compiler *c, expr_ty e)
1850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001852 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 static identifier name;
1854 int kw_default_count = 0, arglength;
1855 arguments_ty args = e->v.Lambda.args;
1856 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (!name) {
1859 name = PyUnicode_InternFromString("<lambda>");
1860 if (!name)
1861 return 0;
1862 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001863
Benjamin Peterson419d9a82013-02-10 09:48:22 -05001864 if (args->defaults)
1865 VISIT_SEQ(c, expr, args->defaults);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (args->kwonlyargs) {
1867 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1868 args->kw_defaults);
1869 if (res < 0) return 0;
1870 kw_default_count = res;
1871 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001872 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001873 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* Make None the first constant, so the lambda can't have a
1877 docstring. */
1878 if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
1879 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 c->u->u_argcount = asdl_seq_LEN(args->args);
1882 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
1883 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1884 if (c->u->u_ste->ste_generator) {
1885 ADDOP_IN_SCOPE(c, POP_TOP);
1886 }
1887 else {
1888 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1889 }
1890 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001891 qualname = c->u->u_qualname;
1892 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04001894 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 arglength = asdl_seq_LEN(args->defaults);
1898 arglength |= kw_default_count << 8;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001899 compiler_make_closure(c, co, arglength, qualname);
1900 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_DECREF(co);
1902
1903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904}
1905
1906static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907compiler_if(struct compiler *c, stmt_ty s)
1908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 basicblock *end, *next;
1910 int constant;
1911 assert(s->kind == If_kind);
1912 end = compiler_new_block(c);
1913 if (end == NULL)
1914 return 0;
1915
Georg Brandl8334fd92010-12-04 10:26:46 +00001916 constant = expr_constant(c, s->v.If.test);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 /* constant = 0: "if 0"
1918 * constant = 1: "if 1", "if 2", ...
1919 * constant = -1: rest */
1920 if (constant == 0) {
1921 if (s->v.If.orelse)
1922 VISIT_SEQ(c, stmt, s->v.If.orelse);
1923 } else if (constant == 1) {
1924 VISIT_SEQ(c, stmt, s->v.If.body);
1925 } else {
1926 if (s->v.If.orelse) {
1927 next = compiler_new_block(c);
1928 if (next == NULL)
1929 return 0;
1930 }
1931 else
1932 next = end;
1933 VISIT(c, expr, s->v.If.test);
1934 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
1935 VISIT_SEQ(c, stmt, s->v.If.body);
1936 ADDOP_JREL(c, JUMP_FORWARD, end);
1937 if (s->v.If.orelse) {
1938 compiler_use_next_block(c, next);
1939 VISIT_SEQ(c, stmt, s->v.If.orelse);
1940 }
1941 }
1942 compiler_use_next_block(c, end);
1943 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944}
1945
1946static int
1947compiler_for(struct compiler *c, stmt_ty s)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 start = compiler_new_block(c);
1952 cleanup = compiler_new_block(c);
1953 end = compiler_new_block(c);
1954 if (start == NULL || end == NULL || cleanup == NULL)
1955 return 0;
1956 ADDOP_JREL(c, SETUP_LOOP, end);
1957 if (!compiler_push_fblock(c, LOOP, start))
1958 return 0;
1959 VISIT(c, expr, s->v.For.iter);
1960 ADDOP(c, GET_ITER);
1961 compiler_use_next_block(c, start);
1962 ADDOP_JREL(c, FOR_ITER, cleanup);
1963 VISIT(c, expr, s->v.For.target);
1964 VISIT_SEQ(c, stmt, s->v.For.body);
1965 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1966 compiler_use_next_block(c, cleanup);
1967 ADDOP(c, POP_BLOCK);
1968 compiler_pop_fblock(c, LOOP, start);
1969 VISIT_SEQ(c, stmt, s->v.For.orelse);
1970 compiler_use_next_block(c, end);
1971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972}
1973
1974static int
1975compiler_while(struct compiler *c, stmt_ty s)
1976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 basicblock *loop, *orelse, *end, *anchor = NULL;
Georg Brandl8334fd92010-12-04 10:26:46 +00001978 int constant = expr_constant(c, s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (constant == 0) {
1981 if (s->v.While.orelse)
1982 VISIT_SEQ(c, stmt, s->v.While.orelse);
1983 return 1;
1984 }
1985 loop = compiler_new_block(c);
1986 end = compiler_new_block(c);
1987 if (constant == -1) {
1988 anchor = compiler_new_block(c);
1989 if (anchor == NULL)
1990 return 0;
1991 }
1992 if (loop == NULL || end == NULL)
1993 return 0;
1994 if (s->v.While.orelse) {
1995 orelse = compiler_new_block(c);
1996 if (orelse == NULL)
1997 return 0;
1998 }
1999 else
2000 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 ADDOP_JREL(c, SETUP_LOOP, end);
2003 compiler_use_next_block(c, loop);
2004 if (!compiler_push_fblock(c, LOOP, loop))
2005 return 0;
2006 if (constant == -1) {
2007 VISIT(c, expr, s->v.While.test);
2008 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
2009 }
2010 VISIT_SEQ(c, stmt, s->v.While.body);
2011 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* XXX should the two POP instructions be in a separate block
2014 if there is no else clause ?
2015 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (constant == -1) {
2018 compiler_use_next_block(c, anchor);
2019 ADDOP(c, POP_BLOCK);
2020 }
2021 compiler_pop_fblock(c, LOOP, loop);
2022 if (orelse != NULL) /* what if orelse is just pass? */
2023 VISIT_SEQ(c, stmt, s->v.While.orelse);
2024 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027}
2028
2029static int
2030compiler_continue(struct compiler *c)
2031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2033 static const char IN_FINALLY_ERROR_MSG[] =
2034 "'continue' not supported inside 'finally' clause";
2035 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (!c->u->u_nfblocks)
2038 return compiler_error(c, LOOP_ERROR_MSG);
2039 i = c->u->u_nfblocks - 1;
2040 switch (c->u->u_fblock[i].fb_type) {
2041 case LOOP:
2042 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2043 break;
2044 case EXCEPT:
2045 case FINALLY_TRY:
2046 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2047 /* Prevent continue anywhere under a finally
2048 even if hidden in a sub-try or except. */
2049 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2050 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2051 }
2052 if (i == -1)
2053 return compiler_error(c, LOOP_ERROR_MSG);
2054 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2055 break;
2056 case FINALLY_END:
2057 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2058 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061}
2062
2063/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064
2065 SETUP_FINALLY L
2066 <code for body>
2067 POP_BLOCK
2068 LOAD_CONST <None>
2069 L: <code for finalbody>
2070 END_FINALLY
2071
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 The special instructions use the block stack. Each block
2073 stack entry contains the instruction that created it (here
2074 SETUP_FINALLY), the level of the value stack at the time the
2075 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 Pushes the current value stack level and the label
2079 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 POP_BLOCK:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Pops en entry from the block stack, and pops the value
2082 stack until its level is the same as indicated on the
2083 block stack. (The label is ignored.)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 END_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 Pops a variable number of entries from the *value* stack
2086 and re-raises the exception they specify. The number of
2087 entries popped depends on the (pseudo) exception type.
2088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 The block stack is unwound when an exception is raised:
2090 when a SETUP_FINALLY entry is found, the exception is pushed
2091 onto the value stack (and the exception condition is cleared),
2092 and the interpreter jumps to the label gotten from the block
2093 stack.
2094*/
2095
2096static int
2097compiler_try_finally(struct compiler *c, stmt_ty s)
2098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 basicblock *body, *end;
2100 body = compiler_new_block(c);
2101 end = compiler_new_block(c);
2102 if (body == NULL || end == NULL)
2103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 ADDOP_JREL(c, SETUP_FINALLY, end);
2106 compiler_use_next_block(c, body);
2107 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2108 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002109 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2110 if (!compiler_try_except(c, s))
2111 return 0;
2112 }
2113 else {
2114 VISIT_SEQ(c, stmt, s->v.Try.body);
2115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 ADDOP(c, POP_BLOCK);
2117 compiler_pop_fblock(c, FINALLY_TRY, body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2120 compiler_use_next_block(c, end);
2121 if (!compiler_push_fblock(c, FINALLY_END, end))
2122 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002123 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 ADDOP(c, END_FINALLY);
2125 compiler_pop_fblock(c, FINALLY_END, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128}
2129
2130/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002131 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 (The contents of the value stack is shown in [], with the top
2133 at the right; 'tb' is trace-back info, 'val' the exception's
2134 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135
2136 Value stack Label Instruction Argument
2137 [] SETUP_EXCEPT L1
2138 [] <code for S>
2139 [] POP_BLOCK
2140 [] JUMP_FORWARD L0
2141
2142 [tb, val, exc] L1: DUP )
2143 [tb, val, exc, exc] <evaluate E1> )
2144 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2145 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
2146 [tb, val, exc] POP
2147 [tb, val] <assign to V1> (or POP if no V1)
2148 [tb] POP
2149 [] <code for S1>
2150 JUMP_FORWARD L0
2151
2152 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 .............................etc.......................
2154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
2156
2157 [] L0: <next statement>
2158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 Of course, parts are not generated if Vi or Ei is not present.
2160*/
2161static int
2162compiler_try_except(struct compiler *c, stmt_ty s)
2163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 basicblock *body, *orelse, *except, *end;
2165 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 body = compiler_new_block(c);
2168 except = compiler_new_block(c);
2169 orelse = compiler_new_block(c);
2170 end = compiler_new_block(c);
2171 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2172 return 0;
2173 ADDOP_JREL(c, SETUP_EXCEPT, except);
2174 compiler_use_next_block(c, body);
2175 if (!compiler_push_fblock(c, EXCEPT, body))
2176 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002177 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 ADDOP(c, POP_BLOCK);
2179 compiler_pop_fblock(c, EXCEPT, body);
2180 ADDOP_JREL(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002181 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 compiler_use_next_block(c, except);
2183 for (i = 0; i < n; i++) {
2184 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002185 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (!handler->v.ExceptHandler.type && i < n-1)
2187 return compiler_error(c, "default 'except:' must be last");
2188 c->u->u_lineno_set = 0;
2189 c->u->u_lineno = handler->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002190 c->u->u_col_offset = handler->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 except = compiler_new_block(c);
2192 if (except == NULL)
2193 return 0;
2194 if (handler->v.ExceptHandler.type) {
2195 ADDOP(c, DUP_TOP);
2196 VISIT(c, expr, handler->v.ExceptHandler.type);
2197 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2198 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
2199 }
2200 ADDOP(c, POP_TOP);
2201 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002202 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00002203
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002204 cleanup_end = compiler_new_block(c);
2205 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002206 if (!(cleanup_end || cleanup_body))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002207 return 0;
Guido van Rossumb940e112007-01-10 16:19:56 +00002208
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002209 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
2210 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002212 /*
2213 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002214 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002215 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03002216 try:
2217 # body
2218 finally:
2219 name = None
2220 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002221 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002223 /* second try: */
2224 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
2225 compiler_use_next_block(c, cleanup_body);
2226 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2227 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002229 /* second # body */
2230 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2231 ADDOP(c, POP_BLOCK);
2232 ADDOP(c, POP_EXCEPT);
2233 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002235 /* finally: */
2236 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2237 compiler_use_next_block(c, cleanup_end);
2238 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
2239 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002241 /* name = None */
2242 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2243 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002245 /* del name */
2246 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002248 ADDOP(c, END_FINALLY);
2249 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 }
2251 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002252 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002254 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05002255 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002256 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257
Guido van Rossumb940e112007-01-10 16:19:56 +00002258 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002259 ADDOP(c, POP_TOP);
2260 compiler_use_next_block(c, cleanup_body);
2261 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
2262 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05002264 ADDOP(c, POP_EXCEPT);
2265 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 }
2267 ADDOP_JREL(c, JUMP_FORWARD, end);
2268 compiler_use_next_block(c, except);
2269 }
2270 ADDOP(c, END_FINALLY);
2271 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002272 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 compiler_use_next_block(c, end);
2274 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275}
2276
2277static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002278compiler_try(struct compiler *c, stmt_ty s) {
2279 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2280 return compiler_try_finally(c, s);
2281 else
2282 return compiler_try_except(c, s);
2283}
2284
2285
2286static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287compiler_import_as(struct compiler *c, identifier name, identifier asname)
2288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* The IMPORT_NAME opcode was already generated. This function
2290 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 If there is a dot in name, we need to split it and emit a
2293 LOAD_ATTR for each name.
2294 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
2296 PyUnicode_GET_LENGTH(name), 1);
2297 if (dot == -2)
2298 return -1;
2299 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 /* Consume the base module name to get the first attribute */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002301 Py_ssize_t pos = dot + 1;
2302 while (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 PyObject *attr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002304 dot = PyUnicode_FindChar(name, '.', pos,
2305 PyUnicode_GET_LENGTH(name), 1);
2306 if (dot == -2)
2307 return -1;
2308 attr = PyUnicode_Substring(name, pos,
2309 (dot != -1) ? dot :
2310 PyUnicode_GET_LENGTH(name));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (!attr)
2312 return -1;
2313 ADDOP_O(c, LOAD_ATTR, attr, names);
2314 Py_DECREF(attr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002315 pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 }
2317 }
2318 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002319}
2320
2321static int
2322compiler_import(struct compiler *c, stmt_ty s)
2323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* The Import node stores a module name like a.b.c as a single
2325 string. This is convenient for all cases except
2326 import a.b.c as d
2327 where we need to parse that string to extract the individual
2328 module names.
2329 XXX Perhaps change the representation to make this case simpler?
2330 */
2331 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 for (i = 0; i < n; i++) {
2334 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2335 int r;
2336 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 level = PyLong_FromLong(0);
2339 if (level == NULL)
2340 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 ADDOP_O(c, LOAD_CONST, level, consts);
2343 Py_DECREF(level);
2344 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2345 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (alias->asname) {
2348 r = compiler_import_as(c, alias->name, alias->asname);
2349 if (!r)
2350 return r;
2351 }
2352 else {
2353 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002354 Py_ssize_t dot = PyUnicode_FindChar(
2355 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02002356 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002357 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02002358 if (tmp == NULL)
2359 return 0;
2360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002362 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 Py_DECREF(tmp);
2364 }
2365 if (!r)
2366 return r;
2367 }
2368 }
2369 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370}
2371
2372static int
2373compiler_from_import(struct compiler *c, stmt_ty s)
2374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 PyObject *names = PyTuple_New(n);
2378 PyObject *level;
2379 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (!empty_string) {
2382 empty_string = PyUnicode_FromString("");
2383 if (!empty_string)
2384 return 0;
2385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 if (!names)
2388 return 0;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 level = PyLong_FromLong(s->v.ImportFrom.level);
2391 if (!level) {
2392 Py_DECREF(names);
2393 return 0;
2394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* build up the names */
2397 for (i = 0; i < n; i++) {
2398 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2399 Py_INCREF(alias->name);
2400 PyTuple_SET_ITEM(names, i, alias->name);
2401 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
2404 !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
2405 Py_DECREF(level);
2406 Py_DECREF(names);
2407 return compiler_error(c, "from __future__ imports must occur "
2408 "at the beginning of the file");
2409 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 ADDOP_O(c, LOAD_CONST, level, consts);
2412 Py_DECREF(level);
2413 ADDOP_O(c, LOAD_CONST, names, consts);
2414 Py_DECREF(names);
2415 if (s->v.ImportFrom.module) {
2416 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2417 }
2418 else {
2419 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
2420 }
2421 for (i = 0; i < n; i++) {
2422 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
2423 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 assert(n == 1);
2427 ADDOP(c, IMPORT_STAR);
2428 return 1;
2429 }
2430
2431 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2432 store_name = alias->name;
2433 if (alias->asname)
2434 store_name = alias->asname;
2435
2436 if (!compiler_nameop(c, store_name, Store)) {
2437 Py_DECREF(names);
2438 return 0;
2439 }
2440 }
2441 /* remove imported module */
2442 ADDOP(c, POP_TOP);
2443 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444}
2445
2446static int
2447compiler_assert(struct compiler *c, stmt_ty s)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 static PyObject *assertion_error = NULL;
2450 basicblock *end;
Victor Stinner14e461d2013-08-26 22:28:21 +02002451 PyObject* msg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452
Georg Brandl8334fd92010-12-04 10:26:46 +00002453 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return 1;
2455 if (assertion_error == NULL) {
2456 assertion_error = PyUnicode_InternFromString("AssertionError");
2457 if (assertion_error == NULL)
2458 return 0;
2459 }
2460 if (s->v.Assert.test->kind == Tuple_kind &&
2461 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
Victor Stinner14e461d2013-08-26 22:28:21 +02002462 msg = PyUnicode_FromString("assertion is always true, "
2463 "perhaps remove parentheses?");
2464 if (msg == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 return 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002466 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg,
2467 c->c_filename, c->u->u_lineno,
2468 NULL, NULL) == -1) {
2469 Py_DECREF(msg);
2470 return 0;
2471 }
2472 Py_DECREF(msg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 }
2474 VISIT(c, expr, s->v.Assert.test);
2475 end = compiler_new_block(c);
2476 if (end == NULL)
2477 return 0;
2478 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
2479 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2480 if (s->v.Assert.msg) {
2481 VISIT(c, expr, s->v.Assert.msg);
2482 ADDOP_I(c, CALL_FUNCTION, 1);
2483 }
2484 ADDOP_I(c, RAISE_VARARGS, 1);
2485 compiler_use_next_block(c, end);
2486 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487}
2488
2489static int
2490compiler_visit_stmt(struct compiler *c, stmt_ty s)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* Always assign a lineno to the next instruction for a stmt. */
2495 c->u->u_lineno = s->lineno;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00002496 c->u->u_col_offset = s->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 switch (s->kind) {
2500 case FunctionDef_kind:
2501 return compiler_function(c, s);
2502 case ClassDef_kind:
2503 return compiler_class(c, s);
2504 case Return_kind:
2505 if (c->u->u_ste->ste_type != FunctionBlock)
2506 return compiler_error(c, "'return' outside function");
2507 if (s->v.Return.value) {
2508 VISIT(c, expr, s->v.Return.value);
2509 }
2510 else
2511 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2512 ADDOP(c, RETURN_VALUE);
2513 break;
2514 case Delete_kind:
2515 VISIT_SEQ(c, expr, s->v.Delete.targets)
2516 break;
2517 case Assign_kind:
2518 n = asdl_seq_LEN(s->v.Assign.targets);
2519 VISIT(c, expr, s->v.Assign.value);
2520 for (i = 0; i < n; i++) {
2521 if (i < n - 1)
2522 ADDOP(c, DUP_TOP);
2523 VISIT(c, expr,
2524 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2525 }
2526 break;
2527 case AugAssign_kind:
2528 return compiler_augassign(c, s);
2529 case For_kind:
2530 return compiler_for(c, s);
2531 case While_kind:
2532 return compiler_while(c, s);
2533 case If_kind:
2534 return compiler_if(c, s);
2535 case Raise_kind:
2536 n = 0;
2537 if (s->v.Raise.exc) {
2538 VISIT(c, expr, s->v.Raise.exc);
2539 n++;
2540 if (s->v.Raise.cause) {
2541 VISIT(c, expr, s->v.Raise.cause);
2542 n++;
2543 }
2544 }
2545 ADDOP_I(c, RAISE_VARARGS, n);
2546 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002547 case Try_kind:
2548 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 case Assert_kind:
2550 return compiler_assert(c, s);
2551 case Import_kind:
2552 return compiler_import(c, s);
2553 case ImportFrom_kind:
2554 return compiler_from_import(c, s);
2555 case Global_kind:
2556 case Nonlocal_kind:
2557 break;
2558 case Expr_kind:
2559 if (c->c_interactive && c->c_nestlevel <= 1) {
2560 VISIT(c, expr, s->v.Expr.value);
2561 ADDOP(c, PRINT_EXPR);
2562 }
2563 else if (s->v.Expr.value->kind != Str_kind &&
2564 s->v.Expr.value->kind != Num_kind) {
2565 VISIT(c, expr, s->v.Expr.value);
2566 ADDOP(c, POP_TOP);
2567 }
2568 break;
2569 case Pass_kind:
2570 break;
2571 case Break_kind:
2572 if (!compiler_in_loop(c))
2573 return compiler_error(c, "'break' outside loop");
2574 ADDOP(c, BREAK_LOOP);
2575 break;
2576 case Continue_kind:
2577 return compiler_continue(c);
2578 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05002579 return compiler_with(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 }
2581 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582}
2583
2584static int
2585unaryop(unaryop_ty op)
2586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 switch (op) {
2588 case Invert:
2589 return UNARY_INVERT;
2590 case Not:
2591 return UNARY_NOT;
2592 case UAdd:
2593 return UNARY_POSITIVE;
2594 case USub:
2595 return UNARY_NEGATIVE;
2596 default:
2597 PyErr_Format(PyExc_SystemError,
2598 "unary op %d should not be possible", op);
2599 return 0;
2600 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601}
2602
2603static int
2604binop(struct compiler *c, operator_ty op)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 switch (op) {
2607 case Add:
2608 return BINARY_ADD;
2609 case Sub:
2610 return BINARY_SUBTRACT;
2611 case Mult:
2612 return BINARY_MULTIPLY;
2613 case Div:
2614 return BINARY_TRUE_DIVIDE;
2615 case Mod:
2616 return BINARY_MODULO;
2617 case Pow:
2618 return BINARY_POWER;
2619 case LShift:
2620 return BINARY_LSHIFT;
2621 case RShift:
2622 return BINARY_RSHIFT;
2623 case BitOr:
2624 return BINARY_OR;
2625 case BitXor:
2626 return BINARY_XOR;
2627 case BitAnd:
2628 return BINARY_AND;
2629 case FloorDiv:
2630 return BINARY_FLOOR_DIVIDE;
2631 default:
2632 PyErr_Format(PyExc_SystemError,
2633 "binary op %d should not be possible", op);
2634 return 0;
2635 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636}
2637
2638static int
2639cmpop(cmpop_ty op)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 switch (op) {
2642 case Eq:
2643 return PyCmp_EQ;
2644 case NotEq:
2645 return PyCmp_NE;
2646 case Lt:
2647 return PyCmp_LT;
2648 case LtE:
2649 return PyCmp_LE;
2650 case Gt:
2651 return PyCmp_GT;
2652 case GtE:
2653 return PyCmp_GE;
2654 case Is:
2655 return PyCmp_IS;
2656 case IsNot:
2657 return PyCmp_IS_NOT;
2658 case In:
2659 return PyCmp_IN;
2660 case NotIn:
2661 return PyCmp_NOT_IN;
2662 default:
2663 return PyCmp_BAD;
2664 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665}
2666
2667static int
2668inplace_binop(struct compiler *c, operator_ty op)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 switch (op) {
2671 case Add:
2672 return INPLACE_ADD;
2673 case Sub:
2674 return INPLACE_SUBTRACT;
2675 case Mult:
2676 return INPLACE_MULTIPLY;
2677 case Div:
2678 return INPLACE_TRUE_DIVIDE;
2679 case Mod:
2680 return INPLACE_MODULO;
2681 case Pow:
2682 return INPLACE_POWER;
2683 case LShift:
2684 return INPLACE_LSHIFT;
2685 case RShift:
2686 return INPLACE_RSHIFT;
2687 case BitOr:
2688 return INPLACE_OR;
2689 case BitXor:
2690 return INPLACE_XOR;
2691 case BitAnd:
2692 return INPLACE_AND;
2693 case FloorDiv:
2694 return INPLACE_FLOOR_DIVIDE;
2695 default:
2696 PyErr_Format(PyExc_SystemError,
2697 "inplace binary op %d should not be possible", op);
2698 return 0;
2699 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700}
2701
2702static int
2703compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 int op, scope, arg;
2706 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 PyObject *dict = c->u->u_names;
2709 PyObject *mangled;
2710 /* XXX AugStore isn't used anywhere! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 mangled = _Py_Mangle(c->u->u_private, name);
2713 if (!mangled)
2714 return 0;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002715
Benjamin Peterson70b224d2012-12-06 17:49:58 -05002716 assert(PyUnicode_CompareWithASCIIString(name, "None") &&
2717 PyUnicode_CompareWithASCIIString(name, "True") &&
2718 PyUnicode_CompareWithASCIIString(name, "False"));
2719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 op = 0;
2721 optype = OP_NAME;
2722 scope = PyST_GetScope(c->u->u_ste, mangled);
2723 switch (scope) {
2724 case FREE:
2725 dict = c->u->u_freevars;
2726 optype = OP_DEREF;
2727 break;
2728 case CELL:
2729 dict = c->u->u_cellvars;
2730 optype = OP_DEREF;
2731 break;
2732 case LOCAL:
2733 if (c->u->u_ste->ste_type == FunctionBlock)
2734 optype = OP_FAST;
2735 break;
2736 case GLOBAL_IMPLICIT:
2737 if (c->u->u_ste->ste_type == FunctionBlock &&
2738 !c->u->u_ste->ste_unoptimized)
2739 optype = OP_GLOBAL;
2740 break;
2741 case GLOBAL_EXPLICIT:
2742 optype = OP_GLOBAL;
2743 break;
2744 default:
2745 /* scope can be 0 */
2746 break;
2747 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002750 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 switch (optype) {
2753 case OP_DEREF:
2754 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04002755 case Load:
2756 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
2757 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 case Store: op = STORE_DEREF; break;
2759 case AugLoad:
2760 case AugStore:
2761 break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00002762 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 case Param:
2764 default:
2765 PyErr_SetString(PyExc_SystemError,
2766 "param invalid for deref variable");
2767 return 0;
2768 }
2769 break;
2770 case OP_FAST:
2771 switch (ctx) {
2772 case Load: op = LOAD_FAST; break;
2773 case Store: op = STORE_FAST; break;
2774 case Del: op = DELETE_FAST; break;
2775 case AugLoad:
2776 case AugStore:
2777 break;
2778 case Param:
2779 default:
2780 PyErr_SetString(PyExc_SystemError,
2781 "param invalid for local variable");
2782 return 0;
2783 }
2784 ADDOP_O(c, op, mangled, varnames);
2785 Py_DECREF(mangled);
2786 return 1;
2787 case OP_GLOBAL:
2788 switch (ctx) {
2789 case Load: op = LOAD_GLOBAL; break;
2790 case Store: op = STORE_GLOBAL; break;
2791 case Del: op = DELETE_GLOBAL; break;
2792 case AugLoad:
2793 case AugStore:
2794 break;
2795 case Param:
2796 default:
2797 PyErr_SetString(PyExc_SystemError,
2798 "param invalid for global variable");
2799 return 0;
2800 }
2801 break;
2802 case OP_NAME:
2803 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00002804 case Load: op = LOAD_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 case Store: op = STORE_NAME; break;
2806 case Del: op = DELETE_NAME; break;
2807 case AugLoad:
2808 case AugStore:
2809 break;
2810 case Param:
2811 default:
2812 PyErr_SetString(PyExc_SystemError,
2813 "param invalid for name variable");
2814 return 0;
2815 }
2816 break;
2817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 assert(op);
2820 arg = compiler_add_o(c, dict, mangled);
2821 Py_DECREF(mangled);
2822 if (arg < 0)
2823 return 0;
2824 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825}
2826
2827static int
2828compiler_boolop(struct compiler *c, expr_ty e)
2829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 basicblock *end;
2831 int jumpi, i, n;
2832 asdl_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 assert(e->kind == BoolOp_kind);
2835 if (e->v.BoolOp.op == And)
2836 jumpi = JUMP_IF_FALSE_OR_POP;
2837 else
2838 jumpi = JUMP_IF_TRUE_OR_POP;
2839 end = compiler_new_block(c);
2840 if (end == NULL)
2841 return 0;
2842 s = e->v.BoolOp.values;
2843 n = asdl_seq_LEN(s) - 1;
2844 assert(n >= 0);
2845 for (i = 0; i < n; ++i) {
2846 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
2847 ADDOP_JABS(c, jumpi, end);
2848 }
2849 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
2850 compiler_use_next_block(c, end);
2851 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852}
2853
2854static int
2855compiler_list(struct compiler *c, expr_ty e)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 int n = asdl_seq_LEN(e->v.List.elts);
2858 if (e->v.List.ctx == Store) {
2859 int i, seen_star = 0;
2860 for (i = 0; i < n; i++) {
2861 expr_ty elt = asdl_seq_GET(e->v.List.elts, i);
2862 if (elt->kind == Starred_kind && !seen_star) {
2863 if ((i >= (1 << 8)) ||
2864 (n-i-1 >= (INT_MAX >> 8)))
2865 return compiler_error(c,
2866 "too many expressions in "
2867 "star-unpacking assignment");
2868 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2869 seen_star = 1;
2870 asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value);
2871 } else if (elt->kind == Starred_kind) {
2872 return compiler_error(c,
2873 "two starred expressions in assignment");
2874 }
2875 }
2876 if (!seen_star) {
2877 ADDOP_I(c, UNPACK_SEQUENCE, n);
2878 }
2879 }
2880 VISIT_SEQ(c, expr, e->v.List.elts);
2881 if (e->v.List.ctx == Load) {
2882 ADDOP_I(c, BUILD_LIST, n);
2883 }
2884 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885}
2886
2887static int
2888compiler_tuple(struct compiler *c, expr_ty e)
2889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 int n = asdl_seq_LEN(e->v.Tuple.elts);
2891 if (e->v.Tuple.ctx == Store) {
2892 int i, seen_star = 0;
2893 for (i = 0; i < n; i++) {
2894 expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i);
2895 if (elt->kind == Starred_kind && !seen_star) {
2896 if ((i >= (1 << 8)) ||
2897 (n-i-1 >= (INT_MAX >> 8)))
2898 return compiler_error(c,
2899 "too many expressions in "
2900 "star-unpacking assignment");
2901 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
2902 seen_star = 1;
2903 asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value);
2904 } else if (elt->kind == Starred_kind) {
2905 return compiler_error(c,
2906 "two starred expressions in assignment");
2907 }
2908 }
2909 if (!seen_star) {
2910 ADDOP_I(c, UNPACK_SEQUENCE, n);
2911 }
2912 }
2913 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2914 if (e->v.Tuple.ctx == Load) {
2915 ADDOP_I(c, BUILD_TUPLE, n);
2916 }
2917 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918}
2919
2920static int
2921compiler_compare(struct compiler *c, expr_ty e)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 int i, n;
2924 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2927 VISIT(c, expr, e->v.Compare.left);
2928 n = asdl_seq_LEN(e->v.Compare.ops);
2929 assert(n > 0);
2930 if (n > 1) {
2931 cleanup = compiler_new_block(c);
2932 if (cleanup == NULL)
2933 return 0;
2934 VISIT(c, expr,
2935 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
2936 }
2937 for (i = 1; i < n; i++) {
2938 ADDOP(c, DUP_TOP);
2939 ADDOP(c, ROT_THREE);
2940 ADDOP_I(c, COMPARE_OP,
2941 cmpop((cmpop_ty)(asdl_seq_GET(
2942 e->v.Compare.ops, i - 1))));
2943 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
2944 NEXT_BLOCK(c);
2945 if (i < (n - 1))
2946 VISIT(c, expr,
2947 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2948 }
2949 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
2950 ADDOP_I(c, COMPARE_OP,
2951 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
2952 if (n > 1) {
2953 basicblock *end = compiler_new_block(c);
2954 if (end == NULL)
2955 return 0;
2956 ADDOP_JREL(c, JUMP_FORWARD, end);
2957 compiler_use_next_block(c, cleanup);
2958 ADDOP(c, ROT_TWO);
2959 ADDOP(c, POP_TOP);
2960 compiler_use_next_block(c, end);
2961 }
2962 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963}
2964
2965static int
2966compiler_call(struct compiler *c, expr_ty e)
2967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 VISIT(c, expr, e->v.Call.func);
2969 return compiler_call_helper(c, 0,
2970 e->v.Call.args,
2971 e->v.Call.keywords,
2972 e->v.Call.starargs,
2973 e->v.Call.kwargs);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002974}
2975
2976/* shared code between compiler_call and compiler_class */
2977static int
2978compiler_call_helper(struct compiler *c,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 int n, /* Args already pushed */
2980 asdl_seq *args,
2981 asdl_seq *keywords,
2982 expr_ty starargs,
2983 expr_ty kwargs)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 int code = 0;
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 n += asdl_seq_LEN(args);
2988 VISIT_SEQ(c, expr, args);
2989 if (keywords) {
2990 VISIT_SEQ(c, keyword, keywords);
2991 n |= asdl_seq_LEN(keywords) << 8;
2992 }
2993 if (starargs) {
2994 VISIT(c, expr, starargs);
2995 code |= 1;
2996 }
2997 if (kwargs) {
2998 VISIT(c, expr, kwargs);
2999 code |= 2;
3000 }
3001 switch (code) {
3002 case 0:
3003 ADDOP_I(c, CALL_FUNCTION, n);
3004 break;
3005 case 1:
3006 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3007 break;
3008 case 2:
3009 ADDOP_I(c, CALL_FUNCTION_KW, n);
3010 break;
3011 case 3:
3012 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3013 break;
3014 }
3015 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016}
3017
Nick Coghlan650f0d02007-04-15 12:05:43 +00003018
3019/* List and set comprehensions and generator expressions work by creating a
3020 nested function to perform the actual iteration. This means that the
3021 iteration variables don't leak into the current scope.
3022 The defined function is called immediately following its definition, with the
3023 result of that call being the result of the expression.
3024 The LC/SC version returns the populated container, while the GE version is
3025 flagged in symtable.c as a generator, so it returns the generator object
3026 when the function is called.
3027 This code *knows* that the loop cannot contain break, continue, or return,
3028 so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops.
3029
3030 Possible cleanups:
3031 - iterate over the generator sequence instead of using recursion
3032*/
3033
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035compiler_comprehension_generator(struct compiler *c,
3036 asdl_seq *generators, int gen_index,
3037 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 /* generate code for the iterator, then each of the ifs,
3040 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 comprehension_ty gen;
3043 basicblock *start, *anchor, *skip, *if_cleanup;
3044 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 start = compiler_new_block(c);
3047 skip = compiler_new_block(c);
3048 if_cleanup = compiler_new_block(c);
3049 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3052 anchor == NULL)
3053 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 if (gen_index == 0) {
3058 /* Receive outermost iter as an implicit argument */
3059 c->u->u_argcount = 1;
3060 ADDOP_I(c, LOAD_FAST, 0);
3061 }
3062 else {
3063 /* Sub-iter - calculate on the fly */
3064 VISIT(c, expr, gen->iter);
3065 ADDOP(c, GET_ITER);
3066 }
3067 compiler_use_next_block(c, start);
3068 ADDOP_JREL(c, FOR_ITER, anchor);
3069 NEXT_BLOCK(c);
3070 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 /* XXX this needs to be cleaned up...a lot! */
3073 n = asdl_seq_LEN(gen->ifs);
3074 for (i = 0; i < n; i++) {
3075 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
3076 VISIT(c, expr, e);
3077 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
3078 NEXT_BLOCK(c);
3079 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 if (++gen_index < asdl_seq_LEN(generators))
3082 if (!compiler_comprehension_generator(c,
3083 generators, gen_index,
3084 elt, val, type))
3085 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 /* only append after the last for generator */
3088 if (gen_index >= asdl_seq_LEN(generators)) {
3089 /* comprehension specific code */
3090 switch (type) {
3091 case COMP_GENEXP:
3092 VISIT(c, expr, elt);
3093 ADDOP(c, YIELD_VALUE);
3094 ADDOP(c, POP_TOP);
3095 break;
3096 case COMP_LISTCOMP:
3097 VISIT(c, expr, elt);
3098 ADDOP_I(c, LIST_APPEND, gen_index + 1);
3099 break;
3100 case COMP_SETCOMP:
3101 VISIT(c, expr, elt);
3102 ADDOP_I(c, SET_ADD, gen_index + 1);
3103 break;
3104 case COMP_DICTCOMP:
3105 /* With 'd[k] = v', v is evaluated before k, so we do
3106 the same. */
3107 VISIT(c, expr, val);
3108 VISIT(c, expr, elt);
3109 ADDOP_I(c, MAP_ADD, gen_index + 1);
3110 break;
3111 default:
3112 return 0;
3113 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 compiler_use_next_block(c, skip);
3116 }
3117 compiler_use_next_block(c, if_cleanup);
3118 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3119 compiler_use_next_block(c, anchor);
3120
3121 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122}
3123
3124static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003125compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 asdl_seq *generators, expr_ty elt, expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00003127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 PyCodeObject *co = NULL;
3129 expr_ty outermost_iter;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003130 PyObject *qualname = NULL;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 outermost_iter = ((comprehension_ty)
3133 asdl_seq_GET(generators, 0))->iter;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003134
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003135 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
3136 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 goto error;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 if (type != COMP_GENEXP) {
3140 int op;
3141 switch (type) {
3142 case COMP_LISTCOMP:
3143 op = BUILD_LIST;
3144 break;
3145 case COMP_SETCOMP:
3146 op = BUILD_SET;
3147 break;
3148 case COMP_DICTCOMP:
3149 op = BUILD_MAP;
3150 break;
3151 default:
3152 PyErr_Format(PyExc_SystemError,
3153 "unknown comprehension type %d", type);
3154 goto error_in_scope;
3155 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 ADDOP_I(c, op, 0);
3158 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (!compiler_comprehension_generator(c, generators, 0, elt,
3161 val, type))
3162 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 if (type != COMP_GENEXP) {
3165 ADDOP(c, RETURN_VALUE);
3166 }
3167
3168 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003169 qualname = c->u->u_qualname;
3170 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04003172 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 goto error;
3174
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003175 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003177 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 Py_DECREF(co);
3179
3180 VISIT(c, expr, outermost_iter);
3181 ADDOP(c, GET_ITER);
3182 ADDOP_I(c, CALL_FUNCTION, 1);
3183 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003184error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003186error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01003187 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 Py_XDECREF(co);
3189 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00003190}
3191
3192static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193compiler_genexp(struct compiler *c, expr_ty e)
3194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 static identifier name;
3196 if (!name) {
3197 name = PyUnicode_FromString("<genexpr>");
3198 if (!name)
3199 return 0;
3200 }
3201 assert(e->kind == GeneratorExp_kind);
3202 return compiler_comprehension(c, e, COMP_GENEXP, name,
3203 e->v.GeneratorExp.generators,
3204 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003205}
3206
3207static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00003208compiler_listcomp(struct compiler *c, expr_ty e)
3209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 static identifier name;
3211 if (!name) {
3212 name = PyUnicode_FromString("<listcomp>");
3213 if (!name)
3214 return 0;
3215 }
3216 assert(e->kind == ListComp_kind);
3217 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
3218 e->v.ListComp.generators,
3219 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003220}
3221
3222static int
3223compiler_setcomp(struct compiler *c, expr_ty e)
3224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 static identifier name;
3226 if (!name) {
3227 name = PyUnicode_FromString("<setcomp>");
3228 if (!name)
3229 return 0;
3230 }
3231 assert(e->kind == SetComp_kind);
3232 return compiler_comprehension(c, e, COMP_SETCOMP, name,
3233 e->v.SetComp.generators,
3234 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00003235}
3236
3237
3238static int
3239compiler_dictcomp(struct compiler *c, expr_ty e)
3240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 static identifier name;
3242 if (!name) {
3243 name = PyUnicode_FromString("<dictcomp>");
3244 if (!name)
3245 return 0;
3246 }
3247 assert(e->kind == DictComp_kind);
3248 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
3249 e->v.DictComp.generators,
3250 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00003251}
3252
3253
3254static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255compiler_visit_keyword(struct compiler *c, keyword_ty k)
3256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3258 VISIT(c, expr, k->value);
3259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260}
3261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 whether they are true or false.
3264
3265 Return values: 1 for true, 0 for false, -1 for non-constant.
3266 */
3267
3268static int
Georg Brandl8334fd92010-12-04 10:26:46 +00003269expr_constant(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 char *id;
3272 switch (e->kind) {
3273 case Ellipsis_kind:
3274 return 1;
3275 case Num_kind:
3276 return PyObject_IsTrue(e->v.Num.n);
3277 case Str_kind:
3278 return PyObject_IsTrue(e->v.Str.s);
3279 case Name_kind:
3280 /* optimize away names that can't be reassigned */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003281 id = PyUnicode_AsUTF8(e->v.Name.id);
Benjamin Peterson442f2092012-12-06 17:41:04 -05003282 if (id && strcmp(id, "__debug__") == 0)
3283 return !c->c_optimize;
3284 return -1;
3285 case NameConstant_kind: {
3286 PyObject *o = e->v.NameConstant.value;
3287 if (o == Py_None)
3288 return 0;
3289 else if (o == Py_True)
3290 return 1;
3291 else if (o == Py_False)
3292 return 0;
3293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 default:
3295 return -1;
3296 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297}
3298
Guido van Rossumc2e20742006-02-27 22:32:47 +00003299/*
3300 Implements the with statement from PEP 343.
3301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 The semantics outlined in that PEP are as follows:
Guido van Rossumc2e20742006-02-27 22:32:47 +00003303
3304 with EXPR as VAR:
3305 BLOCK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306
Guido van Rossumc2e20742006-02-27 22:32:47 +00003307 It is implemented roughly as:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308
Thomas Wouters477c8d52006-05-27 19:21:47 +00003309 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003310 exit = context.__exit__ # not calling it
3311 value = context.__enter__()
3312 try:
3313 VAR = value # if VAR present in the syntax
3314 BLOCK
3315 finally:
3316 if an exception was raised:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003318 else:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320 exit(*exc)
3321 */
3322static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003323compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003324{
Guido van Rossumc2e20742006-02-27 22:32:47 +00003325 basicblock *block, *finally;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003326 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003327
3328 assert(s->kind == With_kind);
3329
Guido van Rossumc2e20742006-02-27 22:32:47 +00003330 block = compiler_new_block(c);
3331 finally = compiler_new_block(c);
3332 if (!block || !finally)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003333 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003334
Thomas Wouters477c8d52006-05-27 19:21:47 +00003335 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003336 VISIT(c, expr, item->context_expr);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003337 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003338
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003339 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003340 compiler_use_next_block(c, block);
3341 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003342 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003343 }
3344
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003345 if (item->optional_vars) {
3346 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00003347 }
3348 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003350 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003351 }
3352
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003353 pos++;
3354 if (pos == asdl_seq_LEN(s->v.With.items))
3355 /* BLOCK code */
3356 VISIT_SEQ(c, stmt, s->v.With.body)
3357 else if (!compiler_with(c, s, pos))
3358 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003359
3360 /* End of try block; start the finally block */
3361 ADDOP(c, POP_BLOCK);
3362 compiler_pop_fblock(c, FINALLY_TRY, block);
3363
3364 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3365 compiler_use_next_block(c, finally);
3366 if (!compiler_push_fblock(c, FINALLY_END, finally))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00003367 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003368
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003369 /* Finally block starts; context.__exit__ is on the stack under
3370 the exception or return information. Just issue our magic
3371 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003372 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003373
3374 /* Finally block ends. */
3375 ADDOP(c, END_FINALLY);
3376 compiler_pop_fblock(c, FINALLY_END, finally);
3377 return 1;
3378}
3379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380static int
3381compiler_visit_expr(struct compiler *c, expr_ty e)
3382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 /* If expr e has a different line number than the last expr/stmt,
3386 set a new line number for the next instruction.
3387 */
3388 if (e->lineno > c->u->u_lineno) {
3389 c->u->u_lineno = e->lineno;
3390 c->u->u_lineno_set = 0;
3391 }
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003392 /* Updating the column offset is always harmless. */
3393 c->u->u_col_offset = e->col_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 switch (e->kind) {
3395 case BoolOp_kind:
3396 return compiler_boolop(c, e);
3397 case BinOp_kind:
3398 VISIT(c, expr, e->v.BinOp.left);
3399 VISIT(c, expr, e->v.BinOp.right);
3400 ADDOP(c, binop(c, e->v.BinOp.op));
3401 break;
3402 case UnaryOp_kind:
3403 VISIT(c, expr, e->v.UnaryOp.operand);
3404 ADDOP(c, unaryop(e->v.UnaryOp.op));
3405 break;
3406 case Lambda_kind:
3407 return compiler_lambda(c, e);
3408 case IfExp_kind:
3409 return compiler_ifexp(c, e);
3410 case Dict_kind:
3411 n = asdl_seq_LEN(e->v.Dict.values);
3412 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
3413 for (i = 0; i < n; i++) {
3414 VISIT(c, expr,
3415 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3416 VISIT(c, expr,
3417 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3418 ADDOP(c, STORE_MAP);
3419 }
3420 break;
3421 case Set_kind:
3422 n = asdl_seq_LEN(e->v.Set.elts);
3423 VISIT_SEQ(c, expr, e->v.Set.elts);
3424 ADDOP_I(c, BUILD_SET, n);
3425 break;
3426 case GeneratorExp_kind:
3427 return compiler_genexp(c, e);
3428 case ListComp_kind:
3429 return compiler_listcomp(c, e);
3430 case SetComp_kind:
3431 return compiler_setcomp(c, e);
3432 case DictComp_kind:
3433 return compiler_dictcomp(c, e);
3434 case Yield_kind:
3435 if (c->u->u_ste->ste_type != FunctionBlock)
3436 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003437 if (e->v.Yield.value) {
3438 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 }
3440 else {
3441 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3442 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003443 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00003445 case YieldFrom_kind:
3446 if (c->u->u_ste->ste_type != FunctionBlock)
3447 return compiler_error(c, "'yield' outside function");
3448 VISIT(c, expr, e->v.YieldFrom.value);
3449 ADDOP(c, GET_ITER);
3450 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3451 ADDOP(c, YIELD_FROM);
3452 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 case Compare_kind:
3454 return compiler_compare(c, e);
3455 case Call_kind:
3456 return compiler_call(c, e);
3457 case Num_kind:
3458 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3459 break;
3460 case Str_kind:
3461 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3462 break;
3463 case Bytes_kind:
3464 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3465 break;
3466 case Ellipsis_kind:
3467 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3468 break;
Benjamin Peterson442f2092012-12-06 17:41:04 -05003469 case NameConstant_kind:
3470 ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts);
3471 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 /* The following exprs can be assignment targets. */
3473 case Attribute_kind:
3474 if (e->v.Attribute.ctx != AugStore)
3475 VISIT(c, expr, e->v.Attribute.value);
3476 switch (e->v.Attribute.ctx) {
3477 case AugLoad:
3478 ADDOP(c, DUP_TOP);
3479 /* Fall through to load */
3480 case Load:
3481 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3482 break;
3483 case AugStore:
3484 ADDOP(c, ROT_TWO);
3485 /* Fall through to save */
3486 case Store:
3487 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3488 break;
3489 case Del:
3490 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3491 break;
3492 case Param:
3493 default:
3494 PyErr_SetString(PyExc_SystemError,
3495 "param invalid in attribute expression");
3496 return 0;
3497 }
3498 break;
3499 case Subscript_kind:
3500 switch (e->v.Subscript.ctx) {
3501 case AugLoad:
3502 VISIT(c, expr, e->v.Subscript.value);
3503 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3504 break;
3505 case Load:
3506 VISIT(c, expr, e->v.Subscript.value);
3507 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3508 break;
3509 case AugStore:
3510 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3511 break;
3512 case Store:
3513 VISIT(c, expr, e->v.Subscript.value);
3514 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3515 break;
3516 case Del:
3517 VISIT(c, expr, e->v.Subscript.value);
3518 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3519 break;
3520 case Param:
3521 default:
3522 PyErr_SetString(PyExc_SystemError,
3523 "param invalid in subscript expression");
3524 return 0;
3525 }
3526 break;
3527 case Starred_kind:
3528 switch (e->v.Starred.ctx) {
3529 case Store:
3530 /* In all legitimate cases, the Starred node was already replaced
3531 * by compiler_list/compiler_tuple. XXX: is that okay? */
3532 return compiler_error(c,
3533 "starred assignment target must be in a list or tuple");
3534 default:
3535 return compiler_error(c,
3536 "can use starred expression only as assignment target");
3537 }
3538 break;
3539 case Name_kind:
3540 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3541 /* child nodes of List and Tuple will have expr_context set */
3542 case List_kind:
3543 return compiler_list(c, e);
3544 case Tuple_kind:
3545 return compiler_tuple(c, e);
3546 }
3547 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548}
3549
3550static int
3551compiler_augassign(struct compiler *c, stmt_ty s)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 expr_ty e = s->v.AugAssign.target;
3554 expr_ty auge;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 assert(s->kind == AugAssign_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 switch (e->kind) {
3559 case Attribute_kind:
3560 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
3561 AugLoad, e->lineno, e->col_offset, c->c_arena);
3562 if (auge == NULL)
3563 return 0;
3564 VISIT(c, expr, auge);
3565 VISIT(c, expr, s->v.AugAssign.value);
3566 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3567 auge->v.Attribute.ctx = AugStore;
3568 VISIT(c, expr, auge);
3569 break;
3570 case Subscript_kind:
3571 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
3572 AugLoad, e->lineno, e->col_offset, c->c_arena);
3573 if (auge == NULL)
3574 return 0;
3575 VISIT(c, expr, auge);
3576 VISIT(c, expr, s->v.AugAssign.value);
3577 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3578 auge->v.Subscript.ctx = AugStore;
3579 VISIT(c, expr, auge);
3580 break;
3581 case Name_kind:
3582 if (!compiler_nameop(c, e->v.Name.id, Load))
3583 return 0;
3584 VISIT(c, expr, s->v.AugAssign.value);
3585 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3586 return compiler_nameop(c, e->v.Name.id, Store);
3587 default:
3588 PyErr_Format(PyExc_SystemError,
3589 "invalid node type (%d) for augmented assignment",
3590 e->kind);
3591 return 0;
3592 }
3593 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594}
3595
3596static int
3597compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 struct fblockinfo *f;
3600 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3601 PyErr_SetString(PyExc_SystemError,
3602 "too many statically nested blocks");
3603 return 0;
3604 }
3605 f = &c->u->u_fblock[c->u->u_nfblocks++];
3606 f->fb_type = t;
3607 f->fb_block = b;
3608 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609}
3610
3611static void
3612compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 struct compiler_unit *u = c->u;
3615 assert(u->u_nfblocks > 0);
3616 u->u_nfblocks--;
3617 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3618 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619}
3620
Thomas Wouters89f507f2006-12-13 04:49:30 +00003621static int
3622compiler_in_loop(struct compiler *c) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 int i;
3624 struct compiler_unit *u = c->u;
3625 for (i = 0; i < u->u_nfblocks; ++i) {
3626 if (u->u_fblock[i].fb_type == LOOP)
3627 return 1;
3628 }
3629 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003630}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631/* Raises a SyntaxError and returns 0.
3632 If something goes wrong, a different exception may be raised.
3633*/
3634
3635static int
3636compiler_error(struct compiler *c, const char *errstr)
3637{
Benjamin Peterson43b06862011-05-27 09:08:01 -05003638 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640
Victor Stinner14e461d2013-08-26 22:28:21 +02003641 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 if (!loc) {
3643 Py_INCREF(Py_None);
3644 loc = Py_None;
3645 }
Victor Stinner14e461d2013-08-26 22:28:21 +02003646 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Benjamin Petersond4efd9e2010-09-20 23:02:10 +00003647 c->u->u_col_offset, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 if (!u)
3649 goto exit;
3650 v = Py_BuildValue("(zO)", errstr, u);
3651 if (!v)
3652 goto exit;
3653 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 Py_DECREF(loc);
3656 Py_XDECREF(u);
3657 Py_XDECREF(v);
3658 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659}
3660
3661static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662compiler_handle_subscr(struct compiler *c, const char *kind,
3663 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 /* XXX this code is duplicated */
3668 switch (ctx) {
3669 case AugLoad: /* fall through to Load */
3670 case Load: op = BINARY_SUBSCR; break;
3671 case AugStore:/* fall through to Store */
3672 case Store: op = STORE_SUBSCR; break;
3673 case Del: op = DELETE_SUBSCR; break;
3674 case Param:
3675 PyErr_Format(PyExc_SystemError,
3676 "invalid %s kind %d in subscript\n",
3677 kind, ctx);
3678 return 0;
3679 }
3680 if (ctx == AugLoad) {
Antoine Pitrou74a69fa2010-09-04 18:43:52 +00003681 ADDOP(c, DUP_TOP_TWO);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 }
3683 else if (ctx == AugStore) {
3684 ADDOP(c, ROT_THREE);
3685 }
3686 ADDOP(c, op);
3687 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688}
3689
3690static int
3691compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 int n = 2;
3694 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 /* only handles the cases where BUILD_SLICE is emitted */
3697 if (s->v.Slice.lower) {
3698 VISIT(c, expr, s->v.Slice.lower);
3699 }
3700 else {
3701 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 if (s->v.Slice.upper) {
3705 VISIT(c, expr, s->v.Slice.upper);
3706 }
3707 else {
3708 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3709 }
3710
3711 if (s->v.Slice.step) {
3712 n++;
3713 VISIT(c, expr, s->v.Slice.step);
3714 }
3715 ADDOP_I(c, BUILD_SLICE, n);
3716 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717}
3718
3719static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3721 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 switch (s->kind) {
3724 case Slice_kind:
3725 return compiler_slice(c, s, ctx);
3726 case Index_kind:
3727 VISIT(c, expr, s->v.Index.value);
3728 break;
3729 case ExtSlice_kind:
3730 default:
3731 PyErr_SetString(PyExc_SystemError,
3732 "extended slice invalid in nested slice");
3733 return 0;
3734 }
3735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736}
3737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738static int
3739compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 char * kindname = NULL;
3742 switch (s->kind) {
3743 case Index_kind:
3744 kindname = "index";
3745 if (ctx != AugStore) {
3746 VISIT(c, expr, s->v.Index.value);
3747 }
3748 break;
3749 case Slice_kind:
3750 kindname = "slice";
3751 if (ctx != AugStore) {
3752 if (!compiler_slice(c, s, ctx))
3753 return 0;
3754 }
3755 break;
3756 case ExtSlice_kind:
3757 kindname = "extended slice";
3758 if (ctx != AugStore) {
3759 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3760 for (i = 0; i < n; i++) {
3761 slice_ty sub = (slice_ty)asdl_seq_GET(
3762 s->v.ExtSlice.dims, i);
3763 if (!compiler_visit_nested_slice(c, sub, ctx))
3764 return 0;
3765 }
3766 ADDOP_I(c, BUILD_TUPLE, n);
3767 }
3768 break;
3769 default:
3770 PyErr_Format(PyExc_SystemError,
3771 "invalid subscript kind %d", s->kind);
3772 return 0;
3773 }
3774 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775}
3776
Thomas Wouters89f507f2006-12-13 04:49:30 +00003777/* End of the compiler section, beginning of the assembler section */
3778
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779/* do depth-first search of basic block graph, starting with block.
3780 post records the block indices in post-order.
3781
3782 XXX must handle implicit jumps from one block to next
3783*/
3784
Thomas Wouters89f507f2006-12-13 04:49:30 +00003785struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 PyObject *a_bytecode; /* string containing bytecode */
3787 int a_offset; /* offset into bytecode */
3788 int a_nblocks; /* number of reachable blocks */
3789 basicblock **a_postorder; /* list of blocks in dfs postorder */
3790 PyObject *a_lnotab; /* string containing lnotab */
3791 int a_lnotab_off; /* offset into lnotab */
3792 int a_lineno; /* last lineno of emitted instruction */
3793 int a_lineno_off; /* bytecode offset of last lineno */
Thomas Wouters89f507f2006-12-13 04:49:30 +00003794};
3795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796static void
3797dfs(struct compiler *c, basicblock *b, struct assembler *a)
3798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 int i;
3800 struct instr *instr = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 if (b->b_seen)
3803 return;
3804 b->b_seen = 1;
3805 if (b->b_next != NULL)
3806 dfs(c, b->b_next, a);
3807 for (i = 0; i < b->b_iused; i++) {
3808 instr = &b->b_instr[i];
3809 if (instr->i_jrel || instr->i_jabs)
3810 dfs(c, instr->i_target, a);
3811 }
3812 a->a_postorder[a->a_nblocks++] = b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813}
3814
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003815static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003816stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 int i, target_depth;
3819 struct instr *instr;
3820 if (b->b_seen || b->b_startdepth >= depth)
3821 return maxdepth;
3822 b->b_seen = 1;
3823 b->b_startdepth = depth;
3824 for (i = 0; i < b->b_iused; i++) {
3825 instr = &b->b_instr[i];
3826 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3827 if (depth > maxdepth)
3828 maxdepth = depth;
3829 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3830 if (instr->i_jrel || instr->i_jabs) {
3831 target_depth = depth;
3832 if (instr->i_opcode == FOR_ITER) {
3833 target_depth = depth-2;
3834 } else if (instr->i_opcode == SETUP_FINALLY ||
3835 instr->i_opcode == SETUP_EXCEPT) {
3836 target_depth = depth+3;
3837 if (target_depth > maxdepth)
3838 maxdepth = target_depth;
3839 }
3840 maxdepth = stackdepth_walk(c, instr->i_target,
3841 target_depth, maxdepth);
3842 if (instr->i_opcode == JUMP_ABSOLUTE ||
3843 instr->i_opcode == JUMP_FORWARD) {
3844 goto out; /* remaining code is dead */
3845 }
3846 }
3847 }
3848 if (b->b_next)
3849 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850out:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 b->b_seen = 0;
3852 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853}
3854
3855/* Find the flow path that needs the largest stack. We assume that
3856 * cycles in the flow graph have no net effect on the stack depth.
3857 */
3858static int
3859stackdepth(struct compiler *c)
3860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 basicblock *b, *entryblock;
3862 entryblock = NULL;
3863 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3864 b->b_seen = 0;
3865 b->b_startdepth = INT_MIN;
3866 entryblock = b;
3867 }
3868 if (!entryblock)
3869 return 0;
3870 return stackdepth_walk(c, entryblock, 0, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871}
3872
3873static int
3874assemble_init(struct assembler *a, int nblocks, int firstlineno)
3875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 memset(a, 0, sizeof(struct assembler));
3877 a->a_lineno = firstlineno;
3878 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3879 if (!a->a_bytecode)
3880 return 0;
3881 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3882 if (!a->a_lnotab)
3883 return 0;
3884 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3885 PyErr_NoMemory();
3886 return 0;
3887 }
3888 a->a_postorder = (basicblock **)PyObject_Malloc(
3889 sizeof(basicblock *) * nblocks);
3890 if (!a->a_postorder) {
3891 PyErr_NoMemory();
3892 return 0;
3893 }
3894 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895}
3896
3897static void
3898assemble_free(struct assembler *a)
3899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 Py_XDECREF(a->a_bytecode);
3901 Py_XDECREF(a->a_lnotab);
3902 if (a->a_postorder)
3903 PyObject_Free(a->a_postorder);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904}
3905
3906/* Return the size of a basic block in bytes. */
3907
3908static int
3909instrsize(struct instr *instr)
3910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 if (!instr->i_hasarg)
3912 return 1; /* 1 byte for the opcode*/
3913 if (instr->i_oparg > 0xffff)
3914 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3915 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916}
3917
3918static int
3919blocksize(basicblock *b)
3920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 int i;
3922 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 for (i = 0; i < b->b_iused; i++)
3925 size += instrsize(&b->b_instr[i]);
3926 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927}
3928
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +00003929/* Appends a pair to the end of the line number table, a_lnotab, representing
3930 the instruction's bytecode offset and line number. See
3931 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003932
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003933static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 int d_bytecode, d_lineno;
3937 int len;
3938 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 d_bytecode = a->a_offset - a->a_lineno_off;
3941 d_lineno = i->i_lineno - a->a_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 assert(d_bytecode >= 0);
3944 assert(d_lineno >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 if(d_bytecode == 0 && d_lineno == 0)
3947 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 if (d_bytecode > 255) {
3950 int j, nbytes, ncodes = d_bytecode / 255;
3951 nbytes = a->a_lnotab_off + 2 * ncodes;
3952 len = PyBytes_GET_SIZE(a->a_lnotab);
3953 if (nbytes >= len) {
3954 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
3955 len = nbytes;
3956 else if (len <= INT_MAX / 2)
3957 len *= 2;
3958 else {
3959 PyErr_NoMemory();
3960 return 0;
3961 }
3962 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3963 return 0;
3964 }
3965 lnotab = (unsigned char *)
3966 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3967 for (j = 0; j < ncodes; j++) {
3968 *lnotab++ = 255;
3969 *lnotab++ = 0;
3970 }
3971 d_bytecode -= ncodes * 255;
3972 a->a_lnotab_off += ncodes * 2;
3973 }
3974 assert(d_bytecode <= 255);
3975 if (d_lineno > 255) {
3976 int j, nbytes, ncodes = d_lineno / 255;
3977 nbytes = a->a_lnotab_off + 2 * ncodes;
3978 len = PyBytes_GET_SIZE(a->a_lnotab);
3979 if (nbytes >= len) {
3980 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
3981 len = nbytes;
3982 else if (len <= INT_MAX / 2)
3983 len *= 2;
3984 else {
3985 PyErr_NoMemory();
3986 return 0;
3987 }
3988 if (_PyBytes_Resize(&a->a_lnotab, len) < 0)
3989 return 0;
3990 }
3991 lnotab = (unsigned char *)
3992 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
3993 *lnotab++ = d_bytecode;
3994 *lnotab++ = 255;
3995 d_bytecode = 0;
3996 for (j = 1; j < ncodes; j++) {
3997 *lnotab++ = 0;
3998 *lnotab++ = 255;
3999 }
4000 d_lineno -= ncodes * 255;
4001 a->a_lnotab_off += ncodes * 2;
4002 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 len = PyBytes_GET_SIZE(a->a_lnotab);
4005 if (a->a_lnotab_off + 2 >= len) {
4006 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
4007 return 0;
4008 }
4009 lnotab = (unsigned char *)
4010 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 a->a_lnotab_off += 2;
4013 if (d_bytecode) {
4014 *lnotab++ = d_bytecode;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004015 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 }
4017 else { /* First line of a block; def stmt, etc. */
4018 *lnotab++ = 0;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004019 *lnotab++ = d_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 }
4021 a->a_lineno = i->i_lineno;
4022 a->a_lineno_off = a->a_offset;
4023 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004024}
4025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004026/* assemble_emit()
4027 Extend the bytecode with a new instruction.
4028 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004029*/
4030
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004031static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004032assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 int size, arg = 0, ext = 0;
4035 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
4036 char *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 size = instrsize(i);
4039 if (i->i_hasarg) {
4040 arg = i->i_oparg;
4041 ext = arg >> 16;
4042 }
4043 if (i->i_lineno && !assemble_lnotab(a, i))
4044 return 0;
4045 if (a->a_offset + size >= len) {
4046 if (len > PY_SSIZE_T_MAX / 2)
4047 return 0;
4048 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
4049 return 0;
4050 }
4051 code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
4052 a->a_offset += size;
4053 if (size == 6) {
4054 assert(i->i_hasarg);
4055 *code++ = (char)EXTENDED_ARG;
4056 *code++ = ext & 0xff;
4057 *code++ = ext >> 8;
4058 arg &= 0xffff;
4059 }
4060 *code++ = i->i_opcode;
4061 if (i->i_hasarg) {
4062 assert(size == 3 || size == 6);
4063 *code++ = arg & 0xff;
Victor Stinner4f2dab52011-05-27 16:46:51 +02004064 *code++ = arg >> 8;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 }
4066 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004067}
4068
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004069static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004072 basicblock *b;
4073 int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
4074 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 /* Compute the size of each block and fixup jump args.
4077 Replace block pointer with position in bytecode. */
4078 do {
4079 totsize = 0;
4080 for (i = a->a_nblocks - 1; i >= 0; i--) {
4081 b = a->a_postorder[i];
4082 bsize = blocksize(b);
4083 b->b_offset = totsize;
4084 totsize += bsize;
4085 }
4086 last_extended_arg_count = extended_arg_count;
4087 extended_arg_count = 0;
4088 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4089 bsize = b->b_offset;
4090 for (i = 0; i < b->b_iused; i++) {
4091 struct instr *instr = &b->b_instr[i];
4092 /* Relative jumps are computed relative to
4093 the instruction pointer after fetching
4094 the jump instruction.
4095 */
4096 bsize += instrsize(instr);
4097 if (instr->i_jabs)
4098 instr->i_oparg = instr->i_target->b_offset;
4099 else if (instr->i_jrel) {
4100 int delta = instr->i_target->b_offset - bsize;
4101 instr->i_oparg = delta;
4102 }
4103 else
4104 continue;
4105 if (instr->i_oparg > 0xffff)
4106 extended_arg_count++;
4107 }
4108 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 /* XXX: This is an awful hack that could hurt performance, but
4111 on the bright side it should work until we come up
4112 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 The issue is that in the first loop blocksize() is called
4115 which calls instrsize() which requires i_oparg be set
4116 appropriately. There is a bootstrap problem because
4117 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 So we loop until we stop seeing new EXTENDED_ARGs.
4120 The only EXTENDED_ARGs that could be popping up are
4121 ones in jump instructions. So this should converge
4122 fairly quickly.
4123 */
4124 } while (last_extended_arg_count != extended_arg_count);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004125}
4126
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004127static PyObject *
4128dict_keys_inorder(PyObject *dict, int offset)
4129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 PyObject *tuple, *k, *v;
4131 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 tuple = PyTuple_New(size);
4134 if (tuple == NULL)
4135 return NULL;
4136 while (PyDict_Next(dict, &pos, &k, &v)) {
4137 i = PyLong_AS_LONG(v);
4138 /* The keys of the dictionary are tuples. (see compiler_add_o)
4139 The object we want is always first, though. */
4140 k = PyTuple_GET_ITEM(k, 0);
4141 Py_INCREF(k);
4142 assert((i - offset) < size);
4143 assert((i - offset) >= 0);
4144 PyTuple_SET_ITEM(tuple, i - offset, k);
4145 }
4146 return tuple;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004147}
4148
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 PySTEntryObject *ste = c->u->u_ste;
4153 int flags = 0, n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 if (ste->ste_type == FunctionBlock) {
Benjamin Petersone8e14592013-05-16 14:37:25 -05004155 flags |= CO_NEWLOCALS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 if (!ste->ste_unoptimized)
4157 flags |= CO_OPTIMIZED;
4158 if (ste->ste_nested)
4159 flags |= CO_NESTED;
4160 if (ste->ste_generator)
4161 flags |= CO_GENERATOR;
4162 if (ste->ste_varargs)
4163 flags |= CO_VARARGS;
4164 if (ste->ste_varkeywords)
4165 flags |= CO_VARKEYWORDS;
4166 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 /* (Only) inherit compilerflags in PyCF_MASK */
4169 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004171 n = PyDict_Size(c->u->u_freevars);
4172 if (n < 0)
4173 return -1;
4174 if (n == 0) {
4175 n = PyDict_Size(c->u->u_cellvars);
4176 if (n < 0)
4177 return -1;
4178 if (n == 0) {
4179 flags |= CO_NOFREE;
4180 }
4181 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004184}
4185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186static PyCodeObject *
4187makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 PyObject *tmp;
4190 PyCodeObject *co = NULL;
4191 PyObject *consts = NULL;
4192 PyObject *names = NULL;
4193 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 PyObject *name = NULL;
4195 PyObject *freevars = NULL;
4196 PyObject *cellvars = NULL;
4197 PyObject *bytecode = NULL;
4198 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 tmp = dict_keys_inorder(c->u->u_consts, 0);
4201 if (!tmp)
4202 goto error;
4203 consts = PySequence_List(tmp); /* optimize_code requires a list */
4204 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 names = dict_keys_inorder(c->u->u_names, 0);
4207 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4208 if (!consts || !names || !varnames)
4209 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4212 if (!cellvars)
4213 goto error;
4214 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4215 if (!freevars)
4216 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 nlocals = PyDict_Size(c->u->u_varnames);
4218 flags = compute_code_flags(c);
4219 if (flags < 0)
4220 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
4223 if (!bytecode)
4224 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4227 if (!tmp)
4228 goto error;
4229 Py_DECREF(consts);
4230 consts = tmp;
4231
4232 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
4233 nlocals, stackdepth(c), flags,
4234 bytecode, consts, names, varnames,
4235 freevars, cellvars,
Victor Stinner14e461d2013-08-26 22:28:21 +02004236 c->c_filename, c->u->u_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 c->u->u_firstlineno,
4238 a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004239 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 Py_XDECREF(consts);
4241 Py_XDECREF(names);
4242 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 Py_XDECREF(name);
4244 Py_XDECREF(freevars);
4245 Py_XDECREF(cellvars);
4246 Py_XDECREF(bytecode);
4247 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004248}
4249
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004250
4251/* For debugging purposes only */
4252#if 0
4253static void
4254dump_instr(const struct instr *i)
4255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 const char *jrel = i->i_jrel ? "jrel " : "";
4257 const char *jabs = i->i_jabs ? "jabs " : "";
4258 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 *arg = '\0';
4261 if (i->i_hasarg)
4262 sprintf(arg, "arg: %d ", i->i_oparg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4265 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004266}
4267
4268static void
4269dump_basicblock(const basicblock *b)
4270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 const char *seen = b->b_seen ? "seen " : "";
4272 const char *b_return = b->b_return ? "return " : "";
4273 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4274 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4275 if (b->b_instr) {
4276 int i;
4277 for (i = 0; i < b->b_iused; i++) {
4278 fprintf(stderr, " [%02d] ", i);
4279 dump_instr(b->b_instr + i);
4280 }
4281 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004282}
4283#endif
4284
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285static PyCodeObject *
4286assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 basicblock *b, *entryblock;
4289 struct assembler a;
4290 int i, j, nblocks;
4291 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 /* Make sure every block that falls off the end returns None.
4294 XXX NEXT_BLOCK() isn't quite right, because if the last
4295 block ends with a jump or return b_next shouldn't set.
4296 */
4297 if (!c->u->u_curblock->b_return) {
4298 NEXT_BLOCK(c);
4299 if (addNone)
4300 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4301 ADDOP(c, RETURN_VALUE);
4302 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 nblocks = 0;
4305 entryblock = NULL;
4306 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4307 nblocks++;
4308 entryblock = b;
4309 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 /* Set firstlineno if it wasn't explicitly set. */
4312 if (!c->u->u_firstlineno) {
4313 if (entryblock && entryblock->b_instr)
4314 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4315 else
4316 c->u->u_firstlineno = 1;
4317 }
4318 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4319 goto error;
4320 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 /* Can't modify the bytecode after computing jump offsets. */
4323 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 /* Emit code in reverse postorder from dfs. */
4326 for (i = a.a_nblocks - 1; i >= 0; i--) {
4327 b = a.a_postorder[i];
4328 for (j = 0; j < b->b_iused; j++)
4329 if (!assemble_emit(&a, &b->b_instr[j]))
4330 goto error;
4331 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4334 goto error;
4335 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0)
4336 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 co = makecode(c, &a);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004339 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 assemble_free(&a);
4341 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004342}
Georg Brandl8334fd92010-12-04 10:26:46 +00004343
4344#undef PyAST_Compile
4345PyAPI_FUNC(PyCodeObject *)
4346PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
4347 PyArena *arena)
4348{
4349 return PyAST_CompileEx(mod, filename, flags, -1, arena);
4350}
4351
4352