blob: df12bde44067810ef3201c6b022de315796b390b [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
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Neal Norwitzf733a012006-10-29 18:30:10 +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
Jeremy Hylton819de6c2007-02-27 16:13:23 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +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
Neal Norwitzf733a012006-10-29 18:30:10 +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"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000110 /* Pointer to the most recently allocated block. By following b_list
111 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000112 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 basicblock *u_curblock; /* pointer to current block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
116 int u_nfblocks;
117 struct fblockinfo u_fblock[CO_MAXBLOCKS];
118
119 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000120 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 bool u_lineno_set; /* boolean to indicate whether instr
122 has been generated with current lineno */
123};
124
125/* This struct captures the global state of a compilation.
126
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000127The u pointer points to the current compilation unit, while units
128for enclosing blocks are stored in c_stack. The u and c_stack are
129managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130*/
131
132struct compiler {
133 const char *c_filename;
134 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136 PyCompilerFlags *c_flags;
137
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000138 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000139 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 struct compiler_unit *u; /* compiler state for current block */
142 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147static int compiler_enter_scope(struct compiler *, identifier, void *, int);
148static void compiler_free(struct compiler *);
149static basicblock *compiler_new_block(struct compiler *);
150static int compiler_next_instr(struct compiler *, basicblock *);
151static int compiler_addop(struct compiler *, int);
152static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
153static int compiler_addop_i(struct compiler *, int, int);
154static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155static basicblock *compiler_use_new_block(struct compiler *);
156static int compiler_error(struct compiler *, const char *);
157static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
158
159static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
160static int compiler_visit_stmt(struct compiler *, stmt_ty);
161static int compiler_visit_keyword(struct compiler *, keyword_ty);
162static int compiler_visit_expr(struct compiler *, expr_ty);
163static int compiler_augassign(struct compiler *, stmt_ty);
164static int compiler_visit_slice(struct compiler *, slice_ty,
165 expr_context_ty);
166
167static int compiler_push_fblock(struct compiler *, enum fblocktype,
168 basicblock *);
169static void compiler_pop_fblock(struct compiler *, enum fblocktype,
170 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000171/* Returns true if there is a loop on the fblock stack. */
172static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
174static int inplace_binop(struct compiler *, operator_ty);
175static int expr_constant(expr_ty e);
176
Guido van Rossumc2e20742006-02-27 22:32:47 +0000177static int compiler_with(struct compiler *, stmt_ty);
178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static PyCodeObject *assemble(struct compiler *, int addNone);
180static PyObject *__doc__;
181
182PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000183_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000184{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185 /* Name mangling: __private becomes _classname__private.
186 This is independent from how the name is used. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000187 const char *p, *name = PyString_AsString(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
Neal Norwitz84167d02006-08-12 01:45:47 +0000191 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000192 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000194 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000195 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000197 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000198
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000199 The only time a name with a dot can occur is when
200 we are compiling an import statement that has a
201 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000202
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000203 TODO(jhylton): Decide whether we want to support
204 mangling of the module name, e.g. __M.X.
205 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000206 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000207 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211 /* Strip leading underscores from class name */
212 while (*p == '_')
213 p++;
214 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 plen = strlen(p);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000219
220 assert(1 <= PY_SSIZE_T_MAX - nlen);
221 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
222
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000223 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 if (!ident)
225 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000227 buffer = PyString_AS_STRING(ident);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 strncpy(buffer+1, p, plen);
230 strcpy(buffer+1+plen, name);
231 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000232}
233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234static int
235compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000236{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 c->c_stack = PyList_New(0);
240 if (!c->c_stack)
241 return 0;
242
243 return 1;
244}
245
246PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000247PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249{
250 struct compiler c;
251 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000252 PyCompilerFlags local_flags;
253 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 if (!__doc__) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000256 __doc__ = PyString_InternFromString("__doc__");
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 if (!__doc__)
258 return NULL;
259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260
261 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000262 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_future = PyFuture_FromAST(mod, filename);
266 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000267 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 local_flags.cf_flags = 0;
270 flags = &local_flags;
271 }
272 merged = c.c_future->ff_features | flags->cf_flags;
273 c.c_future->ff_features = merged;
274 flags->cf_flags = merged;
275 c.c_flags = flags;
276 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
278 c.c_st = PySymtable_Build(mod, filename, c.c_future);
279 if (c.c_st == NULL) {
280 if (!PyErr_Occurred())
281 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000282 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 }
284
285 /* XXX initialize to NULL for now, need to handle */
286 c.c_encoding = NULL;
287
288 co = compiler_mod(&c, mod);
289
Thomas Wouters1175c432006-02-27 22:49:54 +0000290 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000292 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293 return co;
294}
295
296PyCodeObject *
297PyNode_Compile(struct _node *n, const char *filename)
298{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000299 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000300 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000301 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000302 if (!arena)
303 return NULL;
304 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000305 if (mod)
306 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000307 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000308 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000309}
310
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000311static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000313{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 if (c->c_st)
315 PySymtable_Free(c->c_st);
316 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000317 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319}
320
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000323{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000337 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000380 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394static void
395compiler_unit_check(struct compiler_unit *u)
396{
397 basicblock *block;
398 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Brett Cannona6c41bc2008-02-07 07:47:31 +0000399 assert((void *)block != (void *)0xcbcbcbcb);
400 assert((void *)block != (void *)0xfbfbfbfb);
401 assert((void *)block != (void *)0xdbdbdbdb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000402 if (block->b_instr != NULL) {
403 assert(block->b_ialloc > 0);
404 assert(block->b_iused > 0);
405 assert(block->b_ialloc >= block->b_iused);
406 }
407 else {
408 assert (block->b_iused == 0);
409 assert (block->b_ialloc == 0);
410 }
411 }
412}
413
414static void
415compiler_unit_free(struct compiler_unit *u)
416{
417 basicblock *b, *next;
418
419 compiler_unit_check(u);
420 b = u->u_blocks;
421 while (b != NULL) {
422 if (b->b_instr)
423 PyObject_Free((void *)b->b_instr);
424 next = b->b_list;
425 PyObject_Free((void *)b);
426 b = next;
427 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000428 Py_CLEAR(u->u_ste);
429 Py_CLEAR(u->u_name);
430 Py_CLEAR(u->u_consts);
431 Py_CLEAR(u->u_names);
432 Py_CLEAR(u->u_varnames);
433 Py_CLEAR(u->u_freevars);
434 Py_CLEAR(u->u_cellvars);
435 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436 PyObject_Free(u);
437}
438
439static int
440compiler_enter_scope(struct compiler *c, identifier name, void *key,
441 int lineno)
442{
443 struct compiler_unit *u;
444
Anthony Baxter7b782b62006-04-11 12:01:56 +0000445 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000446 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000447 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000448 PyErr_NoMemory();
449 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000450 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452 u->u_argcount = 0;
453 u->u_ste = PySymtable_Lookup(c->c_st, key);
454 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 compiler_unit_free(u);
456 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000457 }
458 Py_INCREF(name);
459 u->u_name = name;
460 u->u_varnames = list2dict(u->u_ste->ste_varnames);
461 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000462 if (!u->u_varnames || !u->u_cellvars) {
463 compiler_unit_free(u);
464 return 0;
465 }
466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000467 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000468 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000469 if (!u->u_freevars) {
470 compiler_unit_free(u);
471 return 0;
472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473
474 u->u_blocks = NULL;
475 u->u_tmpname = 0;
476 u->u_nfblocks = 0;
477 u->u_firstlineno = lineno;
478 u->u_lineno = 0;
479 u->u_lineno_set = false;
480 u->u_consts = PyDict_New();
481 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000482 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000483 return 0;
484 }
485 u->u_names = PyDict_New();
486 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488 return 0;
489 }
490
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000491 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492
493 /* Push the old compiler_unit on the stack. */
494 if (c->u) {
495 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000496 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
497 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000499 return 0;
500 }
501 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000502 u->u_private = c->u->u_private;
503 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504 }
505 c->u = u;
506
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000507 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000508 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 return 0;
510
511 return 1;
512}
513
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000514static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515compiler_exit_scope(struct compiler *c)
516{
517 int n;
518 PyObject *wrapper;
519
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000520 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000521 compiler_unit_free(c->u);
522 /* Restore c->u to the parent unit. */
523 n = PyList_GET_SIZE(c->c_stack) - 1;
524 if (n >= 0) {
525 wrapper = PyList_GET_ITEM(c->c_stack, n);
526 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000527 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000528 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000529 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000530 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531 compiler_unit_check(c->u);
532 }
533 else
534 c->u = NULL;
535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
Guido van Rossumc2e20742006-02-27 22:32:47 +0000538/* Allocate a new "anonymous" local variable.
539 Used by list comprehensions and with statements.
540*/
541
542static PyObject *
543compiler_new_tmpname(struct compiler *c)
544{
545 char tmpname[256];
546 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000547 return PyString_FromString(tmpname);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000548}
549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550/* Allocate a new block and return a pointer to it.
551 Returns NULL on error.
552*/
553
554static basicblock *
555compiler_new_block(struct compiler *c)
556{
557 basicblock *b;
558 struct compiler_unit *u;
559
560 u = c->u;
561 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000562 if (b == NULL) {
563 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000567 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000568 b->b_list = u->u_blocks;
569 u->u_blocks = b;
570 return b;
571}
572
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573static basicblock *
574compiler_use_new_block(struct compiler *c)
575{
576 basicblock *block = compiler_new_block(c);
577 if (block == NULL)
578 return NULL;
579 c->u->u_curblock = block;
580 return block;
581}
582
583static basicblock *
584compiler_next_block(struct compiler *c)
585{
586 basicblock *block = compiler_new_block(c);
587 if (block == NULL)
588 return NULL;
589 c->u->u_curblock->b_next = block;
590 c->u->u_curblock = block;
591 return block;
592}
593
594static basicblock *
595compiler_use_next_block(struct compiler *c, basicblock *block)
596{
597 assert(block != NULL);
598 c->u->u_curblock->b_next = block;
599 c->u->u_curblock = block;
600 return block;
601}
602
603/* Returns the offset of the next instruction in the current block's
604 b_instr array. Resizes the b_instr as necessary.
605 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000606*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000607
608static int
609compiler_next_instr(struct compiler *c, basicblock *b)
610{
611 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000612 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000613 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000614 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000615 if (b->b_instr == NULL) {
616 PyErr_NoMemory();
617 return -1;
618 }
619 b->b_ialloc = DEFAULT_BLOCK_SIZE;
620 memset((char *)b->b_instr, 0,
621 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000624 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 size_t oldsize, newsize;
626 oldsize = b->b_ialloc * sizeof(struct instr);
627 newsize = oldsize << 1;
Gregory P. Smith9d534572008-06-11 07:41:16 +0000628
629 if (oldsize > (PY_SIZE_MAX >> 1)) {
630 PyErr_NoMemory();
631 return -1;
632 }
633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634 if (newsize == 0) {
635 PyErr_NoMemory();
636 return -1;
637 }
638 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000639 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000640 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000641 if (tmp == NULL) {
642 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000643 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000644 }
645 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
647 }
648 return b->b_iused++;
649}
650
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000651/* Set the i_lineno member of the instruction at offset off if the
652 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +0000653 already been set. If it has been set, the call has no effect.
654
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +0000655 The line number is reset in the following cases:
656 - when entering a new scope
657 - on each statement
658 - on each expression that start a new line
659 - before the "except" clause
660 - before the "for" and "while" expressions
Neal Norwitzf733a012006-10-29 18:30:10 +0000661*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663static void
664compiler_set_lineno(struct compiler *c, int off)
665{
666 basicblock *b;
667 if (c->u->u_lineno_set)
668 return;
669 c->u->u_lineno_set = true;
670 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000671 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672}
673
674static int
675opcode_stack_effect(int opcode, int oparg)
676{
677 switch (opcode) {
678 case POP_TOP:
679 return -1;
680 case ROT_TWO:
681 case ROT_THREE:
682 return 0;
683 case DUP_TOP:
684 return 1;
685 case ROT_FOUR:
686 return 0;
687
688 case UNARY_POSITIVE:
689 case UNARY_NEGATIVE:
690 case UNARY_NOT:
691 case UNARY_CONVERT:
692 case UNARY_INVERT:
693 return 0;
694
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000695 case LIST_APPEND:
Antoine Pitroud0c35152008-12-17 00:38:28 +0000696 return -1;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000698 case BINARY_POWER:
699 case BINARY_MULTIPLY:
700 case BINARY_DIVIDE:
701 case BINARY_MODULO:
702 case BINARY_ADD:
703 case BINARY_SUBTRACT:
704 case BINARY_SUBSCR:
705 case BINARY_FLOOR_DIVIDE:
706 case BINARY_TRUE_DIVIDE:
707 return -1;
708 case INPLACE_FLOOR_DIVIDE:
709 case INPLACE_TRUE_DIVIDE:
710 return -1;
711
712 case SLICE+0:
713 return 1;
714 case SLICE+1:
715 return 0;
716 case SLICE+2:
717 return 0;
718 case SLICE+3:
719 return -1;
720
721 case STORE_SLICE+0:
722 return -2;
723 case STORE_SLICE+1:
724 return -3;
725 case STORE_SLICE+2:
726 return -3;
727 case STORE_SLICE+3:
728 return -4;
729
730 case DELETE_SLICE+0:
731 return -1;
732 case DELETE_SLICE+1:
733 return -2;
734 case DELETE_SLICE+2:
735 return -2;
736 case DELETE_SLICE+3:
737 return -3;
738
739 case INPLACE_ADD:
740 case INPLACE_SUBTRACT:
741 case INPLACE_MULTIPLY:
742 case INPLACE_DIVIDE:
743 case INPLACE_MODULO:
744 return -1;
745 case STORE_SUBSCR:
746 return -3;
Raymond Hettingereffde122007-12-18 18:26:18 +0000747 case STORE_MAP:
748 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000749 case DELETE_SUBSCR:
750 return -2;
751
752 case BINARY_LSHIFT:
753 case BINARY_RSHIFT:
754 case BINARY_AND:
755 case BINARY_XOR:
756 case BINARY_OR:
757 return -1;
758 case INPLACE_POWER:
759 return -1;
760 case GET_ITER:
761 return 0;
762
763 case PRINT_EXPR:
764 return -1;
765 case PRINT_ITEM:
766 return -1;
767 case PRINT_NEWLINE:
768 return 0;
769 case PRINT_ITEM_TO:
770 return -2;
771 case PRINT_NEWLINE_TO:
772 return -1;
773 case INPLACE_LSHIFT:
774 case INPLACE_RSHIFT:
775 case INPLACE_AND:
776 case INPLACE_XOR:
777 case INPLACE_OR:
778 return -1;
779 case BREAK_LOOP:
780 return 0;
Benjamin Peterson1880d8b2009-05-25 13:13:44 +0000781 case SETUP_WITH:
Benjamin Peterson49a6b0e2009-05-25 20:12:57 +0000782 return 4;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000783 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000784 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785 case LOAD_LOCALS:
786 return 1;
787 case RETURN_VALUE:
788 return -1;
789 case IMPORT_STAR:
790 return -1;
791 case EXEC_STMT:
792 return -3;
793 case YIELD_VALUE:
794 return 0;
795
796 case POP_BLOCK:
797 return 0;
798 case END_FINALLY:
799 return -1; /* or -2 or -3 if exception occurred */
800 case BUILD_CLASS:
801 return -2;
802
803 case STORE_NAME:
804 return -1;
805 case DELETE_NAME:
806 return 0;
807 case UNPACK_SEQUENCE:
808 return oparg-1;
809 case FOR_ITER:
810 return 1;
811
812 case STORE_ATTR:
813 return -2;
814 case DELETE_ATTR:
815 return -1;
816 case STORE_GLOBAL:
817 return -1;
818 case DELETE_GLOBAL:
819 return 0;
820 case DUP_TOPX:
821 return oparg;
822 case LOAD_CONST:
823 return 1;
824 case LOAD_NAME:
825 return 1;
826 case BUILD_TUPLE:
827 case BUILD_LIST:
828 return 1-oparg;
829 case BUILD_MAP:
830 return 1;
831 case LOAD_ATTR:
832 return 0;
833 case COMPARE_OP:
834 return -1;
835 case IMPORT_NAME:
836 return 0;
837 case IMPORT_FROM:
838 return 1;
839
840 case JUMP_FORWARD:
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000841 case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
842 case JUMP_IF_FALSE_OR_POP: /* "" */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000843 case JUMP_ABSOLUTE:
844 return 0;
845
Jeffrey Yasskin68d68522009-02-28 19:03:21 +0000846 case POP_JUMP_IF_FALSE:
847 case POP_JUMP_IF_TRUE:
848 return -1;
849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000850 case LOAD_GLOBAL:
851 return 1;
852
853 case CONTINUE_LOOP:
854 return 0;
855 case SETUP_LOOP:
856 return 0;
857 case SETUP_EXCEPT:
858 case SETUP_FINALLY:
859 return 3; /* actually pushed by an exception */
860
861 case LOAD_FAST:
862 return 1;
863 case STORE_FAST:
864 return -1;
865 case DELETE_FAST:
866 return 0;
867
868 case RAISE_VARARGS:
869 return -oparg;
870#define NARGS(o) (((o) % 256) + 2*((o) / 256))
871 case CALL_FUNCTION:
872 return -NARGS(oparg);
873 case CALL_FUNCTION_VAR:
874 case CALL_FUNCTION_KW:
875 return -NARGS(oparg)-1;
876 case CALL_FUNCTION_VAR_KW:
877 return -NARGS(oparg)-2;
878#undef NARGS
879 case MAKE_FUNCTION:
880 return -oparg;
881 case BUILD_SLICE:
882 if (oparg == 3)
883 return -2;
884 else
885 return -1;
886
887 case MAKE_CLOSURE:
888 return -oparg;
889 case LOAD_CLOSURE:
890 return 1;
891 case LOAD_DEREF:
892 return 1;
893 case STORE_DEREF:
894 return -1;
895 default:
896 fprintf(stderr, "opcode = %d\n", opcode);
897 Py_FatalError("opcode_stack_effect()");
898
899 }
900 return 0; /* not reachable */
901}
902
903/* Add an opcode with no argument.
904 Returns 0 on failure, 1 on success.
905*/
906
907static int
908compiler_addop(struct compiler *c, int opcode)
909{
910 basicblock *b;
911 struct instr *i;
912 int off;
913 off = compiler_next_instr(c, c->u->u_curblock);
914 if (off < 0)
915 return 0;
916 b = c->u->u_curblock;
917 i = &b->b_instr[off];
918 i->i_opcode = opcode;
919 i->i_hasarg = 0;
920 if (opcode == RETURN_VALUE)
921 b->b_return = 1;
922 compiler_set_lineno(c, off);
923 return 1;
924}
925
926static int
927compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
928{
929 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000930 Py_ssize_t arg;
Mark Dickinson105be772008-01-31 22:17:37 +0000931 unsigned char *p, *q;
932 Py_complex z;
933 double d;
934 int real_part_zero, imag_part_zero;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000936 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000937 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
938 if (PyFloat_Check(o)) {
Mark Dickinson105be772008-01-31 22:17:37 +0000939 d = PyFloat_AS_DOUBLE(o);
940 p = (unsigned char*) &d;
941 /* all we need is to make the tuple different in either the 0.0
942 * or -0.0 case from all others, just to avoid the "coercion".
943 */
944 if (*p==0 && p[sizeof(double)-1]==0)
945 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
946 else
947 t = PyTuple_Pack(2, o, o->ob_type);
948 }
949 else if (PyComplex_Check(o)) {
950 /* complex case is even messier: we need to make complex(x,
951 0.) different from complex(x, -0.) and complex(0., y)
952 different from complex(-0., y), for any x and y. In
953 particular, all four complex zeros should be
954 distinguished.*/
955 z = PyComplex_AsCComplex(o);
956 p = (unsigned char*) &(z.real);
957 q = (unsigned char*) &(z.imag);
958 /* all that matters here is that on IEEE platforms
959 real_part_zero will be true if z.real == 0., and false if
960 z.real == -0. In fact, real_part_zero will also be true
961 for some other rarely occurring nonzero floats, but this
962 doesn't matter. Similar comments apply to
963 imag_part_zero. */
964 real_part_zero = *p==0 && p[sizeof(double)-1]==0;
965 imag_part_zero = *q==0 && q[sizeof(double)-1]==0;
966 if (real_part_zero && imag_part_zero) {
967 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_True);
968 }
969 else if (real_part_zero && !imag_part_zero) {
970 t = PyTuple_Pack(4, o, o->ob_type, Py_True, Py_False);
971 }
972 else if (!real_part_zero && imag_part_zero) {
973 t = PyTuple_Pack(4, o, o->ob_type, Py_False, Py_True);
974 }
975 else {
976 t = PyTuple_Pack(2, o, o->ob_type);
977 }
978 }
979 else {
980 t = PyTuple_Pack(2, o, o->ob_type);
Alex Martellid8672aa2007-08-22 21:14:17 +0000981 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 if (t == NULL)
Mark Dickinson105be772008-01-31 22:17:37 +0000983 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984
985 v = PyDict_GetItem(dict, t);
986 if (!v) {
987 arg = PyDict_Size(dict);
988 v = PyInt_FromLong(arg);
989 if (!v) {
990 Py_DECREF(t);
991 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000992 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993 if (PyDict_SetItem(dict, t, v) < 0) {
994 Py_DECREF(t);
995 Py_DECREF(v);
996 return -1;
997 }
998 Py_DECREF(v);
999 }
1000 else
1001 arg = PyInt_AsLong(v);
1002 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004}
1005
1006static int
1007compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1008 PyObject *o)
1009{
1010 int arg = compiler_add_o(c, dict, o);
1011 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001012 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013 return compiler_addop_i(c, opcode, arg);
1014}
1015
1016static int
1017compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001018 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019{
1020 int arg;
1021 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1022 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001023 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001024 arg = compiler_add_o(c, dict, mangled);
1025 Py_DECREF(mangled);
1026 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001027 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001028 return compiler_addop_i(c, opcode, arg);
1029}
1030
1031/* Add an opcode with an integer argument.
1032 Returns 0 on failure, 1 on success.
1033*/
1034
1035static int
1036compiler_addop_i(struct compiler *c, int opcode, int oparg)
1037{
1038 struct instr *i;
1039 int off;
1040 off = compiler_next_instr(c, c->u->u_curblock);
1041 if (off < 0)
1042 return 0;
1043 i = &c->u->u_curblock->b_instr[off];
1044 i->i_opcode = opcode;
1045 i->i_oparg = oparg;
1046 i->i_hasarg = 1;
1047 compiler_set_lineno(c, off);
1048 return 1;
1049}
1050
1051static int
1052compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1053{
1054 struct instr *i;
1055 int off;
1056
1057 assert(b != NULL);
1058 off = compiler_next_instr(c, c->u->u_curblock);
1059 if (off < 0)
1060 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061 i = &c->u->u_curblock->b_instr[off];
1062 i->i_opcode = opcode;
1063 i->i_target = b;
1064 i->i_hasarg = 1;
1065 if (absolute)
1066 i->i_jabs = 1;
1067 else
1068 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001069 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070 return 1;
1071}
1072
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001073/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1074 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075 it as the current block. NEXT_BLOCK() also creates an implicit jump
1076 from the current block to the new block.
1077*/
1078
Neal Norwitzf733a012006-10-29 18:30:10 +00001079/* The returns inside these macros make it impossible to decref objects
1080 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081*/
1082
1083
1084#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001085 if (compiler_use_new_block((C)) == NULL) \
1086 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087}
1088
1089#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001090 if (compiler_next_block((C)) == NULL) \
1091 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092}
1093
1094#define ADDOP(C, OP) { \
1095 if (!compiler_addop((C), (OP))) \
1096 return 0; \
1097}
1098
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001099#define ADDOP_IN_SCOPE(C, OP) { \
1100 if (!compiler_addop((C), (OP))) { \
1101 compiler_exit_scope(c); \
1102 return 0; \
1103 } \
1104}
1105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106#define ADDOP_O(C, OP, O, TYPE) { \
1107 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1108 return 0; \
1109}
1110
1111#define ADDOP_NAME(C, OP, O, TYPE) { \
1112 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1113 return 0; \
1114}
1115
1116#define ADDOP_I(C, OP, O) { \
1117 if (!compiler_addop_i((C), (OP), (O))) \
1118 return 0; \
1119}
1120
1121#define ADDOP_JABS(C, OP, O) { \
1122 if (!compiler_addop_j((C), (OP), (O), 1)) \
1123 return 0; \
1124}
1125
1126#define ADDOP_JREL(C, OP, O) { \
1127 if (!compiler_addop_j((C), (OP), (O), 0)) \
1128 return 0; \
1129}
1130
1131/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1132 the ASDL name to synthesize the name of the C type and the visit function.
1133*/
1134
1135#define VISIT(C, TYPE, V) {\
1136 if (!compiler_visit_ ## TYPE((C), (V))) \
1137 return 0; \
1138}
1139
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001140#define VISIT_IN_SCOPE(C, TYPE, V) {\
1141 if (!compiler_visit_ ## TYPE((C), (V))) { \
1142 compiler_exit_scope(c); \
1143 return 0; \
1144 } \
1145}
1146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147#define VISIT_SLICE(C, V, CTX) {\
1148 if (!compiler_visit_slice((C), (V), (CTX))) \
1149 return 0; \
1150}
1151
1152#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001153 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001155 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001156 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001157 if (!compiler_visit_ ## TYPE((C), elt)) \
1158 return 0; \
1159 } \
1160}
1161
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001162#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001163 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001164 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001165 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001166 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001167 if (!compiler_visit_ ## TYPE((C), elt)) { \
1168 compiler_exit_scope(c); \
1169 return 0; \
1170 } \
1171 } \
1172}
1173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174static int
1175compiler_isdocstring(stmt_ty s)
1176{
1177 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001178 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179 return s->v.Expr.value->kind == Str_kind;
1180}
1181
1182/* Compile a sequence of statements, checking for a docstring. */
1183
1184static int
1185compiler_body(struct compiler *c, asdl_seq *stmts)
1186{
1187 int i = 0;
1188 stmt_ty st;
1189
1190 if (!asdl_seq_LEN(stmts))
1191 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001192 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001193 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1194 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 i = 1;
1196 VISIT(c, expr, st->v.Expr.value);
1197 if (!compiler_nameop(c, __doc__, Store))
1198 return 0;
1199 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001200 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001201 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202 return 1;
1203}
1204
1205static PyCodeObject *
1206compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001207{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001208 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 static PyObject *module;
1211 if (!module) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001212 module = PyString_InternFromString("<module>");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 if (!module)
1214 return NULL;
1215 }
Neal Norwitzed657552006-07-10 00:04:44 +00001216 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1217 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001218 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 switch (mod->kind) {
1220 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001221 if (!compiler_body(c, mod->v.Module.body)) {
1222 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225 break;
1226 case Interactive_kind:
1227 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001228 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001229 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230 break;
1231 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001232 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001233 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001234 break;
1235 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001236 PyErr_SetString(PyExc_SystemError,
1237 "suite should not be possible");
1238 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001240 PyErr_Format(PyExc_SystemError,
1241 "module kind %d should not be possible",
1242 mod->kind);
1243 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001244 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 co = assemble(c, addNone);
1246 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001247 return co;
1248}
1249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250/* The test for LOCAL must come before the test for FREE in order to
1251 handle classes where name is both local and free. The local var is
1252 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001253*/
1254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001255static int
1256get_ref_type(struct compiler *c, PyObject *name)
1257{
1258 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 if (scope == 0) {
1260 char buf[350];
1261 PyOS_snprintf(buf, sizeof(buf),
1262 "unknown scope for %.100s in %.100s(%s) in %s\n"
Amaury Forgeot d'Arc59ce0422009-01-17 20:18:59 +00001263 "symbols: %s\nlocals: %s\nglobals: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001264 PyString_AS_STRING(name),
1265 PyString_AS_STRING(c->u->u_name),
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001266 PyObject_REPR(c->u->u_ste->ste_id),
1267 c->c_filename,
1268 PyObject_REPR(c->u->u_ste->ste_symbols),
1269 PyObject_REPR(c->u->u_varnames),
1270 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 Py_FatalError(buf);
1273 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001274
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001275 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276}
1277
1278static int
1279compiler_lookup_arg(PyObject *dict, PyObject *name)
1280{
1281 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001282 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001284 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001286 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001288 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289 return PyInt_AS_LONG(v);
1290}
1291
1292static int
1293compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1294{
1295 int i, free = PyCode_GetNumFree(co);
1296 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001297 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1298 ADDOP_I(c, MAKE_FUNCTION, args);
1299 return 1;
1300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301 for (i = 0; i < free; ++i) {
1302 /* Bypass com_addop_varname because it will generate
1303 LOAD_DEREF but LOAD_CLOSURE is needed.
1304 */
1305 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1306 int arg, reftype;
1307
1308 /* Special case: If a class contains a method with a
1309 free variable that has the same name as a method,
1310 the name will be considered free *and* local in the
1311 class. It should be handled by the closure, as
1312 well as by the normal name loookup logic.
1313 */
1314 reftype = get_ref_type(c, name);
1315 if (reftype == CELL)
1316 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1317 else /* (reftype == FREE) */
1318 arg = compiler_lookup_arg(c->u->u_freevars, name);
1319 if (arg == -1) {
1320 printf("lookup %s in %s %d %d\n"
1321 "freevars of %s: %s\n",
1322 PyObject_REPR(name),
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001323 PyString_AS_STRING(c->u->u_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324 reftype, arg,
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001325 PyString_AS_STRING(co->co_name),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001326 PyObject_REPR(co->co_freevars));
1327 Py_FatalError("compiler_make_closure()");
1328 }
1329 ADDOP_I(c, LOAD_CLOSURE, arg);
1330 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001331 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001333 ADDOP_I(c, MAKE_CLOSURE, args);
1334 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335}
1336
1337static int
1338compiler_decorators(struct compiler *c, asdl_seq* decos)
1339{
1340 int i;
1341
1342 if (!decos)
1343 return 1;
1344
1345 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001346 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 }
1348 return 1;
1349}
1350
1351static int
1352compiler_arguments(struct compiler *c, arguments_ty args)
1353{
1354 int i;
1355 int n = asdl_seq_LEN(args->args);
1356 /* Correctly handle nested argument lists */
1357 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001358 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 if (arg->kind == Tuple_kind) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001360 PyObject *id = PyString_FromFormat(".%d", i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001361 if (id == NULL) {
1362 return 0;
1363 }
1364 if (!compiler_nameop(c, id, Load)) {
1365 Py_DECREF(id);
1366 return 0;
1367 }
1368 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001369 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 }
1371 }
1372 return 1;
1373}
1374
1375static int
1376compiler_function(struct compiler *c, stmt_ty s)
1377{
1378 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001379 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 arguments_ty args = s->v.FunctionDef.args;
Christian Heimes5224d282008-02-23 15:01:05 +00001381 asdl_seq* decos = s->v.FunctionDef.decorator_list;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001382 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 int i, n, docstring;
1384
1385 assert(s->kind == FunctionDef_kind);
1386
1387 if (!compiler_decorators(c, decos))
1388 return 0;
1389 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001390 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1392 s->lineno))
1393 return 0;
1394
Anthony Baxter7b782b62006-04-11 12:01:56 +00001395 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001396 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001397 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001398 first_const = st->v.Expr.value->v.Str.s;
1399 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001400 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001401 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001404 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001405 compiler_arguments(c, args);
1406
1407 c->u->u_argcount = asdl_seq_LEN(args->args);
1408 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001409 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001411 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1412 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413 }
1414 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001415 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416 if (co == NULL)
1417 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001419 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001420 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421
1422 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1423 ADDOP_I(c, CALL_FUNCTION, 1);
1424 }
1425
1426 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1427}
1428
1429static int
1430compiler_class(struct compiler *c, stmt_ty s)
1431{
Christian Heimes5224d282008-02-23 15:01:05 +00001432 int n, i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 PyObject *str;
Christian Heimes5224d282008-02-23 15:01:05 +00001435 asdl_seq* decos = s->v.ClassDef.decorator_list;
1436
1437 if (!compiler_decorators(c, decos))
1438 return 0;
1439
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 /* push class name on stack, needed by BUILD_CLASS */
1441 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1442 /* push the tuple of base classes on the stack */
1443 n = asdl_seq_LEN(s->v.ClassDef.bases);
1444 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001445 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 ADDOP_I(c, BUILD_TUPLE, n);
1447 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1448 s->lineno))
1449 return 0;
Amaury Forgeot d'Arc69b747b2008-03-28 20:30:50 +00001450 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001451 c->u->u_private = s->v.ClassDef.name;
1452 Py_INCREF(c->u->u_private);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001453 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 if (!str || !compiler_nameop(c, str, Load)) {
1455 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001456 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001458 }
1459
1460 Py_DECREF(str);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001461 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 if (!str || !compiler_nameop(c, str, Store)) {
1463 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001464 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001466 }
1467 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001469 if (!compiler_body(c, s->v.ClassDef.body)) {
1470 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001472 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001474 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1475 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001477 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 if (co == NULL)
1479 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001482 Py_DECREF(co);
1483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 ADDOP_I(c, CALL_FUNCTION, 0);
1485 ADDOP(c, BUILD_CLASS);
Christian Heimes5224d282008-02-23 15:01:05 +00001486 /* apply decorators */
1487 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1488 ADDOP_I(c, CALL_FUNCTION, 1);
1489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1491 return 0;
1492 return 1;
1493}
1494
1495static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001496compiler_ifexp(struct compiler *c, expr_ty e)
1497{
1498 basicblock *end, *next;
1499
1500 assert(e->kind == IfExp_kind);
1501 end = compiler_new_block(c);
1502 if (end == NULL)
1503 return 0;
1504 next = compiler_new_block(c);
1505 if (next == NULL)
1506 return 0;
1507 VISIT(c, expr, e->v.IfExp.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001508 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001509 VISIT(c, expr, e->v.IfExp.body);
1510 ADDOP_JREL(c, JUMP_FORWARD, end);
1511 compiler_use_next_block(c, next);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001512 VISIT(c, expr, e->v.IfExp.orelse);
1513 compiler_use_next_block(c, end);
1514 return 1;
1515}
1516
1517static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518compiler_lambda(struct compiler *c, expr_ty e)
1519{
1520 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001521 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522 arguments_ty args = e->v.Lambda.args;
1523 assert(e->kind == Lambda_kind);
1524
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001525 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001526 name = PyString_InternFromString("<lambda>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001527 if (!name)
1528 return 0;
1529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530
1531 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001532 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1534 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001535
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001536 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537 compiler_arguments(c, args);
1538
1539 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001540 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
Benjamin Peterson8d5934b2008-12-27 18:24:11 +00001541 if (c->u->u_ste->ste_generator) {
1542 ADDOP_IN_SCOPE(c, POP_TOP);
1543 }
1544 else {
1545 ADDOP_IN_SCOPE(c, RETURN_VALUE);
1546 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001548 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001549 if (co == NULL)
1550 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001552 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001553 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001554
1555 return 1;
1556}
1557
1558static int
1559compiler_print(struct compiler *c, stmt_ty s)
1560{
1561 int i, n;
1562 bool dest;
1563
1564 assert(s->kind == Print_kind);
1565 n = asdl_seq_LEN(s->v.Print.values);
1566 dest = false;
1567 if (s->v.Print.dest) {
1568 VISIT(c, expr, s->v.Print.dest);
1569 dest = true;
1570 }
1571 for (i = 0; i < n; i++) {
1572 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1573 if (dest) {
1574 ADDOP(c, DUP_TOP);
1575 VISIT(c, expr, e);
1576 ADDOP(c, ROT_TWO);
1577 ADDOP(c, PRINT_ITEM_TO);
1578 }
1579 else {
1580 VISIT(c, expr, e);
1581 ADDOP(c, PRINT_ITEM);
1582 }
1583 }
1584 if (s->v.Print.nl) {
1585 if (dest)
1586 ADDOP(c, PRINT_NEWLINE_TO)
1587 else
1588 ADDOP(c, PRINT_NEWLINE)
1589 }
1590 else if (dest)
1591 ADDOP(c, POP_TOP);
1592 return 1;
1593}
1594
1595static int
1596compiler_if(struct compiler *c, stmt_ty s)
1597{
1598 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001599 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600 assert(s->kind == If_kind);
1601 end = compiler_new_block(c);
1602 if (end == NULL)
1603 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001604
1605 constant = expr_constant(s->v.If.test);
1606 /* constant = 0: "if 0"
1607 * constant = 1: "if 1", "if 2", ...
1608 * constant = -1: rest */
1609 if (constant == 0) {
1610 if (s->v.If.orelse)
1611 VISIT_SEQ(c, stmt, s->v.If.orelse);
1612 } else if (constant == 1) {
1613 VISIT_SEQ(c, stmt, s->v.If.body);
1614 } else {
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001615 if (s->v.If.orelse) {
1616 next = compiler_new_block(c);
1617 if (next == NULL)
1618 return 0;
1619 }
1620 else
1621 next = end;
Georg Brandlddbaa662006-06-04 21:56:52 +00001622 VISIT(c, expr, s->v.If.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001623 ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
Georg Brandlddbaa662006-06-04 21:56:52 +00001624 VISIT_SEQ(c, stmt, s->v.If.body);
1625 ADDOP_JREL(c, JUMP_FORWARD, end);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001626 if (s->v.If.orelse) {
1627 compiler_use_next_block(c, next);
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001628 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001629 }
Georg Brandlddbaa662006-06-04 21:56:52 +00001630 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631 compiler_use_next_block(c, end);
1632 return 1;
1633}
1634
1635static int
1636compiler_for(struct compiler *c, stmt_ty s)
1637{
1638 basicblock *start, *cleanup, *end;
1639
1640 start = compiler_new_block(c);
1641 cleanup = compiler_new_block(c);
1642 end = compiler_new_block(c);
1643 if (start == NULL || end == NULL || cleanup == NULL)
1644 return 0;
1645 ADDOP_JREL(c, SETUP_LOOP, end);
1646 if (!compiler_push_fblock(c, LOOP, start))
1647 return 0;
1648 VISIT(c, expr, s->v.For.iter);
1649 ADDOP(c, GET_ITER);
1650 compiler_use_next_block(c, start);
1651 ADDOP_JREL(c, FOR_ITER, cleanup);
1652 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001653 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001654 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1655 compiler_use_next_block(c, cleanup);
1656 ADDOP(c, POP_BLOCK);
1657 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001658 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001659 compiler_use_next_block(c, end);
1660 return 1;
1661}
1662
1663static int
1664compiler_while(struct compiler *c, stmt_ty s)
1665{
1666 basicblock *loop, *orelse, *end, *anchor = NULL;
1667 int constant = expr_constant(s->v.While.test);
1668
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001669 if (constant == 0) {
1670 if (s->v.While.orelse)
1671 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 return 1;
Amaury Forgeot d'Arc16570f52008-01-24 22:51:18 +00001673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 loop = compiler_new_block(c);
1675 end = compiler_new_block(c);
1676 if (constant == -1) {
1677 anchor = compiler_new_block(c);
1678 if (anchor == NULL)
1679 return 0;
1680 }
1681 if (loop == NULL || end == NULL)
1682 return 0;
1683 if (s->v.While.orelse) {
1684 orelse = compiler_new_block(c);
1685 if (orelse == NULL)
1686 return 0;
1687 }
1688 else
1689 orelse = NULL;
1690
1691 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001692 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693 if (!compiler_push_fblock(c, LOOP, loop))
1694 return 0;
1695 if (constant == -1) {
1696 VISIT(c, expr, s->v.While.test);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001697 ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001699 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1701
1702 /* XXX should the two POP instructions be in a separate block
1703 if there is no else clause ?
1704 */
1705
1706 if (constant == -1) {
1707 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708 ADDOP(c, POP_BLOCK);
1709 }
1710 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001711 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001712 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713 compiler_use_next_block(c, end);
1714
1715 return 1;
1716}
1717
1718static int
1719compiler_continue(struct compiler *c)
1720{
1721 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001722 static const char IN_FINALLY_ERROR_MSG[] =
1723 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724 int i;
1725
1726 if (!c->u->u_nfblocks)
1727 return compiler_error(c, LOOP_ERROR_MSG);
1728 i = c->u->u_nfblocks - 1;
1729 switch (c->u->u_fblock[i].fb_type) {
1730 case LOOP:
1731 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1732 break;
1733 case EXCEPT:
1734 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001735 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1736 /* Prevent continue anywhere under a finally
1737 even if hidden in a sub-try or except. */
1738 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1739 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1740 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001741 if (i == -1)
1742 return compiler_error(c, LOOP_ERROR_MSG);
1743 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1744 break;
1745 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001746 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747 }
1748
1749 return 1;
1750}
1751
1752/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1753
1754 SETUP_FINALLY L
1755 <code for body>
1756 POP_BLOCK
1757 LOAD_CONST <None>
1758 L: <code for finalbody>
1759 END_FINALLY
1760
1761 The special instructions use the block stack. Each block
1762 stack entry contains the instruction that created it (here
1763 SETUP_FINALLY), the level of the value stack at the time the
1764 block stack entry was created, and a label (here L).
1765
1766 SETUP_FINALLY:
1767 Pushes the current value stack level and the label
1768 onto the block stack.
1769 POP_BLOCK:
1770 Pops en entry from the block stack, and pops the value
1771 stack until its level is the same as indicated on the
1772 block stack. (The label is ignored.)
1773 END_FINALLY:
1774 Pops a variable number of entries from the *value* stack
1775 and re-raises the exception they specify. The number of
1776 entries popped depends on the (pseudo) exception type.
1777
1778 The block stack is unwound when an exception is raised:
1779 when a SETUP_FINALLY entry is found, the exception is pushed
1780 onto the value stack (and the exception condition is cleared),
1781 and the interpreter jumps to the label gotten from the block
1782 stack.
1783*/
1784
1785static int
1786compiler_try_finally(struct compiler *c, stmt_ty s)
1787{
1788 basicblock *body, *end;
1789 body = compiler_new_block(c);
1790 end = compiler_new_block(c);
1791 if (body == NULL || end == NULL)
1792 return 0;
1793
1794 ADDOP_JREL(c, SETUP_FINALLY, end);
1795 compiler_use_next_block(c, body);
1796 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1797 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001798 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 ADDOP(c, POP_BLOCK);
1800 compiler_pop_fblock(c, FINALLY_TRY, body);
1801
1802 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1803 compiler_use_next_block(c, end);
1804 if (!compiler_push_fblock(c, FINALLY_END, end))
1805 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001806 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 ADDOP(c, END_FINALLY);
1808 compiler_pop_fblock(c, FINALLY_END, end);
1809
1810 return 1;
1811}
1812
1813/*
1814 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1815 (The contents of the value stack is shown in [], with the top
1816 at the right; 'tb' is trace-back info, 'val' the exception's
1817 associated value, and 'exc' the exception.)
1818
1819 Value stack Label Instruction Argument
1820 [] SETUP_EXCEPT L1
1821 [] <code for S>
1822 [] POP_BLOCK
1823 [] JUMP_FORWARD L0
1824
1825 [tb, val, exc] L1: DUP )
1826 [tb, val, exc, exc] <evaluate E1> )
1827 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001828 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 [tb, val, exc] POP
1830 [tb, val] <assign to V1> (or POP if no V1)
1831 [tb] POP
1832 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001833 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001835 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 .............................etc.......................
1837
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001838 [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839
1840 [] L0: <next statement>
1841
1842 Of course, parts are not generated if Vi or Ei is not present.
1843*/
1844static int
1845compiler_try_except(struct compiler *c, stmt_ty s)
1846{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001847 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848 int i, n;
1849
1850 body = compiler_new_block(c);
1851 except = compiler_new_block(c);
1852 orelse = compiler_new_block(c);
1853 end = compiler_new_block(c);
1854 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1855 return 0;
1856 ADDOP_JREL(c, SETUP_EXCEPT, except);
1857 compiler_use_next_block(c, body);
1858 if (!compiler_push_fblock(c, EXCEPT, body))
1859 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001860 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 ADDOP(c, POP_BLOCK);
1862 compiler_pop_fblock(c, EXCEPT, body);
1863 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1864 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1865 compiler_use_next_block(c, except);
1866 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001867 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868 s->v.TryExcept.handlers, i);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001869 if (!handler->v.ExceptHandler.type && i < n-1)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc6fd03bb2008-02-04 21:45:05 +00001871 c->u->u_lineno_set = false;
1872 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873 except = compiler_new_block(c);
1874 if (except == NULL)
1875 return 0;
Georg Brandla48f3ab2008-03-30 06:40:17 +00001876 if (handler->v.ExceptHandler.type) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877 ADDOP(c, DUP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001878 VISIT(c, expr, handler->v.ExceptHandler.type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00001880 ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 }
1882 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001883 if (handler->v.ExceptHandler.name) {
1884 VISIT(c, expr, handler->v.ExceptHandler.name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885 }
1886 else {
1887 ADDOP(c, POP_TOP);
1888 }
1889 ADDOP(c, POP_TOP);
Georg Brandla48f3ab2008-03-30 06:40:17 +00001890 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891 ADDOP_JREL(c, JUMP_FORWARD, end);
1892 compiler_use_next_block(c, except);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893 }
1894 ADDOP(c, END_FINALLY);
1895 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001896 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897 compiler_use_next_block(c, end);
1898 return 1;
1899}
1900
1901static int
1902compiler_import_as(struct compiler *c, identifier name, identifier asname)
1903{
1904 /* The IMPORT_NAME opcode was already generated. This function
1905 merely needs to bind the result to a name.
1906
1907 If there is a dot in name, we need to split it and emit a
1908 LOAD_ATTR for each name.
1909 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001910 const char *src = PyString_AS_STRING(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911 const char *dot = strchr(src, '.');
1912 if (dot) {
1913 /* Consume the base module name to get the first attribute */
1914 src = dot + 1;
1915 while (dot) {
1916 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001917 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 dot = strchr(src, '.');
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001919 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001921 if (!attr)
1922 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001924 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925 src = dot + 1;
1926 }
1927 }
1928 return compiler_nameop(c, asname, Store);
1929}
1930
1931static int
1932compiler_import(struct compiler *c, stmt_ty s)
1933{
1934 /* The Import node stores a module name like a.b.c as a single
1935 string. This is convenient for all cases except
1936 import a.b.c as d
1937 where we need to parse that string to extract the individual
1938 module names.
1939 XXX Perhaps change the representation to make this case simpler?
1940 */
1941 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001944 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001946 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947
Neal Norwitzcbce2802006-04-03 06:26:32 +00001948 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001949 level = PyInt_FromLong(0);
1950 else
1951 level = PyInt_FromLong(-1);
1952
1953 if (level == NULL)
1954 return 0;
1955
1956 ADDOP_O(c, LOAD_CONST, level, consts);
1957 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1959 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1960
1961 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001962 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001963 if (!r)
1964 return r;
1965 }
1966 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 identifier tmp = alias->name;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001968 const char *base = PyString_AS_STRING(alias->name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 char *dot = strchr(base, '.');
1970 if (dot)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001971 tmp = PyString_FromStringAndSize(base,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972 dot - base);
1973 r = compiler_nameop(c, tmp, Store);
1974 if (dot) {
1975 Py_DECREF(tmp);
1976 }
1977 if (!r)
1978 return r;
1979 }
1980 }
1981 return 1;
1982}
1983
1984static int
1985compiler_from_import(struct compiler *c, stmt_ty s)
1986{
1987 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988
1989 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001990 PyObject *level;
1991
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 if (!names)
1993 return 0;
1994
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001995 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001996 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001997 level = PyInt_FromLong(-1);
1998 else
1999 level = PyInt_FromLong(s->v.ImportFrom.level);
2000
2001 if (!level) {
2002 Py_DECREF(names);
2003 return 0;
2004 }
2005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006 /* build up the names */
2007 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002008 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 Py_INCREF(alias->name);
2010 PyTuple_SET_ITEM(names, i, alias->name);
2011 }
2012
2013 if (s->lineno > c->c_future->ff_lineno) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002014 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002016 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 Py_DECREF(names);
2018 return compiler_error(c,
2019 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002020 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021
2022 }
2023 }
2024
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002025 ADDOP_O(c, LOAD_CONST, level, consts);
2026 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002028 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2030 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002031 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032 identifier store_name;
2033
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002034 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 assert(n == 1);
2036 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002037 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 }
2039
2040 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2041 store_name = alias->name;
2042 if (alias->asname)
2043 store_name = alias->asname;
2044
2045 if (!compiler_nameop(c, store_name, Store)) {
2046 Py_DECREF(names);
2047 return 0;
2048 }
2049 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002050 /* remove imported module */
2051 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 return 1;
2053}
2054
2055static int
2056compiler_assert(struct compiler *c, stmt_ty s)
2057{
2058 static PyObject *assertion_error = NULL;
2059 basicblock *end;
2060
2061 if (Py_OptimizeFlag)
2062 return 1;
2063 if (assertion_error == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002064 assertion_error = PyString_InternFromString("AssertionError");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 if (assertion_error == NULL)
2066 return 0;
2067 }
Neal Norwitz400aeda2008-03-15 22:03:18 +00002068 if (s->v.Assert.test->kind == Tuple_kind &&
2069 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
2070 const char* msg =
2071 "assertion is always true, perhaps remove parentheses?";
2072 if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
2073 c->u->u_lineno, NULL, NULL) == -1)
2074 return 0;
2075 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 VISIT(c, expr, s->v.Assert.test);
2077 end = compiler_new_block(c);
2078 if (end == NULL)
2079 return 0;
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002080 ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2082 if (s->v.Assert.msg) {
2083 VISIT(c, expr, s->v.Assert.msg);
2084 ADDOP_I(c, RAISE_VARARGS, 2);
2085 }
2086 else {
2087 ADDOP_I(c, RAISE_VARARGS, 1);
2088 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002089 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 return 1;
2091}
2092
2093static int
2094compiler_visit_stmt(struct compiler *c, stmt_ty s)
2095{
2096 int i, n;
2097
Neal Norwitzf733a012006-10-29 18:30:10 +00002098 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 c->u->u_lineno = s->lineno;
2100 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002101
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 if (c->u->u_ste->ste_type != FunctionBlock)
2109 return compiler_error(c, "'return' outside function");
2110 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 VISIT(c, expr, s->v.Return.value);
2112 }
2113 else
2114 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2115 ADDOP(c, RETURN_VALUE);
2116 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002117 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002118 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002120 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 n = asdl_seq_LEN(s->v.Assign.targets);
2122 VISIT(c, expr, s->v.Assign.value);
2123 for (i = 0; i < n; i++) {
2124 if (i < n - 1)
2125 ADDOP(c, DUP_TOP);
2126 VISIT(c, expr,
2127 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2128 }
2129 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002136 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002138 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141 n = 0;
2142 if (s->v.Raise.type) {
2143 VISIT(c, expr, s->v.Raise.type);
2144 n++;
2145 if (s->v.Raise.inst) {
2146 VISIT(c, expr, s->v.Raise.inst);
2147 n++;
2148 if (s->v.Raise.tback) {
2149 VISIT(c, expr, s->v.Raise.tback);
2150 n++;
2151 }
2152 }
2153 }
2154 ADDOP_I(c, RAISE_VARARGS, n);
2155 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002156 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002157 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002158 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002159 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002160 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002162 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002164 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002166 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002167 VISIT(c, expr, s->v.Exec.body);
2168 if (s->v.Exec.globals) {
2169 VISIT(c, expr, s->v.Exec.globals);
2170 if (s->v.Exec.locals) {
2171 VISIT(c, expr, s->v.Exec.locals);
2172 } else {
2173 ADDOP(c, DUP_TOP);
2174 }
2175 } else {
2176 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2177 ADDOP(c, DUP_TOP);
2178 }
2179 ADDOP(c, EXEC_STMT);
2180 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002183 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002184 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002185 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 ADDOP(c, PRINT_EXPR);
2187 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002188 else if (s->v.Expr.value->kind != Str_kind &&
2189 s->v.Expr.value->kind != Num_kind) {
2190 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002191 ADDOP(c, POP_TOP);
2192 }
2193 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002196 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002197 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198 return compiler_error(c, "'break' outside loop");
2199 ADDOP(c, BREAK_LOOP);
2200 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002201 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002202 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002203 case With_kind:
2204 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205 }
2206 return 1;
2207}
2208
2209static int
2210unaryop(unaryop_ty op)
2211{
2212 switch (op) {
2213 case Invert:
2214 return UNARY_INVERT;
2215 case Not:
2216 return UNARY_NOT;
2217 case UAdd:
2218 return UNARY_POSITIVE;
2219 case USub:
2220 return UNARY_NEGATIVE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002221 default:
2222 PyErr_Format(PyExc_SystemError,
2223 "unary op %d should not be possible", op);
2224 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226}
2227
2228static int
2229binop(struct compiler *c, operator_ty op)
2230{
2231 switch (op) {
2232 case Add:
2233 return BINARY_ADD;
2234 case Sub:
2235 return BINARY_SUBTRACT;
2236 case Mult:
2237 return BINARY_MULTIPLY;
2238 case Div:
2239 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2240 return BINARY_TRUE_DIVIDE;
2241 else
2242 return BINARY_DIVIDE;
2243 case Mod:
2244 return BINARY_MODULO;
2245 case Pow:
2246 return BINARY_POWER;
2247 case LShift:
2248 return BINARY_LSHIFT;
2249 case RShift:
2250 return BINARY_RSHIFT;
2251 case BitOr:
2252 return BINARY_OR;
2253 case BitXor:
2254 return BINARY_XOR;
2255 case BitAnd:
2256 return BINARY_AND;
2257 case FloorDiv:
2258 return BINARY_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002259 default:
2260 PyErr_Format(PyExc_SystemError,
2261 "binary op %d should not be possible", op);
2262 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264}
2265
2266static int
2267cmpop(cmpop_ty op)
2268{
2269 switch (op) {
2270 case Eq:
2271 return PyCmp_EQ;
2272 case NotEq:
2273 return PyCmp_NE;
2274 case Lt:
2275 return PyCmp_LT;
2276 case LtE:
2277 return PyCmp_LE;
2278 case Gt:
2279 return PyCmp_GT;
2280 case GtE:
2281 return PyCmp_GE;
2282 case Is:
2283 return PyCmp_IS;
2284 case IsNot:
2285 return PyCmp_IS_NOT;
2286 case In:
2287 return PyCmp_IN;
2288 case NotIn:
2289 return PyCmp_NOT_IN;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002290 default:
2291 return PyCmp_BAD;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293}
2294
2295static int
2296inplace_binop(struct compiler *c, operator_ty op)
2297{
2298 switch (op) {
2299 case Add:
2300 return INPLACE_ADD;
2301 case Sub:
2302 return INPLACE_SUBTRACT;
2303 case Mult:
2304 return INPLACE_MULTIPLY;
2305 case Div:
2306 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2307 return INPLACE_TRUE_DIVIDE;
2308 else
2309 return INPLACE_DIVIDE;
2310 case Mod:
2311 return INPLACE_MODULO;
2312 case Pow:
2313 return INPLACE_POWER;
2314 case LShift:
2315 return INPLACE_LSHIFT;
2316 case RShift:
2317 return INPLACE_RSHIFT;
2318 case BitOr:
2319 return INPLACE_OR;
2320 case BitXor:
2321 return INPLACE_XOR;
2322 case BitAnd:
2323 return INPLACE_AND;
2324 case FloorDiv:
2325 return INPLACE_FLOOR_DIVIDE;
Georg Brandlfc8eef32008-03-28 12:11:56 +00002326 default:
2327 PyErr_Format(PyExc_SystemError,
2328 "inplace binary op %d should not be possible", op);
2329 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331}
2332
2333static int
2334compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2335{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002336 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2338
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002339 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002340 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 /* XXX AugStore isn't used anywhere! */
2342
Neal Norwitz0031ff32008-02-25 01:45:37 +00002343 mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002344 if (!mangled)
2345 return 0;
2346
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347 op = 0;
2348 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002349 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350 switch (scope) {
2351 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002352 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353 optype = OP_DEREF;
2354 break;
2355 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002356 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 optype = OP_DEREF;
2358 break;
2359 case LOCAL:
2360 if (c->u->u_ste->ste_type == FunctionBlock)
2361 optype = OP_FAST;
2362 break;
2363 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002364 if (c->u->u_ste->ste_type == FunctionBlock &&
2365 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366 optype = OP_GLOBAL;
2367 break;
2368 case GLOBAL_EXPLICIT:
2369 optype = OP_GLOBAL;
2370 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002371 default:
2372 /* scope can be 0 */
2373 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374 }
2375
2376 /* XXX Leave assert here, but handle __doc__ and the like better */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002377 assert(scope || PyString_AS_STRING(name)[0] == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378
2379 switch (optype) {
2380 case OP_DEREF:
2381 switch (ctx) {
2382 case Load: op = LOAD_DEREF; break;
2383 case Store: op = STORE_DEREF; break;
2384 case AugLoad:
2385 case AugStore:
2386 break;
2387 case Del:
2388 PyErr_Format(PyExc_SyntaxError,
2389 "can not delete variable '%s' referenced "
2390 "in nested scope",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002391 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002392 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002395 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002396 PyErr_SetString(PyExc_SystemError,
2397 "param invalid for deref variable");
2398 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 }
2400 break;
2401 case OP_FAST:
2402 switch (ctx) {
2403 case Load: op = LOAD_FAST; break;
2404 case Store: op = STORE_FAST; break;
2405 case Del: op = DELETE_FAST; break;
2406 case AugLoad:
2407 case AugStore:
2408 break;
2409 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002410 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002411 PyErr_SetString(PyExc_SystemError,
2412 "param invalid for local variable");
2413 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002414 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002415 ADDOP_O(c, op, mangled, varnames);
2416 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 return 1;
2418 case OP_GLOBAL:
2419 switch (ctx) {
2420 case Load: op = LOAD_GLOBAL; break;
2421 case Store: op = STORE_GLOBAL; break;
2422 case Del: op = DELETE_GLOBAL; break;
2423 case AugLoad:
2424 case AugStore:
2425 break;
2426 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002427 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002428 PyErr_SetString(PyExc_SystemError,
2429 "param invalid for global variable");
2430 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431 }
2432 break;
2433 case OP_NAME:
2434 switch (ctx) {
2435 case Load: op = LOAD_NAME; break;
2436 case Store: op = STORE_NAME; break;
2437 case Del: op = DELETE_NAME; break;
2438 case AugLoad:
2439 case AugStore:
2440 break;
2441 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002442 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002443 PyErr_SetString(PyExc_SystemError,
2444 "param invalid for name variable");
2445 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 }
2447 break;
2448 }
2449
2450 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002451 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002452 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002453 if (arg < 0)
2454 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002455 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456}
2457
2458static int
2459compiler_boolop(struct compiler *c, expr_ty e)
2460{
2461 basicblock *end;
2462 int jumpi, i, n;
2463 asdl_seq *s;
2464
2465 assert(e->kind == BoolOp_kind);
2466 if (e->v.BoolOp.op == And)
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002467 jumpi = JUMP_IF_FALSE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 else
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002469 jumpi = JUMP_IF_TRUE_OR_POP;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002471 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 return 0;
2473 s = e->v.BoolOp.values;
2474 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002475 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002477 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002478 ADDOP_JABS(c, jumpi, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002480 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 compiler_use_next_block(c, end);
2482 return 1;
2483}
2484
2485static int
2486compiler_list(struct compiler *c, expr_ty e)
2487{
2488 int n = asdl_seq_LEN(e->v.List.elts);
2489 if (e->v.List.ctx == Store) {
2490 ADDOP_I(c, UNPACK_SEQUENCE, n);
2491 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002492 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 if (e->v.List.ctx == Load) {
2494 ADDOP_I(c, BUILD_LIST, n);
2495 }
2496 return 1;
2497}
2498
2499static int
2500compiler_tuple(struct compiler *c, expr_ty e)
2501{
2502 int n = asdl_seq_LEN(e->v.Tuple.elts);
2503 if (e->v.Tuple.ctx == Store) {
2504 ADDOP_I(c, UNPACK_SEQUENCE, n);
2505 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002506 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507 if (e->v.Tuple.ctx == Load) {
2508 ADDOP_I(c, BUILD_TUPLE, n);
2509 }
2510 return 1;
2511}
2512
2513static int
2514compiler_compare(struct compiler *c, expr_ty e)
2515{
2516 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002517 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518
2519 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2520 VISIT(c, expr, e->v.Compare.left);
2521 n = asdl_seq_LEN(e->v.Compare.ops);
2522 assert(n > 0);
2523 if (n > 1) {
2524 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002525 if (cleanup == NULL)
2526 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002527 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002528 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 }
2530 for (i = 1; i < n; i++) {
2531 ADDOP(c, DUP_TOP);
2532 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002534 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002535 e->v.Compare.ops, i - 1))));
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002536 ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002539 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002540 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002542 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002544 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 if (n > 1) {
2546 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002547 if (end == NULL)
2548 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549 ADDOP_JREL(c, JUMP_FORWARD, end);
2550 compiler_use_next_block(c, cleanup);
2551 ADDOP(c, ROT_TWO);
2552 ADDOP(c, POP_TOP);
2553 compiler_use_next_block(c, end);
2554 }
2555 return 1;
2556}
2557
2558static int
2559compiler_call(struct compiler *c, expr_ty e)
2560{
2561 int n, code = 0;
2562
2563 VISIT(c, expr, e->v.Call.func);
2564 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002565 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002567 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2569 }
2570 if (e->v.Call.starargs) {
2571 VISIT(c, expr, e->v.Call.starargs);
2572 code |= 1;
2573 }
2574 if (e->v.Call.kwargs) {
2575 VISIT(c, expr, e->v.Call.kwargs);
2576 code |= 2;
2577 }
2578 switch (code) {
2579 case 0:
2580 ADDOP_I(c, CALL_FUNCTION, n);
2581 break;
2582 case 1:
2583 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2584 break;
2585 case 2:
2586 ADDOP_I(c, CALL_FUNCTION_KW, n);
2587 break;
2588 case 3:
2589 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2590 break;
2591 }
2592 return 1;
2593}
2594
2595static int
Antoine Pitroud0c35152008-12-17 00:38:28 +00002596compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
2597 int gen_index, expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598{
2599 /* generate code for the iterator, then each of the ifs,
2600 and then write to the element */
2601
2602 comprehension_ty l;
2603 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002604 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605
2606 start = compiler_new_block(c);
2607 skip = compiler_new_block(c);
2608 if_cleanup = compiler_new_block(c);
2609 anchor = compiler_new_block(c);
2610
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2612 anchor == NULL)
2613 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614
Anthony Baxter7b782b62006-04-11 12:01:56 +00002615 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 VISIT(c, expr, l->iter);
2617 ADDOP(c, GET_ITER);
2618 compiler_use_next_block(c, start);
2619 ADDOP_JREL(c, FOR_ITER, anchor);
2620 NEXT_BLOCK(c);
2621 VISIT(c, expr, l->target);
2622
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002623 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624 n = asdl_seq_LEN(l->ifs);
2625 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002626 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002628 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 }
2631
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 if (++gen_index < asdl_seq_LEN(generators))
Antoine Pitroud0c35152008-12-17 00:38:28 +00002633 if (!compiler_listcomp_generator(c, generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 /* only append after the last for generator */
2637 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002638 VISIT(c, expr, elt);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002639 ADDOP_I(c, LIST_APPEND, gen_index+1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002640
2641 compiler_use_next_block(c, skip);
2642 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002643 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2645 compiler_use_next_block(c, anchor);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646
2647 return 1;
2648}
2649
2650static int
2651compiler_listcomp(struct compiler *c, expr_ty e)
2652{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 assert(e->kind == ListComp_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 ADDOP_I(c, BUILD_LIST, 0);
Antoine Pitroud0c35152008-12-17 00:38:28 +00002655 return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
2656 e->v.ListComp.elt);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657}
2658
2659static int
2660compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 asdl_seq *generators, int gen_index,
2662 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663{
2664 /* generate code for the iterator, then each of the ifs,
2665 and then write to the element */
2666
2667 comprehension_ty ge;
2668 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
2671 start = compiler_new_block(c);
2672 skip = compiler_new_block(c);
2673 if_cleanup = compiler_new_block(c);
2674 anchor = compiler_new_block(c);
2675 end = compiler_new_block(c);
2676
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 anchor == NULL || end == NULL)
2679 return 0;
2680
Anthony Baxter7b782b62006-04-11 12:01:56 +00002681 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 ADDOP_JREL(c, SETUP_LOOP, end);
2683 if (!compiler_push_fblock(c, LOOP, start))
2684 return 0;
2685
2686 if (gen_index == 0) {
2687 /* Receive outermost iter as an implicit argument */
2688 c->u->u_argcount = 1;
2689 ADDOP_I(c, LOAD_FAST, 0);
2690 }
2691 else {
2692 /* Sub-iter - calculate on the fly */
2693 VISIT(c, expr, ge->iter);
2694 ADDOP(c, GET_ITER);
2695 }
2696 compiler_use_next_block(c, start);
2697 ADDOP_JREL(c, FOR_ITER, anchor);
2698 NEXT_BLOCK(c);
2699 VISIT(c, expr, ge->target);
2700
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002701 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 n = asdl_seq_LEN(ge->ifs);
2703 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002704 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 VISIT(c, expr, e);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002706 ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 NEXT_BLOCK(c);
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002708 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2712 return 0;
2713
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002714 /* only append after the last 'for' generator */
2715 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 VISIT(c, expr, elt);
2717 ADDOP(c, YIELD_VALUE);
2718 ADDOP(c, POP_TOP);
2719
2720 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721 }
Jeffrey Yasskin68d68522009-02-28 19:03:21 +00002722 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2724 compiler_use_next_block(c, anchor);
2725 ADDOP(c, POP_BLOCK);
2726 compiler_pop_fblock(c, LOOP, start);
2727 compiler_use_next_block(c, end);
2728
2729 return 1;
2730}
2731
2732static int
2733compiler_genexp(struct compiler *c, expr_ty e)
2734{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002735 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736 PyCodeObject *co;
2737 expr_ty outermost_iter = ((comprehension_ty)
2738 (asdl_seq_GET(e->v.GeneratorExp.generators,
2739 0)))->iter;
2740
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002741 if (!name) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002742 name = PyString_FromString("<genexpr>");
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002743 if (!name)
2744 return 0;
2745 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746
2747 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2748 return 0;
2749 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2750 e->v.GeneratorExp.elt);
2751 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002752 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 if (co == NULL)
2754 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002757 Py_DECREF(co);
2758
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759 VISIT(c, expr, outermost_iter);
2760 ADDOP(c, GET_ITER);
2761 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762
2763 return 1;
2764}
2765
2766static int
2767compiler_visit_keyword(struct compiler *c, keyword_ty k)
2768{
2769 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2770 VISIT(c, expr, k->value);
2771 return 1;
2772}
2773
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002774/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775 whether they are true or false.
2776
2777 Return values: 1 for true, 0 for false, -1 for non-constant.
2778 */
2779
2780static int
2781expr_constant(expr_ty e)
2782{
2783 switch (e->kind) {
2784 case Num_kind:
2785 return PyObject_IsTrue(e->v.Num.n);
2786 case Str_kind:
2787 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002788 case Name_kind:
2789 /* __debug__ is not assignable, so we can optimize
2790 * it away in if and while statements */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002791 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002792 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002793 return ! Py_OptimizeFlag;
2794 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 default:
2796 return -1;
2797 }
2798}
2799
Guido van Rossumc2e20742006-02-27 22:32:47 +00002800/*
2801 Implements the with statement from PEP 343.
2802
2803 The semantics outlined in that PEP are as follows:
2804
2805 with EXPR as VAR:
2806 BLOCK
2807
2808 It is implemented roughly as:
2809
Guido van Rossumda5b7012006-05-02 19:47:52 +00002810 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002811 exit = context.__exit__ # not calling it
2812 value = context.__enter__()
2813 try:
2814 VAR = value # if VAR present in the syntax
2815 BLOCK
2816 finally:
2817 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002818 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821 exit(*exc)
2822 */
2823static int
2824compiler_with(struct compiler *c, stmt_ty s)
2825{
Guido van Rossumc2e20742006-02-27 22:32:47 +00002826 basicblock *block, *finally;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002827
2828 assert(s->kind == With_kind);
2829
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 block = compiler_new_block(c);
2831 finally = compiler_new_block(c);
2832 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834
Guido van Rossumda5b7012006-05-02 19:47:52 +00002835 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 VISIT(c, expr, s->v.With.context_expr);
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002837 ADDOP_JREL(c, SETUP_WITH, finally);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002839 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002840 compiler_use_next_block(c, block);
2841 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002843 }
2844
2845 if (s->v.With.optional_vars) {
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00002846 VISIT(c, expr, s->v.With.optional_vars);
2847 }
2848 else {
2849 /* Discard result from context.__enter__() */
2850 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851 }
2852
2853 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002854 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002855
2856 /* End of try block; start the finally block */
2857 ADDOP(c, POP_BLOCK);
2858 compiler_pop_fblock(c, FINALLY_TRY, block);
2859
2860 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2861 compiler_use_next_block(c, finally);
2862 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002864
Nick Coghlan7af53be2008-03-07 14:13:28 +00002865 /* Finally block starts; context.__exit__ is on the stack under
2866 the exception or return information. Just issue our magic
2867 opcode. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869
2870 /* Finally block ends. */
2871 ADDOP(c, END_FINALLY);
2872 compiler_pop_fblock(c, FINALLY_END, finally);
2873 return 1;
2874}
2875
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876static int
2877compiler_visit_expr(struct compiler *c, expr_ty e)
2878{
2879 int i, n;
2880
Neal Norwitzf733a012006-10-29 18:30:10 +00002881 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002882 set a new line number for the next instruction.
2883 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 if (e->lineno > c->u->u_lineno) {
2885 c->u->u_lineno = e->lineno;
2886 c->u->u_lineno_set = false;
2887 }
2888 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002889 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002891 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892 VISIT(c, expr, e->v.BinOp.left);
2893 VISIT(c, expr, e->v.BinOp.right);
2894 ADDOP(c, binop(c, e->v.BinOp.op));
2895 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 VISIT(c, expr, e->v.UnaryOp.operand);
2898 ADDOP(c, unaryop(e->v.UnaryOp.op));
2899 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002902 case IfExp_kind:
2903 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002904 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettinger70fcfd02007-12-19 22:14:34 +00002906 ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002908 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002909 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002910 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002911 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002912 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002913 }
2914 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002915 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002917 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 return compiler_genexp(c, e);
2919 case Yield_kind:
2920 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002921 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 if (e->v.Yield.value) {
2923 VISIT(c, expr, e->v.Yield.value);
2924 }
2925 else {
2926 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2927 }
2928 ADDOP(c, YIELD_VALUE);
2929 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002932 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002934 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 VISIT(c, expr, e->v.Repr.value);
2936 ADDOP(c, UNARY_CONVERT);
2937 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002938 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2940 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002941 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2943 break;
2944 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002945 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946 if (e->v.Attribute.ctx != AugStore)
2947 VISIT(c, expr, e->v.Attribute.value);
2948 switch (e->v.Attribute.ctx) {
2949 case AugLoad:
2950 ADDOP(c, DUP_TOP);
2951 /* Fall through to load */
2952 case Load:
2953 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2954 break;
2955 case AugStore:
2956 ADDOP(c, ROT_TWO);
2957 /* Fall through to save */
2958 case Store:
2959 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2960 break;
2961 case Del:
2962 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2963 break;
2964 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002965 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002966 PyErr_SetString(PyExc_SystemError,
2967 "param invalid in attribute expression");
2968 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 }
2970 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002971 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972 switch (e->v.Subscript.ctx) {
2973 case AugLoad:
2974 VISIT(c, expr, e->v.Subscript.value);
2975 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2976 break;
2977 case Load:
2978 VISIT(c, expr, e->v.Subscript.value);
2979 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2980 break;
2981 case AugStore:
2982 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2983 break;
2984 case Store:
2985 VISIT(c, expr, e->v.Subscript.value);
2986 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2987 break;
2988 case Del:
2989 VISIT(c, expr, e->v.Subscript.value);
2990 VISIT_SLICE(c, e->v.Subscript.slice, Del);
2991 break;
2992 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002993 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002994 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002995 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00002996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 }
2998 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002999 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003000 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3001 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003002 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 return compiler_tuple(c, e);
3006 }
3007 return 1;
3008}
3009
3010static int
3011compiler_augassign(struct compiler *c, stmt_ty s)
3012{
3013 expr_ty e = s->v.AugAssign.target;
3014 expr_ty auge;
3015
3016 assert(s->kind == AugAssign_kind);
3017
3018 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003019 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003021 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003022 if (auge == NULL)
3023 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 VISIT(c, expr, auge);
3025 VISIT(c, expr, s->v.AugAssign.value);
3026 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3027 auge->v.Attribute.ctx = AugStore;
3028 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 break;
3030 case Subscript_kind:
3031 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003032 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003033 if (auge == NULL)
3034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 VISIT(c, expr, auge);
3036 VISIT(c, expr, s->v.AugAssign.value);
3037 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003038 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003040 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003042 if (!compiler_nameop(c, e->v.Name.id, Load))
3043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 VISIT(c, expr, s->v.AugAssign.value);
3045 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3046 return compiler_nameop(c, e->v.Name.id, Store);
3047 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003048 PyErr_Format(PyExc_SystemError,
3049 "invalid node type (%d) for augmented assignment",
3050 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 }
3053 return 1;
3054}
3055
3056static int
3057compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3058{
3059 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003060 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3061 PyErr_SetString(PyExc_SystemError,
3062 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003064 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065 f = &c->u->u_fblock[c->u->u_nfblocks++];
3066 f->fb_type = t;
3067 f->fb_block = b;
3068 return 1;
3069}
3070
3071static void
3072compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3073{
3074 struct compiler_unit *u = c->u;
3075 assert(u->u_nfblocks > 0);
3076 u->u_nfblocks--;
3077 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3078 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3079}
3080
Jeremy Hylton82271f12006-10-04 02:24:52 +00003081static int
3082compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003083 int i;
3084 struct compiler_unit *u = c->u;
3085 for (i = 0; i < u->u_nfblocks; ++i) {
3086 if (u->u_fblock[i].fb_type == LOOP)
3087 return 1;
3088 }
3089 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003090}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091/* Raises a SyntaxError and returns 0.
3092 If something goes wrong, a different exception may be raised.
3093*/
3094
3095static int
3096compiler_error(struct compiler *c, const char *errstr)
3097{
3098 PyObject *loc;
3099 PyObject *u = NULL, *v = NULL;
3100
3101 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3102 if (!loc) {
3103 Py_INCREF(Py_None);
3104 loc = Py_None;
3105 }
3106 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3107 Py_None, loc);
3108 if (!u)
3109 goto exit;
3110 v = Py_BuildValue("(zO)", errstr, u);
3111 if (!v)
3112 goto exit;
3113 PyErr_SetObject(PyExc_SyntaxError, v);
3114 exit:
3115 Py_DECREF(loc);
3116 Py_XDECREF(u);
3117 Py_XDECREF(v);
3118 return 0;
3119}
3120
3121static int
3122compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003124{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003125 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003127 /* XXX this code is duplicated */
3128 switch (ctx) {
3129 case AugLoad: /* fall through to Load */
3130 case Load: op = BINARY_SUBSCR; break;
3131 case AugStore:/* fall through to Store */
3132 case Store: op = STORE_SUBSCR; break;
3133 case Del: op = DELETE_SUBSCR; break;
3134 case Param:
3135 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003136 "invalid %s kind %d in subscript\n",
3137 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 return 0;
3139 }
3140 if (ctx == AugLoad) {
3141 ADDOP_I(c, DUP_TOPX, 2);
3142 }
3143 else if (ctx == AugStore) {
3144 ADDOP(c, ROT_THREE);
3145 }
3146 ADDOP(c, op);
3147 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148}
3149
3150static int
3151compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3152{
3153 int n = 2;
3154 assert(s->kind == Slice_kind);
3155
3156 /* only handles the cases where BUILD_SLICE is emitted */
3157 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 }
3160 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166 }
3167 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003168 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 }
3170
3171 if (s->v.Slice.step) {
3172 n++;
3173 VISIT(c, expr, s->v.Slice.step);
3174 }
3175 ADDOP_I(c, BUILD_SLICE, n);
3176 return 1;
3177}
3178
3179static int
3180compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3181{
3182 int op = 0, slice_offset = 0, stack_count = 0;
3183
3184 assert(s->v.Slice.step == NULL);
3185 if (s->v.Slice.lower) {
3186 slice_offset++;
3187 stack_count++;
3188 if (ctx != AugStore)
3189 VISIT(c, expr, s->v.Slice.lower);
3190 }
3191 if (s->v.Slice.upper) {
3192 slice_offset += 2;
3193 stack_count++;
3194 if (ctx != AugStore)
3195 VISIT(c, expr, s->v.Slice.upper);
3196 }
3197
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 if (ctx == AugLoad) {
3199 switch (stack_count) {
3200 case 0: ADDOP(c, DUP_TOP); break;
3201 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3202 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3203 }
3204 }
3205 else if (ctx == AugStore) {
3206 switch (stack_count) {
3207 case 0: ADDOP(c, ROT_TWO); break;
3208 case 1: ADDOP(c, ROT_THREE); break;
3209 case 2: ADDOP(c, ROT_FOUR); break;
3210 }
3211 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
3213 switch (ctx) {
3214 case AugLoad: /* fall through to Load */
3215 case Load: op = SLICE; break;
3216 case AugStore:/* fall through to Store */
3217 case Store: op = STORE_SLICE; break;
3218 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003219 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003220 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003221 PyErr_SetString(PyExc_SystemError,
3222 "param invalid in simple slice");
3223 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 }
3225
3226 ADDOP(c, op + slice_offset);
3227 return 1;
3228}
3229
3230static int
3231compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3232 expr_context_ty ctx)
3233{
3234 switch (s->kind) {
3235 case Ellipsis_kind:
3236 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3237 break;
3238 case Slice_kind:
3239 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 case Index_kind:
3241 VISIT(c, expr, s->v.Index.value);
3242 break;
3243 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003244 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003245 PyErr_SetString(PyExc_SystemError,
3246 "extended slice invalid in nested slice");
3247 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248 }
3249 return 1;
3250}
3251
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252static int
3253compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3254{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003255 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003257 case Index_kind:
3258 kindname = "index";
3259 if (ctx != AugStore) {
3260 VISIT(c, expr, s->v.Index.value);
3261 }
3262 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003264 kindname = "ellipsis";
3265 if (ctx != AugStore) {
3266 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 break;
3269 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003270 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271 if (!s->v.Slice.step)
3272 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003273 if (ctx != AugStore) {
3274 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 return 0;
3276 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003277 break;
3278 case ExtSlice_kind:
3279 kindname = "extended slice";
3280 if (ctx != AugStore) {
3281 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3282 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003283 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003284 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003285 if (!compiler_visit_nested_slice(c, sub, ctx))
3286 return 0;
3287 }
3288 ADDOP_I(c, BUILD_TUPLE, n);
3289 }
3290 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003291 default:
3292 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003293 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003294 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003296 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297}
3298
Neal Norwitzf733a012006-10-29 18:30:10 +00003299
3300/* End of the compiler section, beginning of the assembler section */
3301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302/* do depth-first search of basic block graph, starting with block.
3303 post records the block indices in post-order.
3304
3305 XXX must handle implicit jumps from one block to next
3306*/
3307
Neal Norwitzf733a012006-10-29 18:30:10 +00003308struct assembler {
3309 PyObject *a_bytecode; /* string containing bytecode */
3310 int a_offset; /* offset into bytecode */
3311 int a_nblocks; /* number of reachable blocks */
3312 basicblock **a_postorder; /* list of blocks in dfs postorder */
3313 PyObject *a_lnotab; /* string containing lnotab */
3314 int a_lnotab_off; /* offset into lnotab */
3315 int a_lineno; /* last lineno of emitted instruction */
3316 int a_lineno_off; /* bytecode offset of last lineno */
3317};
3318
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319static void
3320dfs(struct compiler *c, basicblock *b, struct assembler *a)
3321{
3322 int i;
3323 struct instr *instr = NULL;
3324
3325 if (b->b_seen)
3326 return;
3327 b->b_seen = 1;
3328 if (b->b_next != NULL)
3329 dfs(c, b->b_next, a);
3330 for (i = 0; i < b->b_iused; i++) {
3331 instr = &b->b_instr[i];
3332 if (instr->i_jrel || instr->i_jabs)
3333 dfs(c, instr->i_target, a);
3334 }
3335 a->a_postorder[a->a_nblocks++] = b;
3336}
3337
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003338static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3340{
3341 int i;
3342 struct instr *instr;
3343 if (b->b_seen || b->b_startdepth >= depth)
3344 return maxdepth;
3345 b->b_seen = 1;
3346 b->b_startdepth = depth;
3347 for (i = 0; i < b->b_iused; i++) {
3348 instr = &b->b_instr[i];
3349 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3350 if (depth > maxdepth)
3351 maxdepth = depth;
3352 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3353 if (instr->i_jrel || instr->i_jabs) {
3354 maxdepth = stackdepth_walk(c, instr->i_target,
3355 depth, maxdepth);
3356 if (instr->i_opcode == JUMP_ABSOLUTE ||
3357 instr->i_opcode == JUMP_FORWARD) {
3358 goto out; /* remaining code is dead */
3359 }
3360 }
3361 }
3362 if (b->b_next)
3363 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3364out:
3365 b->b_seen = 0;
3366 return maxdepth;
3367}
3368
3369/* Find the flow path that needs the largest stack. We assume that
3370 * cycles in the flow graph have no net effect on the stack depth.
3371 */
3372static int
3373stackdepth(struct compiler *c)
3374{
3375 basicblock *b, *entryblock;
3376 entryblock = NULL;
3377 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3378 b->b_seen = 0;
3379 b->b_startdepth = INT_MIN;
3380 entryblock = b;
3381 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003382 if (!entryblock)
3383 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 return stackdepth_walk(c, entryblock, 0, 0);
3385}
3386
3387static int
3388assemble_init(struct assembler *a, int nblocks, int firstlineno)
3389{
3390 memset(a, 0, sizeof(struct assembler));
3391 a->a_lineno = firstlineno;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003392 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 if (!a->a_bytecode)
3394 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003395 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 if (!a->a_lnotab)
3397 return 0;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003398 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
3399 PyErr_NoMemory();
3400 return 0;
3401 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003402 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003403 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003404 if (!a->a_postorder) {
3405 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003406 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003407 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408 return 1;
3409}
3410
3411static void
3412assemble_free(struct assembler *a)
3413{
3414 Py_XDECREF(a->a_bytecode);
3415 Py_XDECREF(a->a_lnotab);
3416 if (a->a_postorder)
3417 PyObject_Free(a->a_postorder);
3418}
3419
3420/* Return the size of a basic block in bytes. */
3421
3422static int
3423instrsize(struct instr *instr)
3424{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003425 if (!instr->i_hasarg)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003426 return 1; /* 1 byte for the opcode*/
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003427 if (instr->i_oparg > 0xffff)
Raymond Hettingerdff1fd92007-12-20 01:25:05 +00003428 return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
3429 return 3; /* 1 (opcode) + 2 (oparg) */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430}
3431
3432static int
3433blocksize(basicblock *b)
3434{
3435 int i;
3436 int size = 0;
3437
3438 for (i = 0; i < b->b_iused; i++)
3439 size += instrsize(&b->b_instr[i]);
3440 return size;
3441}
3442
Jeffrey Yasskin655d8352009-05-23 23:23:01 +00003443/* Appends a pair to the end of the line number table, a_lnotab, representing
3444 the instruction's bytecode offset and line number. See
3445 Objects/lnotab_notes.txt for the description of the line number table. */
Tim Peters2a7f3842001-06-09 09:26:21 +00003446
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003447static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003448assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003449{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450 int d_bytecode, d_lineno;
3451 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003452 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453
3454 d_bytecode = a->a_offset - a->a_lineno_off;
3455 d_lineno = i->i_lineno - a->a_lineno;
3456
3457 assert(d_bytecode >= 0);
3458 assert(d_lineno >= 0);
3459
Amaury Forgeot d'Arc99af7db2008-02-05 00:26:21 +00003460 if(d_bytecode == 0 && d_lineno == 0)
3461 return 1;
3462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003463 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003464 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003465 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003466 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003468 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003470 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003471 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003472 else {
3473 PyErr_NoMemory();
3474 return 0;
3475 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003476 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003478 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003479 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003480 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003481 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482 *lnotab++ = 255;
3483 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003484 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485 d_bytecode -= ncodes * 255;
3486 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003487 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488 assert(d_bytecode <= 255);
3489 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003490 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491 nbytes = a->a_lnotab_off + 2 * ncodes;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003492 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493 if (nbytes >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003494 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495 len = nbytes;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003496 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 len *= 2;
Gregory P. Smith9d534572008-06-11 07:41:16 +00003498 else {
3499 PyErr_NoMemory();
3500 return 0;
3501 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003502 if (_PyString_Resize(&a->a_lnotab, len) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003504 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003505 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003506 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003508 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003510 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003512 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 d_lineno -= ncodes * 255;
3515 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003516 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003517
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003518 len = PyString_GET_SIZE(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519 if (a->a_lnotab_off + 2 >= len) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003520 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003521 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003522 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003523 lnotab = (unsigned char *)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003524 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003525
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 a->a_lnotab_off += 2;
3527 if (d_bytecode) {
3528 *lnotab++ = d_bytecode;
3529 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003530 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003531 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 *lnotab++ = 0;
3533 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 a->a_lineno = i->i_lineno;
3536 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003537 return 1;
3538}
3539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540/* assemble_emit()
3541 Extend the bytecode with a new instruction.
3542 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003543*/
3544
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003545static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003547{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003548 int size, arg = 0, ext = 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003549 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 char *code;
3551
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003552 size = instrsize(i);
3553 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003555 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559 if (a->a_offset + size >= len) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00003560 if (len > PY_SSIZE_T_MAX / 2)
3561 return 0;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003562 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003563 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003564 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003565 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003567 if (size == 6) {
3568 assert(i->i_hasarg);
3569 *code++ = (char)EXTENDED_ARG;
3570 *code++ = ext & 0xff;
3571 *code++ = ext >> 8;
3572 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003575 if (i->i_hasarg) {
3576 assert(size == 3 || size == 6);
3577 *code++ = arg & 0xff;
3578 *code++ = arg >> 8;
3579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003581}
3582
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003583static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003585{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003587 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003588 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003589
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 /* Compute the size of each block and fixup jump args.
3591 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003592start:
3593 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003595 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 bsize = blocksize(b);
3597 b->b_offset = totsize;
3598 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003599 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003600 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3602 bsize = b->b_offset;
3603 for (i = 0; i < b->b_iused; i++) {
3604 struct instr *instr = &b->b_instr[i];
3605 /* Relative jumps are computed relative to
3606 the instruction pointer after fetching
3607 the jump instruction.
3608 */
3609 bsize += instrsize(instr);
3610 if (instr->i_jabs)
3611 instr->i_oparg = instr->i_target->b_offset;
3612 else if (instr->i_jrel) {
3613 int delta = instr->i_target->b_offset - bsize;
3614 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003615 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003616 else
3617 continue;
3618 if (instr->i_oparg > 0xffff)
3619 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003620 }
3621 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003622
3623 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003624 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003625 with a better solution.
3626
3627 In the meantime, should the goto be dropped in favor
3628 of a loop?
3629
3630 The issue is that in the first loop blocksize() is called
3631 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003632 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003633 i_oparg is calculated in the second loop above.
3634
3635 So we loop until we stop seeing new EXTENDED_ARGs.
3636 The only EXTENDED_ARGs that could be popping up are
3637 ones in jump instructions. So this should converge
3638 fairly quickly.
3639 */
3640 if (last_extended_arg_count != extended_arg_count) {
3641 last_extended_arg_count = extended_arg_count;
3642 goto start;
3643 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003644}
3645
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003646static PyObject *
3647dict_keys_inorder(PyObject *dict, int offset)
3648{
3649 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003650 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003651
3652 tuple = PyTuple_New(size);
3653 if (tuple == NULL)
3654 return NULL;
3655 while (PyDict_Next(dict, &pos, &k, &v)) {
3656 i = PyInt_AS_LONG(v);
Benjamin Petersonda9327f2009-01-31 23:43:25 +00003657 /* The keys of the dictionary are tuples. (see compiler_add_o)
3658 The object we want is always first, though. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003659 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003660 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003661 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003662 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003663 PyTuple_SET_ITEM(tuple, i - offset, k);
3664 }
3665 return tuple;
3666}
3667
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003668static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003670{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 PySTEntryObject *ste = c->u->u_ste;
3672 int flags = 0, n;
3673 if (ste->ste_type != ModuleBlock)
3674 flags |= CO_NEWLOCALS;
3675 if (ste->ste_type == FunctionBlock) {
3676 if (!ste->ste_unoptimized)
3677 flags |= CO_OPTIMIZED;
3678 if (ste->ste_nested)
3679 flags |= CO_NESTED;
3680 if (ste->ste_generator)
3681 flags |= CO_GENERATOR;
Benjamin Peterson12554cb2009-01-31 23:54:38 +00003682 if (ste->ste_varargs)
3683 flags |= CO_VARARGS;
3684 if (ste->ste_varkeywords)
3685 flags |= CO_VARKEYWORDS;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003686 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003687
3688 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003689 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003690
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691 n = PyDict_Size(c->u->u_freevars);
3692 if (n < 0)
3693 return -1;
3694 if (n == 0) {
3695 n = PyDict_Size(c->u->u_cellvars);
3696 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003697 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698 if (n == 0) {
3699 flags |= CO_NOFREE;
3700 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003701 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003702
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003703 return flags;
3704}
3705
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003706static PyCodeObject *
3707makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003708{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709 PyObject *tmp;
3710 PyCodeObject *co = NULL;
3711 PyObject *consts = NULL;
3712 PyObject *names = NULL;
3713 PyObject *varnames = NULL;
3714 PyObject *filename = NULL;
3715 PyObject *name = NULL;
3716 PyObject *freevars = NULL;
3717 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003718 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 tmp = dict_keys_inorder(c->u->u_consts, 0);
3722 if (!tmp)
3723 goto error;
3724 consts = PySequence_List(tmp); /* optimize_code requires a list */
3725 Py_DECREF(tmp);
3726
3727 names = dict_keys_inorder(c->u->u_names, 0);
3728 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3729 if (!consts || !names || !varnames)
3730 goto error;
3731
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003732 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3733 if (!cellvars)
3734 goto error;
3735 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3736 if (!freevars)
3737 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003738 filename = PyString_FromString(c->c_filename);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 if (!filename)
3740 goto error;
3741
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 flags = compute_code_flags(c);
3744 if (flags < 0)
3745 goto error;
3746
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003747 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 if (!bytecode)
3749 goto error;
3750
3751 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3752 if (!tmp)
3753 goto error;
3754 Py_DECREF(consts);
3755 consts = tmp;
3756
3757 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3758 bytecode, consts, names, varnames,
3759 freevars, cellvars,
3760 filename, c->u->u_name,
3761 c->u->u_firstlineno,
3762 a->a_lnotab);
3763 error:
3764 Py_XDECREF(consts);
3765 Py_XDECREF(names);
3766 Py_XDECREF(varnames);
3767 Py_XDECREF(filename);
3768 Py_XDECREF(name);
3769 Py_XDECREF(freevars);
3770 Py_XDECREF(cellvars);
3771 Py_XDECREF(bytecode);
3772 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003773}
3774
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003775
3776/* For debugging purposes only */
3777#if 0
3778static void
3779dump_instr(const struct instr *i)
3780{
3781 const char *jrel = i->i_jrel ? "jrel " : "";
3782 const char *jabs = i->i_jabs ? "jabs " : "";
3783 char arg[128];
3784
3785 *arg = '\0';
3786 if (i->i_hasarg)
3787 sprintf(arg, "arg: %d ", i->i_oparg);
3788
3789 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3790 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3791}
3792
3793static void
3794dump_basicblock(const basicblock *b)
3795{
3796 const char *seen = b->b_seen ? "seen " : "";
3797 const char *b_return = b->b_return ? "return " : "";
3798 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3799 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3800 if (b->b_instr) {
3801 int i;
3802 for (i = 0; i < b->b_iused; i++) {
3803 fprintf(stderr, " [%02d] ", i);
3804 dump_instr(b->b_instr + i);
3805 }
3806 }
3807}
3808#endif
3809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810static PyCodeObject *
3811assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003812{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813 basicblock *b, *entryblock;
3814 struct assembler a;
3815 int i, j, nblocks;
3816 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 /* Make sure every block that falls off the end returns None.
3819 XXX NEXT_BLOCK() isn't quite right, because if the last
3820 block ends with a jump or return b_next shouldn't set.
3821 */
3822 if (!c->u->u_curblock->b_return) {
3823 NEXT_BLOCK(c);
3824 if (addNone)
3825 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3826 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003827 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003828
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 nblocks = 0;
3830 entryblock = NULL;
3831 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3832 nblocks++;
3833 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003834 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003835
Neal Norwitzed657552006-07-10 00:04:44 +00003836 /* Set firstlineno if it wasn't explicitly set. */
3837 if (!c->u->u_firstlineno) {
3838 if (entryblock && entryblock->b_instr)
3839 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3840 else
3841 c->u->u_firstlineno = 1;
3842 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3844 goto error;
3845 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003846
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003848 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 /* Emit code in reverse postorder from dfs. */
3851 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003852 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 for (j = 0; j < b->b_iused; j++)
3854 if (!assemble_emit(&a, &b->b_instr[j]))
3855 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003856 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003857
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003858 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 goto error;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003860 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003862
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003863 co = makecode(c, &a);
3864 error:
3865 assemble_free(&a);
3866 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003867}