blob: 01dbb1aaa3ac84dc9bee4924bd88e4a41f393124 [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. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000187 const char *p, *name = PyString_AsString(ident);
188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
191 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 }
Anthony Baxter7b782b62006-04-11 12:01:56 +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);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
220 if (!ident)
221 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 buffer = PyString_AS_STRING(ident);
224 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 strncpy(buffer+1, p, plen);
226 strcpy(buffer+1+plen, name);
227 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000228}
229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230static int
231compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000232{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 c->c_stack = PyList_New(0);
236 if (!c->c_stack)
237 return 0;
238
239 return 1;
240}
241
242PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000243PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000244 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245{
246 struct compiler c;
247 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyCompilerFlags local_flags;
249 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 if (!__doc__) {
252 __doc__ = PyString_InternFromString("__doc__");
253 if (!__doc__)
254 return NULL;
255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
257 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000258 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000260 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261 c.c_future = PyFuture_FromAST(mod, filename);
262 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000263 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000265 local_flags.cf_flags = 0;
266 flags = &local_flags;
267 }
268 merged = c.c_future->ff_features | flags->cf_flags;
269 c.c_future->ff_features = merged;
270 flags->cf_flags = merged;
271 c.c_flags = flags;
272 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 c.c_st = PySymtable_Build(mod, filename, c.c_future);
275 if (c.c_st == NULL) {
276 if (!PyErr_Occurred())
277 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000278 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 }
280
281 /* XXX initialize to NULL for now, need to handle */
282 c.c_encoding = NULL;
283
284 co = compiler_mod(&c, mod);
285
Thomas Wouters1175c432006-02-27 22:49:54 +0000286 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000288 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 return co;
290}
291
292PyCodeObject *
293PyNode_Compile(struct _node *n, const char *filename)
294{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000295 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000296 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000297 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000298 if (!arena)
299 return NULL;
300 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 if (mod)
302 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000304 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000305}
306
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000307static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000309{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310 if (c->c_st)
311 PySymtable_Free(c->c_st);
312 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000313 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315}
316
Guido van Rossum79f25d91997-04-29 20:08:16 +0000317static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000321 PyObject *v, *k;
322 PyObject *dict = PyDict_New();
323 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 n = PyList_Size(list);
326 for (i = 0; i < n; i++) {
327 v = PyInt_FromLong(i);
328 if (!v) {
329 Py_DECREF(dict);
330 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000331 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000332 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000333 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
335 Py_XDECREF(k);
336 Py_DECREF(v);
337 Py_DECREF(dict);
338 return NULL;
339 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000340 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 return dict;
344}
345
346/* Return new dict containing names from src that match scope(s).
347
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000348src is a symbol table dictionary. If the scope of a name matches
349either scope_type or flag is set, insert it into the new dict. The
350values are integers, starting at offset and increasing by one for
351each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352*/
353
354static PyObject *
355dictbytype(PyObject *src, int scope_type, int flag, int offset)
356{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000357 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 PyObject *k, *v, *dest = PyDict_New();
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 assert(offset >= 0);
361 if (dest == NULL)
362 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
364 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365 /* XXX this should probably be a macro in symtable.h */
366 assert(PyInt_Check(v));
367 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
370 PyObject *tuple, *item = PyInt_FromLong(i);
371 if (item == NULL) {
372 Py_DECREF(dest);
373 return NULL;
374 }
375 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000376 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
378 Py_DECREF(item);
379 Py_DECREF(dest);
380 Py_XDECREF(tuple);
381 return NULL;
382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 }
387 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000388}
389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390static void
391compiler_unit_check(struct compiler_unit *u)
392{
393 basicblock *block;
394 for (block = u->u_blocks; block != NULL; block = block->b_list) {
395 assert(block != (void *)0xcbcbcbcb);
396 assert(block != (void *)0xfbfbfbfb);
397 assert(block != (void *)0xdbdbdbdb);
398 if (block->b_instr != NULL) {
399 assert(block->b_ialloc > 0);
400 assert(block->b_iused > 0);
401 assert(block->b_ialloc >= block->b_iused);
402 }
403 else {
404 assert (block->b_iused == 0);
405 assert (block->b_ialloc == 0);
406 }
407 }
408}
409
410static void
411compiler_unit_free(struct compiler_unit *u)
412{
413 basicblock *b, *next;
414
415 compiler_unit_check(u);
416 b = u->u_blocks;
417 while (b != NULL) {
418 if (b->b_instr)
419 PyObject_Free((void *)b->b_instr);
420 next = b->b_list;
421 PyObject_Free((void *)b);
422 b = next;
423 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000424 Py_CLEAR(u->u_ste);
425 Py_CLEAR(u->u_name);
426 Py_CLEAR(u->u_consts);
427 Py_CLEAR(u->u_names);
428 Py_CLEAR(u->u_varnames);
429 Py_CLEAR(u->u_freevars);
430 Py_CLEAR(u->u_cellvars);
431 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000432 PyObject_Free(u);
433}
434
435static int
436compiler_enter_scope(struct compiler *c, identifier name, void *key,
437 int lineno)
438{
439 struct compiler_unit *u;
440
Anthony Baxter7b782b62006-04-11 12:01:56 +0000441 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000442 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000443 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444 PyErr_NoMemory();
445 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000446 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000447 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448 u->u_argcount = 0;
449 u->u_ste = PySymtable_Lookup(c->c_st, key);
450 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 compiler_unit_free(u);
452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453 }
454 Py_INCREF(name);
455 u->u_name = name;
456 u->u_varnames = list2dict(u->u_ste->ste_varnames);
457 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000458 if (!u->u_varnames || !u->u_cellvars) {
459 compiler_unit_free(u);
460 return 0;
461 }
462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000465 if (!u->u_freevars) {
466 compiler_unit_free(u);
467 return 0;
468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
470 u->u_blocks = NULL;
471 u->u_tmpname = 0;
472 u->u_nfblocks = 0;
473 u->u_firstlineno = lineno;
474 u->u_lineno = 0;
475 u->u_lineno_set = false;
476 u->u_consts = PyDict_New();
477 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479 return 0;
480 }
481 u->u_names = PyDict_New();
482 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000483 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484 return 0;
485 }
486
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488
489 /* Push the old compiler_unit on the stack. */
490 if (c->u) {
491 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000492 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
493 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496 }
497 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 u->u_private = c->u->u_private;
499 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500 }
501 c->u = u;
502
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000504 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505 return 0;
506
507 return 1;
508}
509
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000510static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511compiler_exit_scope(struct compiler *c)
512{
513 int n;
514 PyObject *wrapper;
515
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 compiler_unit_free(c->u);
518 /* Restore c->u to the parent unit. */
519 n = PyList_GET_SIZE(c->c_stack) - 1;
520 if (n >= 0) {
521 wrapper = PyList_GET_ITEM(c->c_stack, n);
522 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000523 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 compiler_unit_check(c->u);
528 }
529 else
530 c->u = NULL;
531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532}
533
Guido van Rossumc2e20742006-02-27 22:32:47 +0000534/* Allocate a new "anonymous" local variable.
535 Used by list comprehensions and with statements.
536*/
537
538static PyObject *
539compiler_new_tmpname(struct compiler *c)
540{
541 char tmpname[256];
542 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
543 return PyString_FromString(tmpname);
544}
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546/* Allocate a new block and return a pointer to it.
547 Returns NULL on error.
548*/
549
550static basicblock *
551compiler_new_block(struct compiler *c)
552{
553 basicblock *b;
554 struct compiler_unit *u;
555
556 u = c->u;
557 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000558 if (b == NULL) {
559 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000563 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 b->b_list = u->u_blocks;
565 u->u_blocks = b;
566 return b;
567}
568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569static basicblock *
570compiler_use_new_block(struct compiler *c)
571{
572 basicblock *block = compiler_new_block(c);
573 if (block == NULL)
574 return NULL;
575 c->u->u_curblock = block;
576 return block;
577}
578
579static basicblock *
580compiler_next_block(struct compiler *c)
581{
582 basicblock *block = compiler_new_block(c);
583 if (block == NULL)
584 return NULL;
585 c->u->u_curblock->b_next = block;
586 c->u->u_curblock = block;
587 return block;
588}
589
590static basicblock *
591compiler_use_next_block(struct compiler *c, basicblock *block)
592{
593 assert(block != NULL);
594 c->u->u_curblock->b_next = block;
595 c->u->u_curblock = block;
596 return block;
597}
598
599/* Returns the offset of the next instruction in the current block's
600 b_instr array. Resizes the b_instr as necessary.
601 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000602*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603
604static int
605compiler_next_instr(struct compiler *c, basicblock *b)
606{
607 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000608 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000609 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000610 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 if (b->b_instr == NULL) {
612 PyErr_NoMemory();
613 return -1;
614 }
615 b->b_ialloc = DEFAULT_BLOCK_SIZE;
616 memset((char *)b->b_instr, 0,
617 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000620 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621 size_t oldsize, newsize;
622 oldsize = b->b_ialloc * sizeof(struct instr);
623 newsize = oldsize << 1;
624 if (newsize == 0) {
625 PyErr_NoMemory();
626 return -1;
627 }
628 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000629 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000630 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000631 if (tmp == NULL) {
632 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000634 }
635 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
637 }
638 return b->b_iused++;
639}
640
Jeremy Hylton12603c42006-04-01 16:18:02 +0000641/* Set the i_lineno member of the instruction at offse off if the
642 line number for the current expression/statement (?) has not
643 already been set. If it has been set, the call has no effect.
644
645 Every time a new node is b
Neal Norwitzf733a012006-10-29 18:30:10 +0000646*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648static void
649compiler_set_lineno(struct compiler *c, int off)
650{
651 basicblock *b;
652 if (c->u->u_lineno_set)
653 return;
654 c->u->u_lineno_set = true;
655 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
659static int
660opcode_stack_effect(int opcode, int oparg)
661{
662 switch (opcode) {
663 case POP_TOP:
664 return -1;
665 case ROT_TWO:
666 case ROT_THREE:
667 return 0;
668 case DUP_TOP:
669 return 1;
670 case ROT_FOUR:
671 return 0;
672
673 case UNARY_POSITIVE:
674 case UNARY_NEGATIVE:
675 case UNARY_NOT:
676 case UNARY_CONVERT:
677 case UNARY_INVERT:
678 return 0;
679
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000680 case LIST_APPEND:
681 return -2;
682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 case BINARY_POWER:
684 case BINARY_MULTIPLY:
685 case BINARY_DIVIDE:
686 case BINARY_MODULO:
687 case BINARY_ADD:
688 case BINARY_SUBTRACT:
689 case BINARY_SUBSCR:
690 case BINARY_FLOOR_DIVIDE:
691 case BINARY_TRUE_DIVIDE:
692 return -1;
693 case INPLACE_FLOOR_DIVIDE:
694 case INPLACE_TRUE_DIVIDE:
695 return -1;
696
697 case SLICE+0:
698 return 1;
699 case SLICE+1:
700 return 0;
701 case SLICE+2:
702 return 0;
703 case SLICE+3:
704 return -1;
705
706 case STORE_SLICE+0:
707 return -2;
708 case STORE_SLICE+1:
709 return -3;
710 case STORE_SLICE+2:
711 return -3;
712 case STORE_SLICE+3:
713 return -4;
714
715 case DELETE_SLICE+0:
716 return -1;
717 case DELETE_SLICE+1:
718 return -2;
719 case DELETE_SLICE+2:
720 return -2;
721 case DELETE_SLICE+3:
722 return -3;
723
724 case INPLACE_ADD:
725 case INPLACE_SUBTRACT:
726 case INPLACE_MULTIPLY:
727 case INPLACE_DIVIDE:
728 case INPLACE_MODULO:
729 return -1;
730 case STORE_SUBSCR:
731 return -3;
732 case DELETE_SUBSCR:
733 return -2;
734
735 case BINARY_LSHIFT:
736 case BINARY_RSHIFT:
737 case BINARY_AND:
738 case BINARY_XOR:
739 case BINARY_OR:
740 return -1;
741 case INPLACE_POWER:
742 return -1;
743 case GET_ITER:
744 return 0;
745
746 case PRINT_EXPR:
747 return -1;
748 case PRINT_ITEM:
749 return -1;
750 case PRINT_NEWLINE:
751 return 0;
752 case PRINT_ITEM_TO:
753 return -2;
754 case PRINT_NEWLINE_TO:
755 return -1;
756 case INPLACE_LSHIFT:
757 case INPLACE_RSHIFT:
758 case INPLACE_AND:
759 case INPLACE_XOR:
760 case INPLACE_OR:
761 return -1;
762 case BREAK_LOOP:
763 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000764 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000765 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case LOAD_LOCALS:
767 return 1;
768 case RETURN_VALUE:
769 return -1;
770 case IMPORT_STAR:
771 return -1;
772 case EXEC_STMT:
773 return -3;
774 case YIELD_VALUE:
775 return 0;
776
777 case POP_BLOCK:
778 return 0;
779 case END_FINALLY:
780 return -1; /* or -2 or -3 if exception occurred */
781 case BUILD_CLASS:
782 return -2;
783
784 case STORE_NAME:
785 return -1;
786 case DELETE_NAME:
787 return 0;
788 case UNPACK_SEQUENCE:
789 return oparg-1;
790 case FOR_ITER:
791 return 1;
792
793 case STORE_ATTR:
794 return -2;
795 case DELETE_ATTR:
796 return -1;
797 case STORE_GLOBAL:
798 return -1;
799 case DELETE_GLOBAL:
800 return 0;
801 case DUP_TOPX:
802 return oparg;
803 case LOAD_CONST:
804 return 1;
805 case LOAD_NAME:
806 return 1;
807 case BUILD_TUPLE:
808 case BUILD_LIST:
809 return 1-oparg;
810 case BUILD_MAP:
811 return 1;
812 case LOAD_ATTR:
813 return 0;
814 case COMPARE_OP:
815 return -1;
816 case IMPORT_NAME:
817 return 0;
818 case IMPORT_FROM:
819 return 1;
820
821 case JUMP_FORWARD:
822 case JUMP_IF_FALSE:
823 case JUMP_IF_TRUE:
824 case JUMP_ABSOLUTE:
825 return 0;
826
827 case LOAD_GLOBAL:
828 return 1;
829
830 case CONTINUE_LOOP:
831 return 0;
832 case SETUP_LOOP:
833 return 0;
834 case SETUP_EXCEPT:
835 case SETUP_FINALLY:
836 return 3; /* actually pushed by an exception */
837
838 case LOAD_FAST:
839 return 1;
840 case STORE_FAST:
841 return -1;
842 case DELETE_FAST:
843 return 0;
844
845 case RAISE_VARARGS:
846 return -oparg;
847#define NARGS(o) (((o) % 256) + 2*((o) / 256))
848 case CALL_FUNCTION:
849 return -NARGS(oparg);
850 case CALL_FUNCTION_VAR:
851 case CALL_FUNCTION_KW:
852 return -NARGS(oparg)-1;
853 case CALL_FUNCTION_VAR_KW:
854 return -NARGS(oparg)-2;
855#undef NARGS
856 case MAKE_FUNCTION:
857 return -oparg;
858 case BUILD_SLICE:
859 if (oparg == 3)
860 return -2;
861 else
862 return -1;
863
864 case MAKE_CLOSURE:
865 return -oparg;
866 case LOAD_CLOSURE:
867 return 1;
868 case LOAD_DEREF:
869 return 1;
870 case STORE_DEREF:
871 return -1;
872 default:
873 fprintf(stderr, "opcode = %d\n", opcode);
874 Py_FatalError("opcode_stack_effect()");
875
876 }
877 return 0; /* not reachable */
878}
879
880/* Add an opcode with no argument.
881 Returns 0 on failure, 1 on success.
882*/
883
884static int
885compiler_addop(struct compiler *c, int opcode)
886{
887 basicblock *b;
888 struct instr *i;
889 int off;
890 off = compiler_next_instr(c, c->u->u_curblock);
891 if (off < 0)
892 return 0;
893 b = c->u->u_curblock;
894 i = &b->b_instr[off];
895 i->i_opcode = opcode;
896 i->i_hasarg = 0;
897 if (opcode == RETURN_VALUE)
898 b->b_return = 1;
899 compiler_set_lineno(c, off);
900 return 1;
901}
902
903static int
904compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
905{
906 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000909 /* necessary to make sure types aren't coerced (e.g., int and long) */
910 t = PyTuple_Pack(2, o, o->ob_type);
911 if (t == NULL)
912 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000913
914 v = PyDict_GetItem(dict, t);
915 if (!v) {
916 arg = PyDict_Size(dict);
917 v = PyInt_FromLong(arg);
918 if (!v) {
919 Py_DECREF(t);
920 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000921 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000922 if (PyDict_SetItem(dict, t, v) < 0) {
923 Py_DECREF(t);
924 Py_DECREF(v);
925 return -1;
926 }
927 Py_DECREF(v);
928 }
929 else
930 arg = PyInt_AsLong(v);
931 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000932 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933}
934
935static int
936compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
937 PyObject *o)
938{
939 int arg = compiler_add_o(c, dict, o);
940 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942 return compiler_addop_i(c, opcode, arg);
943}
944
945static int
946compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000947 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948{
949 int arg;
950 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
951 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000952 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953 arg = compiler_add_o(c, dict, mangled);
954 Py_DECREF(mangled);
955 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000956 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957 return compiler_addop_i(c, opcode, arg);
958}
959
960/* Add an opcode with an integer argument.
961 Returns 0 on failure, 1 on success.
962*/
963
964static int
965compiler_addop_i(struct compiler *c, int opcode, int oparg)
966{
967 struct instr *i;
968 int off;
969 off = compiler_next_instr(c, c->u->u_curblock);
970 if (off < 0)
971 return 0;
972 i = &c->u->u_curblock->b_instr[off];
973 i->i_opcode = opcode;
974 i->i_oparg = oparg;
975 i->i_hasarg = 1;
976 compiler_set_lineno(c, off);
977 return 1;
978}
979
980static int
981compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
982{
983 struct instr *i;
984 int off;
985
986 assert(b != NULL);
987 off = compiler_next_instr(c, c->u->u_curblock);
988 if (off < 0)
989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990 i = &c->u->u_curblock->b_instr[off];
991 i->i_opcode = opcode;
992 i->i_target = b;
993 i->i_hasarg = 1;
994 if (absolute)
995 i->i_jabs = 1;
996 else
997 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +0000998 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 return 1;
1000}
1001
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1003 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004 it as the current block. NEXT_BLOCK() also creates an implicit jump
1005 from the current block to the new block.
1006*/
1007
Neal Norwitzf733a012006-10-29 18:30:10 +00001008/* The returns inside these macros make it impossible to decref objects
1009 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010*/
1011
1012
1013#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001014 if (compiler_use_new_block((C)) == NULL) \
1015 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016}
1017
1018#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001019 if (compiler_next_block((C)) == NULL) \
1020 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001021}
1022
1023#define ADDOP(C, OP) { \
1024 if (!compiler_addop((C), (OP))) \
1025 return 0; \
1026}
1027
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001028#define ADDOP_IN_SCOPE(C, OP) { \
1029 if (!compiler_addop((C), (OP))) { \
1030 compiler_exit_scope(c); \
1031 return 0; \
1032 } \
1033}
1034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035#define ADDOP_O(C, OP, O, TYPE) { \
1036 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1037 return 0; \
1038}
1039
1040#define ADDOP_NAME(C, OP, O, TYPE) { \
1041 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1042 return 0; \
1043}
1044
1045#define ADDOP_I(C, OP, O) { \
1046 if (!compiler_addop_i((C), (OP), (O))) \
1047 return 0; \
1048}
1049
1050#define ADDOP_JABS(C, OP, O) { \
1051 if (!compiler_addop_j((C), (OP), (O), 1)) \
1052 return 0; \
1053}
1054
1055#define ADDOP_JREL(C, OP, O) { \
1056 if (!compiler_addop_j((C), (OP), (O), 0)) \
1057 return 0; \
1058}
1059
1060/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1061 the ASDL name to synthesize the name of the C type and the visit function.
1062*/
1063
1064#define VISIT(C, TYPE, V) {\
1065 if (!compiler_visit_ ## TYPE((C), (V))) \
1066 return 0; \
1067}
1068
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001069#define VISIT_IN_SCOPE(C, TYPE, V) {\
1070 if (!compiler_visit_ ## TYPE((C), (V))) { \
1071 compiler_exit_scope(c); \
1072 return 0; \
1073 } \
1074}
1075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076#define VISIT_SLICE(C, V, CTX) {\
1077 if (!compiler_visit_slice((C), (V), (CTX))) \
1078 return 0; \
1079}
1080
1081#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001082 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001084 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001085 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001086 if (!compiler_visit_ ## TYPE((C), elt)) \
1087 return 0; \
1088 } \
1089}
1090
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001091#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001092 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001093 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001094 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001095 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001096 if (!compiler_visit_ ## TYPE((C), elt)) { \
1097 compiler_exit_scope(c); \
1098 return 0; \
1099 } \
1100 } \
1101}
1102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103static int
1104compiler_isdocstring(stmt_ty s)
1105{
1106 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001107 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108 return s->v.Expr.value->kind == Str_kind;
1109}
1110
1111/* Compile a sequence of statements, checking for a docstring. */
1112
1113static int
1114compiler_body(struct compiler *c, asdl_seq *stmts)
1115{
1116 int i = 0;
1117 stmt_ty st;
1118
1119 if (!asdl_seq_LEN(stmts))
1120 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001121 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001122 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1123 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 i = 1;
1125 VISIT(c, expr, st->v.Expr.value);
1126 if (!compiler_nameop(c, __doc__, Store))
1127 return 0;
1128 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001129 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001130 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 return 1;
1132}
1133
1134static PyCodeObject *
1135compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001136{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001137 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 static PyObject *module;
1140 if (!module) {
1141 module = PyString_FromString("<module>");
1142 if (!module)
1143 return NULL;
1144 }
Neal Norwitzed657552006-07-10 00:04:44 +00001145 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1146 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001147 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 switch (mod->kind) {
1149 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001150 if (!compiler_body(c, mod->v.Module.body)) {
1151 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001153 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 break;
1155 case Interactive_kind:
1156 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001157 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001158 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 break;
1160 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001161 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001162 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 break;
1164 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001165 PyErr_SetString(PyExc_SystemError,
1166 "suite should not be possible");
1167 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001168 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001169 PyErr_Format(PyExc_SystemError,
1170 "module kind %d should not be possible",
1171 mod->kind);
1172 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001173 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 co = assemble(c, addNone);
1175 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001176 return co;
1177}
1178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179/* The test for LOCAL must come before the test for FREE in order to
1180 handle classes where name is both local and free. The local var is
1181 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001182*/
1183
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184static int
1185get_ref_type(struct compiler *c, PyObject *name)
1186{
1187 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001188 if (scope == 0) {
1189 char buf[350];
1190 PyOS_snprintf(buf, sizeof(buf),
1191 "unknown scope for %.100s in %.100s(%s) in %s\n"
1192 "symbols: %s\nlocals: %s\nglobals: %s\n",
1193 PyString_AS_STRING(name),
1194 PyString_AS_STRING(c->u->u_name),
1195 PyObject_REPR(c->u->u_ste->ste_id),
1196 c->c_filename,
1197 PyObject_REPR(c->u->u_ste->ste_symbols),
1198 PyObject_REPR(c->u->u_varnames),
1199 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001201 Py_FatalError(buf);
1202 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001203
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001204 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205}
1206
1207static int
1208compiler_lookup_arg(PyObject *dict, PyObject *name)
1209{
1210 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001211 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001213 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001215 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001217 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 return PyInt_AS_LONG(v);
1219}
1220
1221static int
1222compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1223{
1224 int i, free = PyCode_GetNumFree(co);
1225 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1227 ADDOP_I(c, MAKE_FUNCTION, args);
1228 return 1;
1229 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230 for (i = 0; i < free; ++i) {
1231 /* Bypass com_addop_varname because it will generate
1232 LOAD_DEREF but LOAD_CLOSURE is needed.
1233 */
1234 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1235 int arg, reftype;
1236
1237 /* Special case: If a class contains a method with a
1238 free variable that has the same name as a method,
1239 the name will be considered free *and* local in the
1240 class. It should be handled by the closure, as
1241 well as by the normal name loookup logic.
1242 */
1243 reftype = get_ref_type(c, name);
1244 if (reftype == CELL)
1245 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1246 else /* (reftype == FREE) */
1247 arg = compiler_lookup_arg(c->u->u_freevars, name);
1248 if (arg == -1) {
1249 printf("lookup %s in %s %d %d\n"
1250 "freevars of %s: %s\n",
1251 PyObject_REPR(name),
1252 PyString_AS_STRING(c->u->u_name),
1253 reftype, arg,
1254 PyString_AS_STRING(co->co_name),
1255 PyObject_REPR(co->co_freevars));
1256 Py_FatalError("compiler_make_closure()");
1257 }
1258 ADDOP_I(c, LOAD_CLOSURE, arg);
1259 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 ADDOP_I(c, MAKE_CLOSURE, args);
1263 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264}
1265
1266static int
1267compiler_decorators(struct compiler *c, asdl_seq* decos)
1268{
1269 int i;
1270
1271 if (!decos)
1272 return 1;
1273
1274 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001275 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 }
1277 return 1;
1278}
1279
1280static int
1281compiler_arguments(struct compiler *c, arguments_ty args)
1282{
1283 int i;
1284 int n = asdl_seq_LEN(args->args);
1285 /* Correctly handle nested argument lists */
1286 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001287 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288 if (arg->kind == Tuple_kind) {
1289 PyObject *id = PyString_FromFormat(".%d", i);
1290 if (id == NULL) {
1291 return 0;
1292 }
1293 if (!compiler_nameop(c, id, Load)) {
1294 Py_DECREF(id);
1295 return 0;
1296 }
1297 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001298 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001299 }
1300 }
1301 return 1;
1302}
1303
1304static int
1305compiler_function(struct compiler *c, stmt_ty s)
1306{
1307 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001308 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309 arguments_ty args = s->v.FunctionDef.args;
1310 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001311 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 int i, n, docstring;
1313
1314 assert(s->kind == FunctionDef_kind);
1315
1316 if (!compiler_decorators(c, decos))
1317 return 0;
1318 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001319 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001320 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1321 s->lineno))
1322 return 0;
1323
Anthony Baxter7b782b62006-04-11 12:01:56 +00001324 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001325 docstring = compiler_isdocstring(st);
1326 if (docstring)
1327 first_const = st->v.Expr.value->v.Str.s;
1328 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001329 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001330 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001331 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001333 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 compiler_arguments(c, args);
1335
1336 c->u->u_argcount = asdl_seq_LEN(args->args);
1337 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001338 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001340 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1341 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001342 }
1343 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001344 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 if (co == NULL)
1346 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001348 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001349 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350
1351 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1352 ADDOP_I(c, CALL_FUNCTION, 1);
1353 }
1354
1355 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1356}
1357
1358static int
1359compiler_class(struct compiler *c, stmt_ty s)
1360{
1361 int n;
1362 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001363 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364 /* push class name on stack, needed by BUILD_CLASS */
1365 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1366 /* push the tuple of base classes on the stack */
1367 n = asdl_seq_LEN(s->v.ClassDef.bases);
1368 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001369 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 ADDOP_I(c, BUILD_TUPLE, n);
1371 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1372 s->lineno))
1373 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001374 c->u->u_private = s->v.ClassDef.name;
1375 Py_INCREF(c->u->u_private);
1376 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 if (!str || !compiler_nameop(c, str, Load)) {
1378 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001379 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001381 }
1382
1383 Py_DECREF(str);
1384 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 if (!str || !compiler_nameop(c, str, Store)) {
1386 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001387 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001389 }
1390 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001392 if (!compiler_body(c, s->v.ClassDef.body)) {
1393 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001397 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1398 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001400 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401 if (co == NULL)
1402 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001404 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001405 Py_DECREF(co);
1406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407 ADDOP_I(c, CALL_FUNCTION, 0);
1408 ADDOP(c, BUILD_CLASS);
1409 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1410 return 0;
1411 return 1;
1412}
1413
1414static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001415compiler_ifexp(struct compiler *c, expr_ty e)
1416{
1417 basicblock *end, *next;
1418
1419 assert(e->kind == IfExp_kind);
1420 end = compiler_new_block(c);
1421 if (end == NULL)
1422 return 0;
1423 next = compiler_new_block(c);
1424 if (next == NULL)
1425 return 0;
1426 VISIT(c, expr, e->v.IfExp.test);
1427 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1428 ADDOP(c, POP_TOP);
1429 VISIT(c, expr, e->v.IfExp.body);
1430 ADDOP_JREL(c, JUMP_FORWARD, end);
1431 compiler_use_next_block(c, next);
1432 ADDOP(c, POP_TOP);
1433 VISIT(c, expr, e->v.IfExp.orelse);
1434 compiler_use_next_block(c, end);
1435 return 1;
1436}
1437
1438static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439compiler_lambda(struct compiler *c, expr_ty e)
1440{
1441 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001442 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 arguments_ty args = e->v.Lambda.args;
1444 assert(e->kind == Lambda_kind);
1445
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001446 if (!name) {
1447 name = PyString_InternFromString("<lambda>");
1448 if (!name)
1449 return 0;
1450 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451
1452 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001453 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1455 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001456
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001457 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 compiler_arguments(c, args);
1459
1460 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001461 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1462 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001464 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 if (co == NULL)
1466 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001468 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001469 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470
1471 return 1;
1472}
1473
1474static int
1475compiler_print(struct compiler *c, stmt_ty s)
1476{
1477 int i, n;
1478 bool dest;
1479
1480 assert(s->kind == Print_kind);
1481 n = asdl_seq_LEN(s->v.Print.values);
1482 dest = false;
1483 if (s->v.Print.dest) {
1484 VISIT(c, expr, s->v.Print.dest);
1485 dest = true;
1486 }
1487 for (i = 0; i < n; i++) {
1488 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1489 if (dest) {
1490 ADDOP(c, DUP_TOP);
1491 VISIT(c, expr, e);
1492 ADDOP(c, ROT_TWO);
1493 ADDOP(c, PRINT_ITEM_TO);
1494 }
1495 else {
1496 VISIT(c, expr, e);
1497 ADDOP(c, PRINT_ITEM);
1498 }
1499 }
1500 if (s->v.Print.nl) {
1501 if (dest)
1502 ADDOP(c, PRINT_NEWLINE_TO)
1503 else
1504 ADDOP(c, PRINT_NEWLINE)
1505 }
1506 else if (dest)
1507 ADDOP(c, POP_TOP);
1508 return 1;
1509}
1510
1511static int
1512compiler_if(struct compiler *c, stmt_ty s)
1513{
1514 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001515 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516 assert(s->kind == If_kind);
1517 end = compiler_new_block(c);
1518 if (end == NULL)
1519 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001520 next = compiler_new_block(c);
1521 if (next == NULL)
1522 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001523
1524 constant = expr_constant(s->v.If.test);
1525 /* constant = 0: "if 0"
1526 * constant = 1: "if 1", "if 2", ...
1527 * constant = -1: rest */
1528 if (constant == 0) {
1529 if (s->v.If.orelse)
1530 VISIT_SEQ(c, stmt, s->v.If.orelse);
1531 } else if (constant == 1) {
1532 VISIT_SEQ(c, stmt, s->v.If.body);
1533 } else {
1534 VISIT(c, expr, s->v.If.test);
1535 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1536 ADDOP(c, POP_TOP);
1537 VISIT_SEQ(c, stmt, s->v.If.body);
1538 ADDOP_JREL(c, JUMP_FORWARD, end);
1539 compiler_use_next_block(c, next);
1540 ADDOP(c, POP_TOP);
1541 if (s->v.If.orelse)
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001542 VISIT_SEQ(c, stmt, s->v.If.orelse);
Georg Brandlddbaa662006-06-04 21:56:52 +00001543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544 compiler_use_next_block(c, end);
1545 return 1;
1546}
1547
1548static int
1549compiler_for(struct compiler *c, stmt_ty s)
1550{
1551 basicblock *start, *cleanup, *end;
1552
1553 start = compiler_new_block(c);
1554 cleanup = compiler_new_block(c);
1555 end = compiler_new_block(c);
1556 if (start == NULL || end == NULL || cleanup == NULL)
1557 return 0;
1558 ADDOP_JREL(c, SETUP_LOOP, end);
1559 if (!compiler_push_fblock(c, LOOP, start))
1560 return 0;
1561 VISIT(c, expr, s->v.For.iter);
1562 ADDOP(c, GET_ITER);
1563 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001564 /* XXX(nnorwitz): is there a better way to handle this?
1565 for loops are special, we want to be able to trace them
1566 each time around, so we need to set an extra line number. */
1567 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568 ADDOP_JREL(c, FOR_ITER, cleanup);
1569 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001570 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001571 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1572 compiler_use_next_block(c, cleanup);
1573 ADDOP(c, POP_BLOCK);
1574 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001575 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576 compiler_use_next_block(c, end);
1577 return 1;
1578}
1579
1580static int
1581compiler_while(struct compiler *c, stmt_ty s)
1582{
1583 basicblock *loop, *orelse, *end, *anchor = NULL;
1584 int constant = expr_constant(s->v.While.test);
1585
1586 if (constant == 0)
1587 return 1;
1588 loop = compiler_new_block(c);
1589 end = compiler_new_block(c);
1590 if (constant == -1) {
1591 anchor = compiler_new_block(c);
1592 if (anchor == NULL)
1593 return 0;
1594 }
1595 if (loop == NULL || end == NULL)
1596 return 0;
1597 if (s->v.While.orelse) {
1598 orelse = compiler_new_block(c);
1599 if (orelse == NULL)
1600 return 0;
1601 }
1602 else
1603 orelse = NULL;
1604
1605 ADDOP_JREL(c, SETUP_LOOP, end);
1606 compiler_use_next_block(c, loop);
1607 if (!compiler_push_fblock(c, LOOP, loop))
1608 return 0;
1609 if (constant == -1) {
1610 VISIT(c, expr, s->v.While.test);
1611 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1612 ADDOP(c, POP_TOP);
1613 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001614 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1616
1617 /* XXX should the two POP instructions be in a separate block
1618 if there is no else clause ?
1619 */
1620
1621 if (constant == -1) {
1622 compiler_use_next_block(c, anchor);
1623 ADDOP(c, POP_TOP);
1624 ADDOP(c, POP_BLOCK);
1625 }
1626 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001627 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001628 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629 compiler_use_next_block(c, end);
1630
1631 return 1;
1632}
1633
1634static int
1635compiler_continue(struct compiler *c)
1636{
1637 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001638 static const char IN_FINALLY_ERROR_MSG[] =
1639 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640 int i;
1641
1642 if (!c->u->u_nfblocks)
1643 return compiler_error(c, LOOP_ERROR_MSG);
1644 i = c->u->u_nfblocks - 1;
1645 switch (c->u->u_fblock[i].fb_type) {
1646 case LOOP:
1647 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1648 break;
1649 case EXCEPT:
1650 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001651 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1652 /* Prevent continue anywhere under a finally
1653 even if hidden in a sub-try or except. */
1654 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1655 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 if (i == -1)
1658 return compiler_error(c, LOOP_ERROR_MSG);
1659 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1660 break;
1661 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001662 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663 }
1664
1665 return 1;
1666}
1667
1668/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1669
1670 SETUP_FINALLY L
1671 <code for body>
1672 POP_BLOCK
1673 LOAD_CONST <None>
1674 L: <code for finalbody>
1675 END_FINALLY
1676
1677 The special instructions use the block stack. Each block
1678 stack entry contains the instruction that created it (here
1679 SETUP_FINALLY), the level of the value stack at the time the
1680 block stack entry was created, and a label (here L).
1681
1682 SETUP_FINALLY:
1683 Pushes the current value stack level and the label
1684 onto the block stack.
1685 POP_BLOCK:
1686 Pops en entry from the block stack, and pops the value
1687 stack until its level is the same as indicated on the
1688 block stack. (The label is ignored.)
1689 END_FINALLY:
1690 Pops a variable number of entries from the *value* stack
1691 and re-raises the exception they specify. The number of
1692 entries popped depends on the (pseudo) exception type.
1693
1694 The block stack is unwound when an exception is raised:
1695 when a SETUP_FINALLY entry is found, the exception is pushed
1696 onto the value stack (and the exception condition is cleared),
1697 and the interpreter jumps to the label gotten from the block
1698 stack.
1699*/
1700
1701static int
1702compiler_try_finally(struct compiler *c, stmt_ty s)
1703{
1704 basicblock *body, *end;
1705 body = compiler_new_block(c);
1706 end = compiler_new_block(c);
1707 if (body == NULL || end == NULL)
1708 return 0;
1709
1710 ADDOP_JREL(c, SETUP_FINALLY, end);
1711 compiler_use_next_block(c, body);
1712 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1713 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001714 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715 ADDOP(c, POP_BLOCK);
1716 compiler_pop_fblock(c, FINALLY_TRY, body);
1717
1718 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1719 compiler_use_next_block(c, end);
1720 if (!compiler_push_fblock(c, FINALLY_END, end))
1721 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001722 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723 ADDOP(c, END_FINALLY);
1724 compiler_pop_fblock(c, FINALLY_END, end);
1725
1726 return 1;
1727}
1728
1729/*
1730 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1731 (The contents of the value stack is shown in [], with the top
1732 at the right; 'tb' is trace-back info, 'val' the exception's
1733 associated value, and 'exc' the exception.)
1734
1735 Value stack Label Instruction Argument
1736 [] SETUP_EXCEPT L1
1737 [] <code for S>
1738 [] POP_BLOCK
1739 [] JUMP_FORWARD L0
1740
1741 [tb, val, exc] L1: DUP )
1742 [tb, val, exc, exc] <evaluate E1> )
1743 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1744 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1745 [tb, val, exc, 1] POP )
1746 [tb, val, exc] POP
1747 [tb, val] <assign to V1> (or POP if no V1)
1748 [tb] POP
1749 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001750 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751
1752 [tb, val, exc, 0] L2: POP
1753 [tb, val, exc] DUP
1754 .............................etc.......................
1755
1756 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001757 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758
1759 [] L0: <next statement>
1760
1761 Of course, parts are not generated if Vi or Ei is not present.
1762*/
1763static int
1764compiler_try_except(struct compiler *c, stmt_ty s)
1765{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001766 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001767 int i, n;
1768
1769 body = compiler_new_block(c);
1770 except = compiler_new_block(c);
1771 orelse = compiler_new_block(c);
1772 end = compiler_new_block(c);
1773 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1774 return 0;
1775 ADDOP_JREL(c, SETUP_EXCEPT, except);
1776 compiler_use_next_block(c, body);
1777 if (!compiler_push_fblock(c, EXCEPT, body))
1778 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001779 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 ADDOP(c, POP_BLOCK);
1781 compiler_pop_fblock(c, EXCEPT, body);
1782 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1783 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1784 compiler_use_next_block(c, except);
1785 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001786 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787 s->v.TryExcept.handlers, i);
1788 if (!handler->type && i < n-1)
1789 return compiler_error(c, "default 'except:' must be last");
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001790 c->u->u_lineno_set = false;
1791 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 except = compiler_new_block(c);
1793 if (except == NULL)
1794 return 0;
1795 if (handler->type) {
1796 ADDOP(c, DUP_TOP);
1797 VISIT(c, expr, handler->type);
1798 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1799 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1800 ADDOP(c, POP_TOP);
1801 }
1802 ADDOP(c, POP_TOP);
1803 if (handler->name) {
1804 VISIT(c, expr, handler->name);
1805 }
1806 else {
1807 ADDOP(c, POP_TOP);
1808 }
1809 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001810 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811 ADDOP_JREL(c, JUMP_FORWARD, end);
1812 compiler_use_next_block(c, except);
1813 if (handler->type)
1814 ADDOP(c, POP_TOP);
1815 }
1816 ADDOP(c, END_FINALLY);
1817 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001818 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 compiler_use_next_block(c, end);
1820 return 1;
1821}
1822
1823static int
1824compiler_import_as(struct compiler *c, identifier name, identifier asname)
1825{
1826 /* The IMPORT_NAME opcode was already generated. This function
1827 merely needs to bind the result to a name.
1828
1829 If there is a dot in name, we need to split it and emit a
1830 LOAD_ATTR for each name.
1831 */
1832 const char *src = PyString_AS_STRING(name);
1833 const char *dot = strchr(src, '.');
1834 if (dot) {
1835 /* Consume the base module name to get the first attribute */
1836 src = dot + 1;
1837 while (dot) {
1838 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001839 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001841 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001843 if (!attr)
1844 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001846 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 src = dot + 1;
1848 }
1849 }
1850 return compiler_nameop(c, asname, Store);
1851}
1852
1853static int
1854compiler_import(struct compiler *c, stmt_ty s)
1855{
1856 /* The Import node stores a module name like a.b.c as a single
1857 string. This is convenient for all cases except
1858 import a.b.c as d
1859 where we need to parse that string to extract the individual
1860 module names.
1861 XXX Perhaps change the representation to make this case simpler?
1862 */
1863 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001866 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001868 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
Neal Norwitzcbce2802006-04-03 06:26:32 +00001870 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001871 level = PyInt_FromLong(0);
1872 else
1873 level = PyInt_FromLong(-1);
1874
1875 if (level == NULL)
1876 return 0;
1877
1878 ADDOP_O(c, LOAD_CONST, level, consts);
1879 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1881 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1882
1883 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001884 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001885 if (!r)
1886 return r;
1887 }
1888 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 identifier tmp = alias->name;
1890 const char *base = PyString_AS_STRING(alias->name);
1891 char *dot = strchr(base, '.');
1892 if (dot)
1893 tmp = PyString_FromStringAndSize(base,
1894 dot - base);
1895 r = compiler_nameop(c, tmp, Store);
1896 if (dot) {
1897 Py_DECREF(tmp);
1898 }
1899 if (!r)
1900 return r;
1901 }
1902 }
1903 return 1;
1904}
1905
1906static int
1907compiler_from_import(struct compiler *c, stmt_ty s)
1908{
1909 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
1911 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001912 PyObject *level;
1913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 if (!names)
1915 return 0;
1916
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001917 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001918 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001919 level = PyInt_FromLong(-1);
1920 else
1921 level = PyInt_FromLong(s->v.ImportFrom.level);
1922
1923 if (!level) {
1924 Py_DECREF(names);
1925 return 0;
1926 }
1927
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928 /* build up the names */
1929 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001930 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 Py_INCREF(alias->name);
1932 PyTuple_SET_ITEM(names, i, alias->name);
1933 }
1934
1935 if (s->lineno > c->c_future->ff_lineno) {
1936 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1937 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001938 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 Py_DECREF(names);
1940 return compiler_error(c,
1941 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001942 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
1944 }
1945 }
1946
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001947 ADDOP_O(c, LOAD_CONST, level, consts);
1948 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001950 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1952 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001953 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954 identifier store_name;
1955
1956 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1957 assert(n == 1);
1958 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001959 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 }
1961
1962 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1963 store_name = alias->name;
1964 if (alias->asname)
1965 store_name = alias->asname;
1966
1967 if (!compiler_nameop(c, store_name, Store)) {
1968 Py_DECREF(names);
1969 return 0;
1970 }
1971 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001972 /* remove imported module */
1973 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 return 1;
1975}
1976
1977static int
1978compiler_assert(struct compiler *c, stmt_ty s)
1979{
1980 static PyObject *assertion_error = NULL;
1981 basicblock *end;
1982
1983 if (Py_OptimizeFlag)
1984 return 1;
1985 if (assertion_error == NULL) {
1986 assertion_error = PyString_FromString("AssertionError");
1987 if (assertion_error == NULL)
1988 return 0;
1989 }
1990 VISIT(c, expr, s->v.Assert.test);
1991 end = compiler_new_block(c);
1992 if (end == NULL)
1993 return 0;
1994 ADDOP_JREL(c, JUMP_IF_TRUE, end);
1995 ADDOP(c, POP_TOP);
1996 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
1997 if (s->v.Assert.msg) {
1998 VISIT(c, expr, s->v.Assert.msg);
1999 ADDOP_I(c, RAISE_VARARGS, 2);
2000 }
2001 else {
2002 ADDOP_I(c, RAISE_VARARGS, 1);
2003 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002004 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 ADDOP(c, POP_TOP);
2006 return 1;
2007}
2008
2009static int
2010compiler_visit_stmt(struct compiler *c, stmt_ty s)
2011{
2012 int i, n;
2013
Neal Norwitzf733a012006-10-29 18:30:10 +00002014 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 c->u->u_lineno = s->lineno;
2016 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002017
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002018 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002019 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002021 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002023 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 if (c->u->u_ste->ste_type != FunctionBlock)
2025 return compiler_error(c, "'return' outside function");
2026 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 VISIT(c, expr, s->v.Return.value);
2028 }
2029 else
2030 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2031 ADDOP(c, RETURN_VALUE);
2032 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002033 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002034 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002036 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 n = asdl_seq_LEN(s->v.Assign.targets);
2038 VISIT(c, expr, s->v.Assign.value);
2039 for (i = 0; i < n; i++) {
2040 if (i < n - 1)
2041 ADDOP(c, DUP_TOP);
2042 VISIT(c, expr,
2043 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2044 }
2045 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002046 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002048 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002050 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002054 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002056 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 n = 0;
2058 if (s->v.Raise.type) {
2059 VISIT(c, expr, s->v.Raise.type);
2060 n++;
2061 if (s->v.Raise.inst) {
2062 VISIT(c, expr, s->v.Raise.inst);
2063 n++;
2064 if (s->v.Raise.tback) {
2065 VISIT(c, expr, s->v.Raise.tback);
2066 n++;
2067 }
2068 }
2069 }
2070 ADDOP_I(c, RAISE_VARARGS, n);
2071 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002072 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002074 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002076 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002078 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002080 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002082 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 VISIT(c, expr, s->v.Exec.body);
2084 if (s->v.Exec.globals) {
2085 VISIT(c, expr, s->v.Exec.globals);
2086 if (s->v.Exec.locals) {
2087 VISIT(c, expr, s->v.Exec.locals);
2088 } else {
2089 ADDOP(c, DUP_TOP);
2090 }
2091 } else {
2092 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2093 ADDOP(c, DUP_TOP);
2094 }
2095 ADDOP(c, EXEC_STMT);
2096 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002101 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 ADDOP(c, PRINT_EXPR);
2103 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002104 else if (s->v.Expr.value->kind != Str_kind &&
2105 s->v.Expr.value->kind != Num_kind) {
2106 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 ADDOP(c, POP_TOP);
2108 }
2109 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002110 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002112 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002113 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 return compiler_error(c, "'break' outside loop");
2115 ADDOP(c, BREAK_LOOP);
2116 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002117 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002119 case With_kind:
2120 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 }
2122 return 1;
2123}
2124
2125static int
2126unaryop(unaryop_ty op)
2127{
2128 switch (op) {
2129 case Invert:
2130 return UNARY_INVERT;
2131 case Not:
2132 return UNARY_NOT;
2133 case UAdd:
2134 return UNARY_POSITIVE;
2135 case USub:
2136 return UNARY_NEGATIVE;
2137 }
2138 return 0;
2139}
2140
2141static int
2142binop(struct compiler *c, operator_ty op)
2143{
2144 switch (op) {
2145 case Add:
2146 return BINARY_ADD;
2147 case Sub:
2148 return BINARY_SUBTRACT;
2149 case Mult:
2150 return BINARY_MULTIPLY;
2151 case Div:
2152 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2153 return BINARY_TRUE_DIVIDE;
2154 else
2155 return BINARY_DIVIDE;
2156 case Mod:
2157 return BINARY_MODULO;
2158 case Pow:
2159 return BINARY_POWER;
2160 case LShift:
2161 return BINARY_LSHIFT;
2162 case RShift:
2163 return BINARY_RSHIFT;
2164 case BitOr:
2165 return BINARY_OR;
2166 case BitXor:
2167 return BINARY_XOR;
2168 case BitAnd:
2169 return BINARY_AND;
2170 case FloorDiv:
2171 return BINARY_FLOOR_DIVIDE;
2172 }
2173 return 0;
2174}
2175
2176static int
2177cmpop(cmpop_ty op)
2178{
2179 switch (op) {
2180 case Eq:
2181 return PyCmp_EQ;
2182 case NotEq:
2183 return PyCmp_NE;
2184 case Lt:
2185 return PyCmp_LT;
2186 case LtE:
2187 return PyCmp_LE;
2188 case Gt:
2189 return PyCmp_GT;
2190 case GtE:
2191 return PyCmp_GE;
2192 case Is:
2193 return PyCmp_IS;
2194 case IsNot:
2195 return PyCmp_IS_NOT;
2196 case In:
2197 return PyCmp_IN;
2198 case NotIn:
2199 return PyCmp_NOT_IN;
2200 }
2201 return PyCmp_BAD;
2202}
2203
2204static int
2205inplace_binop(struct compiler *c, operator_ty op)
2206{
2207 switch (op) {
2208 case Add:
2209 return INPLACE_ADD;
2210 case Sub:
2211 return INPLACE_SUBTRACT;
2212 case Mult:
2213 return INPLACE_MULTIPLY;
2214 case Div:
2215 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2216 return INPLACE_TRUE_DIVIDE;
2217 else
2218 return INPLACE_DIVIDE;
2219 case Mod:
2220 return INPLACE_MODULO;
2221 case Pow:
2222 return INPLACE_POWER;
2223 case LShift:
2224 return INPLACE_LSHIFT;
2225 case RShift:
2226 return INPLACE_RSHIFT;
2227 case BitOr:
2228 return INPLACE_OR;
2229 case BitXor:
2230 return INPLACE_XOR;
2231 case BitAnd:
2232 return INPLACE_AND;
2233 case FloorDiv:
2234 return INPLACE_FLOOR_DIVIDE;
2235 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002236 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002237 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 return 0;
2239}
2240
2241static int
2242compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2243{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002244 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2246
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002247 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002248 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 /* XXX AugStore isn't used anywhere! */
2250
2251 /* First check for assignment to __debug__. Param? */
2252 if ((ctx == Store || ctx == AugStore || ctx == Del)
2253 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2254 return compiler_error(c, "can not assign to __debug__");
2255 }
2256
Jeremy Hylton37075c52007-02-27 01:01:59 +00002257mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002258 if (!mangled)
2259 return 0;
2260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 op = 0;
2262 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002263 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 switch (scope) {
2265 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002266 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267 optype = OP_DEREF;
2268 break;
2269 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002270 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 optype = OP_DEREF;
2272 break;
2273 case LOCAL:
2274 if (c->u->u_ste->ste_type == FunctionBlock)
2275 optype = OP_FAST;
2276 break;
2277 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002278 if (c->u->u_ste->ste_type == FunctionBlock &&
2279 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280 optype = OP_GLOBAL;
2281 break;
2282 case GLOBAL_EXPLICIT:
2283 optype = OP_GLOBAL;
2284 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002285 default:
2286 /* scope can be 0 */
2287 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 }
2289
2290 /* XXX Leave assert here, but handle __doc__ and the like better */
2291 assert(scope || PyString_AS_STRING(name)[0] == '_');
2292
2293 switch (optype) {
2294 case OP_DEREF:
2295 switch (ctx) {
2296 case Load: op = LOAD_DEREF; break;
2297 case Store: op = STORE_DEREF; break;
2298 case AugLoad:
2299 case AugStore:
2300 break;
2301 case Del:
2302 PyErr_Format(PyExc_SyntaxError,
2303 "can not delete variable '%s' referenced "
2304 "in nested scope",
2305 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002306 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002309 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002310 PyErr_SetString(PyExc_SystemError,
2311 "param invalid for deref variable");
2312 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 }
2314 break;
2315 case OP_FAST:
2316 switch (ctx) {
2317 case Load: op = LOAD_FAST; break;
2318 case Store: op = STORE_FAST; break;
2319 case Del: op = DELETE_FAST; break;
2320 case AugLoad:
2321 case AugStore:
2322 break;
2323 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002324 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002325 PyErr_SetString(PyExc_SystemError,
2326 "param invalid for local variable");
2327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002329 ADDOP_O(c, op, mangled, varnames);
2330 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002331 return 1;
2332 case OP_GLOBAL:
2333 switch (ctx) {
2334 case Load: op = LOAD_GLOBAL; break;
2335 case Store: op = STORE_GLOBAL; break;
2336 case Del: op = DELETE_GLOBAL; break;
2337 case AugLoad:
2338 case AugStore:
2339 break;
2340 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002341 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002342 PyErr_SetString(PyExc_SystemError,
2343 "param invalid for global variable");
2344 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 }
2346 break;
2347 case OP_NAME:
2348 switch (ctx) {
2349 case Load: op = LOAD_NAME; break;
2350 case Store: op = STORE_NAME; break;
2351 case Del: op = DELETE_NAME; break;
2352 case AugLoad:
2353 case AugStore:
2354 break;
2355 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002356 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002357 PyErr_SetString(PyExc_SystemError,
2358 "param invalid for name variable");
2359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 }
2361 break;
2362 }
2363
2364 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002365 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002366 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002367 if (arg < 0)
2368 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002369 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370}
2371
2372static int
2373compiler_boolop(struct compiler *c, expr_ty e)
2374{
2375 basicblock *end;
2376 int jumpi, i, n;
2377 asdl_seq *s;
2378
2379 assert(e->kind == BoolOp_kind);
2380 if (e->v.BoolOp.op == And)
2381 jumpi = JUMP_IF_FALSE;
2382 else
2383 jumpi = JUMP_IF_TRUE;
2384 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002385 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386 return 0;
2387 s = e->v.BoolOp.values;
2388 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002389 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002391 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392 ADDOP_JREL(c, jumpi, end);
2393 ADDOP(c, POP_TOP)
2394 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002395 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396 compiler_use_next_block(c, end);
2397 return 1;
2398}
2399
2400static int
2401compiler_list(struct compiler *c, expr_ty e)
2402{
2403 int n = asdl_seq_LEN(e->v.List.elts);
2404 if (e->v.List.ctx == Store) {
2405 ADDOP_I(c, UNPACK_SEQUENCE, n);
2406 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002407 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408 if (e->v.List.ctx == Load) {
2409 ADDOP_I(c, BUILD_LIST, n);
2410 }
2411 return 1;
2412}
2413
2414static int
2415compiler_tuple(struct compiler *c, expr_ty e)
2416{
2417 int n = asdl_seq_LEN(e->v.Tuple.elts);
2418 if (e->v.Tuple.ctx == Store) {
2419 ADDOP_I(c, UNPACK_SEQUENCE, n);
2420 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002421 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422 if (e->v.Tuple.ctx == Load) {
2423 ADDOP_I(c, BUILD_TUPLE, n);
2424 }
2425 return 1;
2426}
2427
2428static int
2429compiler_compare(struct compiler *c, expr_ty e)
2430{
2431 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002432 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433
2434 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2435 VISIT(c, expr, e->v.Compare.left);
2436 n = asdl_seq_LEN(e->v.Compare.ops);
2437 assert(n > 0);
2438 if (n > 1) {
2439 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002440 if (cleanup == NULL)
2441 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002442 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002443 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 }
2445 for (i = 1; i < n; i++) {
2446 ADDOP(c, DUP_TOP);
2447 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002449 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002450 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2452 NEXT_BLOCK(c);
2453 ADDOP(c, POP_TOP);
2454 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002455 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002456 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002457 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002458 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002460 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 if (n > 1) {
2462 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002463 if (end == NULL)
2464 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 ADDOP_JREL(c, JUMP_FORWARD, end);
2466 compiler_use_next_block(c, cleanup);
2467 ADDOP(c, ROT_TWO);
2468 ADDOP(c, POP_TOP);
2469 compiler_use_next_block(c, end);
2470 }
2471 return 1;
2472}
2473
2474static int
2475compiler_call(struct compiler *c, expr_ty e)
2476{
2477 int n, code = 0;
2478
2479 VISIT(c, expr, e->v.Call.func);
2480 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002481 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002483 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2485 }
2486 if (e->v.Call.starargs) {
2487 VISIT(c, expr, e->v.Call.starargs);
2488 code |= 1;
2489 }
2490 if (e->v.Call.kwargs) {
2491 VISIT(c, expr, e->v.Call.kwargs);
2492 code |= 2;
2493 }
2494 switch (code) {
2495 case 0:
2496 ADDOP_I(c, CALL_FUNCTION, n);
2497 break;
2498 case 1:
2499 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2500 break;
2501 case 2:
2502 ADDOP_I(c, CALL_FUNCTION_KW, n);
2503 break;
2504 case 3:
2505 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2506 break;
2507 }
2508 return 1;
2509}
2510
2511static int
2512compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002513 asdl_seq *generators, int gen_index,
2514 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515{
2516 /* generate code for the iterator, then each of the ifs,
2517 and then write to the element */
2518
2519 comprehension_ty l;
2520 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002521 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002522
2523 start = compiler_new_block(c);
2524 skip = compiler_new_block(c);
2525 if_cleanup = compiler_new_block(c);
2526 anchor = compiler_new_block(c);
2527
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002528 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2529 anchor == NULL)
2530 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531
Anthony Baxter7b782b62006-04-11 12:01:56 +00002532 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 VISIT(c, expr, l->iter);
2534 ADDOP(c, GET_ITER);
2535 compiler_use_next_block(c, start);
2536 ADDOP_JREL(c, FOR_ITER, anchor);
2537 NEXT_BLOCK(c);
2538 VISIT(c, expr, l->target);
2539
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002540 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 n = asdl_seq_LEN(l->ifs);
2542 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002543 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 VISIT(c, expr, e);
2545 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2546 NEXT_BLOCK(c);
2547 ADDOP(c, POP_TOP);
2548 }
2549
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002550 if (++gen_index < asdl_seq_LEN(generators))
2551 if (!compiler_listcomp_generator(c, tmpname,
2552 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 /* only append after the last for generator */
2556 if (gen_index >= asdl_seq_LEN(generators)) {
2557 if (!compiler_nameop(c, tmpname, Load))
2558 return 0;
2559 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002560 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002561
2562 compiler_use_next_block(c, skip);
2563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 for (i = 0; i < n; i++) {
2565 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002566 if (i == 0)
2567 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 ADDOP(c, POP_TOP);
2569 }
2570 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2571 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002572 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002574 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575 return 0;
2576
2577 return 1;
2578}
2579
2580static int
2581compiler_listcomp(struct compiler *c, expr_ty e)
2582{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002584 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 asdl_seq *generators = e->v.ListComp.generators;
2586
2587 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002588 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589 if (!tmp)
2590 return 0;
2591 ADDOP_I(c, BUILD_LIST, 0);
2592 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002594 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2595 e->v.ListComp.elt);
2596 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 return rc;
2598}
2599
2600static int
2601compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 asdl_seq *generators, int gen_index,
2603 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604{
2605 /* generate code for the iterator, then each of the ifs,
2606 and then write to the element */
2607
2608 comprehension_ty ge;
2609 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002610 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611
2612 start = compiler_new_block(c);
2613 skip = compiler_new_block(c);
2614 if_cleanup = compiler_new_block(c);
2615 anchor = compiler_new_block(c);
2616 end = compiler_new_block(c);
2617
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002618 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 anchor == NULL || end == NULL)
2620 return 0;
2621
Anthony Baxter7b782b62006-04-11 12:01:56 +00002622 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 ADDOP_JREL(c, SETUP_LOOP, end);
2624 if (!compiler_push_fblock(c, LOOP, start))
2625 return 0;
2626
2627 if (gen_index == 0) {
2628 /* Receive outermost iter as an implicit argument */
2629 c->u->u_argcount = 1;
2630 ADDOP_I(c, LOAD_FAST, 0);
2631 }
2632 else {
2633 /* Sub-iter - calculate on the fly */
2634 VISIT(c, expr, ge->iter);
2635 ADDOP(c, GET_ITER);
2636 }
2637 compiler_use_next_block(c, start);
2638 ADDOP_JREL(c, FOR_ITER, anchor);
2639 NEXT_BLOCK(c);
2640 VISIT(c, expr, ge->target);
2641
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002642 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 n = asdl_seq_LEN(ge->ifs);
2644 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002645 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 VISIT(c, expr, e);
2647 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2648 NEXT_BLOCK(c);
2649 ADDOP(c, POP_TOP);
2650 }
2651
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2654 return 0;
2655
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656 /* only append after the last 'for' generator */
2657 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 VISIT(c, expr, elt);
2659 ADDOP(c, YIELD_VALUE);
2660 ADDOP(c, POP_TOP);
2661
2662 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 for (i = 0; i < n; i++) {
2665 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002666 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667 compiler_use_next_block(c, if_cleanup);
2668
2669 ADDOP(c, POP_TOP);
2670 }
2671 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2672 compiler_use_next_block(c, anchor);
2673 ADDOP(c, POP_BLOCK);
2674 compiler_pop_fblock(c, LOOP, start);
2675 compiler_use_next_block(c, end);
2676
2677 return 1;
2678}
2679
2680static int
2681compiler_genexp(struct compiler *c, expr_ty e)
2682{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002683 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 PyCodeObject *co;
2685 expr_ty outermost_iter = ((comprehension_ty)
2686 (asdl_seq_GET(e->v.GeneratorExp.generators,
2687 0)))->iter;
2688
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002689 if (!name) {
2690 name = PyString_FromString("<genexpr>");
2691 if (!name)
2692 return 0;
2693 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694
2695 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2696 return 0;
2697 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2698 e->v.GeneratorExp.elt);
2699 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002700 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 if (co == NULL)
2702 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002705 Py_DECREF(co);
2706
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 VISIT(c, expr, outermost_iter);
2708 ADDOP(c, GET_ITER);
2709 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710
2711 return 1;
2712}
2713
2714static int
2715compiler_visit_keyword(struct compiler *c, keyword_ty k)
2716{
2717 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2718 VISIT(c, expr, k->value);
2719 return 1;
2720}
2721
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002722/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 whether they are true or false.
2724
2725 Return values: 1 for true, 0 for false, -1 for non-constant.
2726 */
2727
2728static int
2729expr_constant(expr_ty e)
2730{
2731 switch (e->kind) {
2732 case Num_kind:
2733 return PyObject_IsTrue(e->v.Num.n);
2734 case Str_kind:
2735 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002736 case Name_kind:
2737 /* __debug__ is not assignable, so we can optimize
2738 * it away in if and while statements */
2739 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002740 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002741 return ! Py_OptimizeFlag;
2742 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 default:
2744 return -1;
2745 }
2746}
2747
Guido van Rossumc2e20742006-02-27 22:32:47 +00002748/*
2749 Implements the with statement from PEP 343.
2750
2751 The semantics outlined in that PEP are as follows:
2752
2753 with EXPR as VAR:
2754 BLOCK
2755
2756 It is implemented roughly as:
2757
Guido van Rossumda5b7012006-05-02 19:47:52 +00002758 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002759 exit = context.__exit__ # not calling it
2760 value = context.__enter__()
2761 try:
2762 VAR = value # if VAR present in the syntax
2763 BLOCK
2764 finally:
2765 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002766 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002767 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002768 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002769 exit(*exc)
2770 */
2771static int
2772compiler_with(struct compiler *c, stmt_ty s)
2773{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002774 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002775 basicblock *block, *finally;
2776 identifier tmpexit, tmpvalue = NULL;
2777
2778 assert(s->kind == With_kind);
2779
Guido van Rossumc2e20742006-02-27 22:32:47 +00002780 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781 enter_attr = PyString_InternFromString("__enter__");
2782 if (!enter_attr)
2783 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002784 }
2785 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002786 exit_attr = PyString_InternFromString("__exit__");
2787 if (!exit_attr)
2788 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002789 }
2790
2791 block = compiler_new_block(c);
2792 finally = compiler_new_block(c);
2793 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002794 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002795
2796 /* Create a temporary variable to hold context.__exit__ */
2797 tmpexit = compiler_new_tmpname(c);
2798 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002799 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002800 PyArena_AddPyObject(c->c_arena, tmpexit);
2801
2802 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002803 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002804 We need to do this rather than preserving it on the stack
2805 because SETUP_FINALLY remembers the stack level.
2806 We need to do the assignment *inside* the try/finally
2807 so that context.__exit__() is called when the assignment
2808 fails. But we need to call context.__enter__() *before*
2809 the try/finally so that if it fails we won't call
2810 context.__exit__().
2811 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002812 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002813 if (tmpvalue == NULL)
2814 return 0;
2815 PyArena_AddPyObject(c->c_arena, tmpvalue);
2816 }
2817
Guido van Rossumda5b7012006-05-02 19:47:52 +00002818 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002820
2821 /* Squirrel away context.__exit__ */
2822 ADDOP(c, DUP_TOP);
2823 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2824 if (!compiler_nameop(c, tmpexit, Store))
2825 return 0;
2826
2827 /* Call context.__enter__() */
2828 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2829 ADDOP_I(c, CALL_FUNCTION, 0);
2830
2831 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002832 /* Store it in tmpvalue */
2833 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 return 0;
2835 }
2836 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 /* Discard result from context.__enter__() */
2838 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002839 }
2840
2841 /* Start the try block */
2842 ADDOP_JREL(c, SETUP_FINALLY, finally);
2843
2844 compiler_use_next_block(c, block);
2845 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002846 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002847 }
2848
2849 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002850 /* Bind saved result of context.__enter__() to VAR */
2851 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002852 !compiler_nameop(c, tmpvalue, Del))
2853 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002854 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002855 }
2856
2857 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002858 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002859
2860 /* End of try block; start the finally block */
2861 ADDOP(c, POP_BLOCK);
2862 compiler_pop_fblock(c, FINALLY_TRY, block);
2863
2864 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2865 compiler_use_next_block(c, finally);
2866 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002867 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868
2869 /* Finally block starts; push tmpexit and issue our magic opcode. */
2870 if (!compiler_nameop(c, tmpexit, Load) ||
2871 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002872 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002874
2875 /* Finally block ends. */
2876 ADDOP(c, END_FINALLY);
2877 compiler_pop_fblock(c, FINALLY_END, finally);
2878 return 1;
2879}
2880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881static int
2882compiler_visit_expr(struct compiler *c, expr_ty e)
2883{
2884 int i, n;
2885
Neal Norwitzf733a012006-10-29 18:30:10 +00002886 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002887 set a new line number for the next instruction.
2888 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889 if (e->lineno > c->u->u_lineno) {
2890 c->u->u_lineno = e->lineno;
2891 c->u->u_lineno_set = false;
2892 }
2893 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002894 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 VISIT(c, expr, e->v.BinOp.left);
2898 VISIT(c, expr, e->v.BinOp.right);
2899 ADDOP(c, binop(c, e->v.BinOp.op));
2900 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002901 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902 VISIT(c, expr, e->v.UnaryOp.operand);
2903 ADDOP(c, unaryop(e->v.UnaryOp.op));
2904 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002905 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002907 case IfExp_kind:
2908 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002909 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 /* XXX get rid of arg? */
2911 ADDOP_I(c, BUILD_MAP, 0);
2912 n = asdl_seq_LEN(e->v.Dict.values);
2913 /* We must arrange things just right for STORE_SUBSCR.
2914 It wants the stack to look like (value) (dict) (key) */
2915 for (i = 0; i < n; i++) {
2916 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002917 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002918 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002920 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002921 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 ADDOP(c, STORE_SUBSCR);
2923 }
2924 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002925 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002927 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 return compiler_genexp(c, e);
2929 case Yield_kind:
2930 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002931 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932 if (e->v.Yield.value) {
2933 VISIT(c, expr, e->v.Yield.value);
2934 }
2935 else {
2936 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2937 }
2938 ADDOP(c, YIELD_VALUE);
2939 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002940 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002942 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 VISIT(c, expr, e->v.Repr.value);
2946 ADDOP(c, UNARY_CONVERT);
2947 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002948 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2950 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002951 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2953 break;
2954 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 if (e->v.Attribute.ctx != AugStore)
2957 VISIT(c, expr, e->v.Attribute.value);
2958 switch (e->v.Attribute.ctx) {
2959 case AugLoad:
2960 ADDOP(c, DUP_TOP);
2961 /* Fall through to load */
2962 case Load:
2963 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2964 break;
2965 case AugStore:
2966 ADDOP(c, ROT_TWO);
2967 /* Fall through to save */
2968 case Store:
2969 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2970 break;
2971 case Del:
2972 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2973 break;
2974 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002975 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002976 PyErr_SetString(PyExc_SystemError,
2977 "param invalid in attribute expression");
2978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979 }
2980 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 switch (e->v.Subscript.ctx) {
2983 case AugLoad:
2984 VISIT(c, expr, e->v.Subscript.value);
2985 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2986 break;
2987 case Load:
2988 VISIT(c, expr, e->v.Subscript.value);
2989 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2990 break;
2991 case AugStore:
2992 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2993 break;
2994 case Store:
2995 VISIT(c, expr, e->v.Subscript.value);
2996 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2997 break;
2998 case Del:
2999 VISIT(c, expr, e->v.Subscript.value);
3000 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3001 break;
3002 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003003 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003004 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003005 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003006 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007 }
3008 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003009 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3011 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003012 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003014 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 return compiler_tuple(c, e);
3016 }
3017 return 1;
3018}
3019
3020static int
3021compiler_augassign(struct compiler *c, stmt_ty s)
3022{
3023 expr_ty e = s->v.AugAssign.target;
3024 expr_ty auge;
3025
3026 assert(s->kind == AugAssign_kind);
3027
3028 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003029 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003031 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032 if (auge == NULL)
3033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 VISIT(c, expr, auge);
3035 VISIT(c, expr, s->v.AugAssign.value);
3036 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3037 auge->v.Attribute.ctx = AugStore;
3038 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 break;
3040 case Subscript_kind:
3041 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003042 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003043 if (auge == NULL)
3044 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 VISIT(c, expr, auge);
3046 VISIT(c, expr, s->v.AugAssign.value);
3047 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003048 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003050 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003052 if (!compiler_nameop(c, e->v.Name.id, Load))
3053 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054 VISIT(c, expr, s->v.AugAssign.value);
3055 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3056 return compiler_nameop(c, e->v.Name.id, Store);
3057 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003058 PyErr_Format(PyExc_SystemError,
3059 "invalid node type (%d) for augmented assignment",
3060 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003061 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 }
3063 return 1;
3064}
3065
3066static int
3067compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3068{
3069 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003070 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3071 PyErr_SetString(PyExc_SystemError,
3072 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003074 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 f = &c->u->u_fblock[c->u->u_nfblocks++];
3076 f->fb_type = t;
3077 f->fb_block = b;
3078 return 1;
3079}
3080
3081static void
3082compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3083{
3084 struct compiler_unit *u = c->u;
3085 assert(u->u_nfblocks > 0);
3086 u->u_nfblocks--;
3087 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3088 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3089}
3090
Jeremy Hylton82271f12006-10-04 02:24:52 +00003091static int
3092compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003093 int i;
3094 struct compiler_unit *u = c->u;
3095 for (i = 0; i < u->u_nfblocks; ++i) {
3096 if (u->u_fblock[i].fb_type == LOOP)
3097 return 1;
3098 }
3099 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003100}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003101/* Raises a SyntaxError and returns 0.
3102 If something goes wrong, a different exception may be raised.
3103*/
3104
3105static int
3106compiler_error(struct compiler *c, const char *errstr)
3107{
3108 PyObject *loc;
3109 PyObject *u = NULL, *v = NULL;
3110
3111 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3112 if (!loc) {
3113 Py_INCREF(Py_None);
3114 loc = Py_None;
3115 }
3116 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3117 Py_None, loc);
3118 if (!u)
3119 goto exit;
3120 v = Py_BuildValue("(zO)", errstr, u);
3121 if (!v)
3122 goto exit;
3123 PyErr_SetObject(PyExc_SyntaxError, v);
3124 exit:
3125 Py_DECREF(loc);
3126 Py_XDECREF(u);
3127 Py_XDECREF(v);
3128 return 0;
3129}
3130
3131static int
3132compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003133 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003134{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003135 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 /* XXX this code is duplicated */
3138 switch (ctx) {
3139 case AugLoad: /* fall through to Load */
3140 case Load: op = BINARY_SUBSCR; break;
3141 case AugStore:/* fall through to Store */
3142 case Store: op = STORE_SUBSCR; break;
3143 case Del: op = DELETE_SUBSCR; break;
3144 case Param:
3145 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003146 "invalid %s kind %d in subscript\n",
3147 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 return 0;
3149 }
3150 if (ctx == AugLoad) {
3151 ADDOP_I(c, DUP_TOPX, 2);
3152 }
3153 else if (ctx == AugStore) {
3154 ADDOP(c, ROT_THREE);
3155 }
3156 ADDOP(c, op);
3157 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158}
3159
3160static int
3161compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3162{
3163 int n = 2;
3164 assert(s->kind == Slice_kind);
3165
3166 /* only handles the cases where BUILD_SLICE is emitted */
3167 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003168 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 }
3170 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003171 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003173
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 }
3177 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 }
3180
3181 if (s->v.Slice.step) {
3182 n++;
3183 VISIT(c, expr, s->v.Slice.step);
3184 }
3185 ADDOP_I(c, BUILD_SLICE, n);
3186 return 1;
3187}
3188
3189static int
3190compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3191{
3192 int op = 0, slice_offset = 0, stack_count = 0;
3193
3194 assert(s->v.Slice.step == NULL);
3195 if (s->v.Slice.lower) {
3196 slice_offset++;
3197 stack_count++;
3198 if (ctx != AugStore)
3199 VISIT(c, expr, s->v.Slice.lower);
3200 }
3201 if (s->v.Slice.upper) {
3202 slice_offset += 2;
3203 stack_count++;
3204 if (ctx != AugStore)
3205 VISIT(c, expr, s->v.Slice.upper);
3206 }
3207
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003208 if (ctx == AugLoad) {
3209 switch (stack_count) {
3210 case 0: ADDOP(c, DUP_TOP); break;
3211 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3212 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3213 }
3214 }
3215 else if (ctx == AugStore) {
3216 switch (stack_count) {
3217 case 0: ADDOP(c, ROT_TWO); break;
3218 case 1: ADDOP(c, ROT_THREE); break;
3219 case 2: ADDOP(c, ROT_FOUR); break;
3220 }
3221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222
3223 switch (ctx) {
3224 case AugLoad: /* fall through to Load */
3225 case Load: op = SLICE; break;
3226 case AugStore:/* fall through to Store */
3227 case Store: op = STORE_SLICE; break;
3228 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003229 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003230 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003231 PyErr_SetString(PyExc_SystemError,
3232 "param invalid in simple slice");
3233 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 }
3235
3236 ADDOP(c, op + slice_offset);
3237 return 1;
3238}
3239
3240static int
3241compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3242 expr_context_ty ctx)
3243{
3244 switch (s->kind) {
3245 case Ellipsis_kind:
3246 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3247 break;
3248 case Slice_kind:
3249 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 case Index_kind:
3251 VISIT(c, expr, s->v.Index.value);
3252 break;
3253 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003254 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003255 PyErr_SetString(PyExc_SystemError,
3256 "extended slice invalid in nested slice");
3257 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 }
3259 return 1;
3260}
3261
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262static int
3263compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3264{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003265 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003267 case Index_kind:
3268 kindname = "index";
3269 if (ctx != AugStore) {
3270 VISIT(c, expr, s->v.Index.value);
3271 }
3272 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003274 kindname = "ellipsis";
3275 if (ctx != AugStore) {
3276 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3277 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278 break;
3279 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003280 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 if (!s->v.Slice.step)
3282 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003283 if (ctx != AugStore) {
3284 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 return 0;
3286 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003287 break;
3288 case ExtSlice_kind:
3289 kindname = "extended slice";
3290 if (ctx != AugStore) {
3291 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3292 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003293 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003294 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003295 if (!compiler_visit_nested_slice(c, sub, ctx))
3296 return 0;
3297 }
3298 ADDOP_I(c, BUILD_TUPLE, n);
3299 }
3300 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003301 default:
3302 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003303 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003304 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003306 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307}
3308
Neal Norwitzf733a012006-10-29 18:30:10 +00003309
3310/* End of the compiler section, beginning of the assembler section */
3311
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312/* do depth-first search of basic block graph, starting with block.
3313 post records the block indices in post-order.
3314
3315 XXX must handle implicit jumps from one block to next
3316*/
3317
Neal Norwitzf733a012006-10-29 18:30:10 +00003318struct assembler {
3319 PyObject *a_bytecode; /* string containing bytecode */
3320 int a_offset; /* offset into bytecode */
3321 int a_nblocks; /* number of reachable blocks */
3322 basicblock **a_postorder; /* list of blocks in dfs postorder */
3323 PyObject *a_lnotab; /* string containing lnotab */
3324 int a_lnotab_off; /* offset into lnotab */
3325 int a_lineno; /* last lineno of emitted instruction */
3326 int a_lineno_off; /* bytecode offset of last lineno */
3327};
3328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329static void
3330dfs(struct compiler *c, basicblock *b, struct assembler *a)
3331{
3332 int i;
3333 struct instr *instr = NULL;
3334
3335 if (b->b_seen)
3336 return;
3337 b->b_seen = 1;
3338 if (b->b_next != NULL)
3339 dfs(c, b->b_next, a);
3340 for (i = 0; i < b->b_iused; i++) {
3341 instr = &b->b_instr[i];
3342 if (instr->i_jrel || instr->i_jabs)
3343 dfs(c, instr->i_target, a);
3344 }
3345 a->a_postorder[a->a_nblocks++] = b;
3346}
3347
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003348static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3350{
3351 int i;
3352 struct instr *instr;
3353 if (b->b_seen || b->b_startdepth >= depth)
3354 return maxdepth;
3355 b->b_seen = 1;
3356 b->b_startdepth = depth;
3357 for (i = 0; i < b->b_iused; i++) {
3358 instr = &b->b_instr[i];
3359 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3360 if (depth > maxdepth)
3361 maxdepth = depth;
3362 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3363 if (instr->i_jrel || instr->i_jabs) {
3364 maxdepth = stackdepth_walk(c, instr->i_target,
3365 depth, maxdepth);
3366 if (instr->i_opcode == JUMP_ABSOLUTE ||
3367 instr->i_opcode == JUMP_FORWARD) {
3368 goto out; /* remaining code is dead */
3369 }
3370 }
3371 }
3372 if (b->b_next)
3373 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3374out:
3375 b->b_seen = 0;
3376 return maxdepth;
3377}
3378
3379/* Find the flow path that needs the largest stack. We assume that
3380 * cycles in the flow graph have no net effect on the stack depth.
3381 */
3382static int
3383stackdepth(struct compiler *c)
3384{
3385 basicblock *b, *entryblock;
3386 entryblock = NULL;
3387 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3388 b->b_seen = 0;
3389 b->b_startdepth = INT_MIN;
3390 entryblock = b;
3391 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003392 if (!entryblock)
3393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 return stackdepth_walk(c, entryblock, 0, 0);
3395}
3396
3397static int
3398assemble_init(struct assembler *a, int nblocks, int firstlineno)
3399{
3400 memset(a, 0, sizeof(struct assembler));
3401 a->a_lineno = firstlineno;
3402 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3403 if (!a->a_bytecode)
3404 return 0;
3405 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3406 if (!a->a_lnotab)
3407 return 0;
3408 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003409 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003410 if (!a->a_postorder) {
3411 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003413 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414 return 1;
3415}
3416
3417static void
3418assemble_free(struct assembler *a)
3419{
3420 Py_XDECREF(a->a_bytecode);
3421 Py_XDECREF(a->a_lnotab);
3422 if (a->a_postorder)
3423 PyObject_Free(a->a_postorder);
3424}
3425
3426/* Return the size of a basic block in bytes. */
3427
3428static int
3429instrsize(struct instr *instr)
3430{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003431 if (!instr->i_hasarg)
3432 return 1;
3433 if (instr->i_oparg > 0xffff)
3434 return 6;
3435 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436}
3437
3438static int
3439blocksize(basicblock *b)
3440{
3441 int i;
3442 int size = 0;
3443
3444 for (i = 0; i < b->b_iused; i++)
3445 size += instrsize(&b->b_instr[i]);
3446 return size;
3447}
3448
3449/* All about a_lnotab.
3450
3451c_lnotab is an array of unsigned bytes disguised as a Python string.
3452It is used to map bytecode offsets to source code line #s (when needed
3453for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003454
Tim Peters2a7f3842001-06-09 09:26:21 +00003455The array is conceptually a list of
3456 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003458
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 byte code offset source code line number
3460 0 1
3461 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003462 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 350 307
3464 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003465
3466The first trick is that these numbers aren't stored, only the increments
3467from one row to the next (this doesn't really work, but it's a start):
3468
3469 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3470
3471The second trick is that an unsigned byte can't hold negative values, or
3472values larger than 255, so (a) there's a deep assumption that byte code
3473offsets and their corresponding line #s both increase monotonically, and (b)
3474if at least one column jumps by more than 255 from one row to the next, more
3475than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003477part. A user of c_lnotab desiring to find the source line number
3478corresponding to a bytecode address A should do something like this
3479
3480 lineno = addr = 0
3481 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 addr += addr_incr
3483 if addr > A:
3484 return lineno
3485 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003486
3487In order for this to work, when the addr field increments by more than 255,
3488the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003489increment is < 256. So, in the example above, assemble_lnotab (it used
3490to be called com_set_lineno) should not (as was actually done until 2.2)
3491expand 300, 300 to 255, 255, 45, 45,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003492 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003493*/
3494
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003495static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003497{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 int d_bytecode, d_lineno;
3499 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003500 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501
3502 d_bytecode = a->a_offset - a->a_lineno_off;
3503 d_lineno = i->i_lineno - a->a_lineno;
3504
3505 assert(d_bytecode >= 0);
3506 assert(d_lineno >= 0);
3507
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003508 /* XXX(nnorwitz): is there a better way to handle this?
3509 for loops are special, we want to be able to trace them
3510 each time around, so we need to set an extra line number. */
3511 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003512 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003515 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 nbytes = a->a_lnotab_off + 2 * ncodes;
3517 len = PyString_GET_SIZE(a->a_lnotab);
3518 if (nbytes >= len) {
3519 if (len * 2 < nbytes)
3520 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003521 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522 len *= 2;
3523 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3524 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003525 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003526 lnotab = (unsigned char *)
3527 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003528 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 *lnotab++ = 255;
3530 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 d_bytecode -= ncodes * 255;
3533 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 assert(d_bytecode <= 255);
3536 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003537 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 nbytes = a->a_lnotab_off + 2 * ncodes;
3539 len = PyString_GET_SIZE(a->a_lnotab);
3540 if (nbytes >= len) {
3541 if (len * 2 < nbytes)
3542 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003543 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544 len *= 2;
3545 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3546 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003547 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003548 lnotab = (unsigned char *)
3549 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003551 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003553 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003555 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 d_lineno -= ncodes * 255;
3558 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003559 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 len = PyString_GET_SIZE(a->a_lnotab);
3562 if (a->a_lnotab_off + 2 >= len) {
3563 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003564 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003565 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003566 lnotab = (unsigned char *)
3567 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 a->a_lnotab_off += 2;
3570 if (d_bytecode) {
3571 *lnotab++ = d_bytecode;
3572 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003573 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003574 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 *lnotab++ = 0;
3576 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003577 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 a->a_lineno = i->i_lineno;
3579 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003580 return 1;
3581}
3582
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583/* assemble_emit()
3584 Extend the bytecode with a new instruction.
3585 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003586*/
3587
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003588static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003590{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003591 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003592 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 char *code;
3594
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003595 size = instrsize(i);
3596 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003598 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003601 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 if (a->a_offset + size >= len) {
3603 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003604 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3607 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003608 if (size == 6) {
3609 assert(i->i_hasarg);
3610 *code++ = (char)EXTENDED_ARG;
3611 *code++ = ext & 0xff;
3612 *code++ = ext >> 8;
3613 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003616 if (i->i_hasarg) {
3617 assert(size == 3 || size == 6);
3618 *code++ = arg & 0xff;
3619 *code++ = arg >> 8;
3620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003622}
3623
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003624static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003626{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003628 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003629 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003630
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 /* Compute the size of each block and fixup jump args.
3632 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003633start:
3634 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003636 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 bsize = blocksize(b);
3638 b->b_offset = totsize;
3639 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003640 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003641 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3643 bsize = b->b_offset;
3644 for (i = 0; i < b->b_iused; i++) {
3645 struct instr *instr = &b->b_instr[i];
3646 /* Relative jumps are computed relative to
3647 the instruction pointer after fetching
3648 the jump instruction.
3649 */
3650 bsize += instrsize(instr);
3651 if (instr->i_jabs)
3652 instr->i_oparg = instr->i_target->b_offset;
3653 else if (instr->i_jrel) {
3654 int delta = instr->i_target->b_offset - bsize;
3655 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003656 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003657 else
3658 continue;
3659 if (instr->i_oparg > 0xffff)
3660 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003661 }
3662 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003663
3664 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003665 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003666 with a better solution.
3667
3668 In the meantime, should the goto be dropped in favor
3669 of a loop?
3670
3671 The issue is that in the first loop blocksize() is called
3672 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003673 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003674 i_oparg is calculated in the second loop above.
3675
3676 So we loop until we stop seeing new EXTENDED_ARGs.
3677 The only EXTENDED_ARGs that could be popping up are
3678 ones in jump instructions. So this should converge
3679 fairly quickly.
3680 */
3681 if (last_extended_arg_count != extended_arg_count) {
3682 last_extended_arg_count = extended_arg_count;
3683 goto start;
3684 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003685}
3686
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003687static PyObject *
3688dict_keys_inorder(PyObject *dict, int offset)
3689{
3690 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003691 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003692
3693 tuple = PyTuple_New(size);
3694 if (tuple == NULL)
3695 return NULL;
3696 while (PyDict_Next(dict, &pos, &k, &v)) {
3697 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003698 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003699 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003700 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003702 PyTuple_SET_ITEM(tuple, i - offset, k);
3703 }
3704 return tuple;
3705}
3706
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003707static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003709{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710 PySTEntryObject *ste = c->u->u_ste;
3711 int flags = 0, n;
3712 if (ste->ste_type != ModuleBlock)
3713 flags |= CO_NEWLOCALS;
3714 if (ste->ste_type == FunctionBlock) {
3715 if (!ste->ste_unoptimized)
3716 flags |= CO_OPTIMIZED;
3717 if (ste->ste_nested)
3718 flags |= CO_NESTED;
3719 if (ste->ste_generator)
3720 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003721 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722 if (ste->ste_varargs)
3723 flags |= CO_VARARGS;
3724 if (ste->ste_varkeywords)
3725 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003726 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003728
3729 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732 n = PyDict_Size(c->u->u_freevars);
3733 if (n < 0)
3734 return -1;
3735 if (n == 0) {
3736 n = PyDict_Size(c->u->u_cellvars);
3737 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003738 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 if (n == 0) {
3740 flags |= CO_NOFREE;
3741 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003742 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003743
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003744 return flags;
3745}
3746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747static PyCodeObject *
3748makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003749{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 PyObject *tmp;
3751 PyCodeObject *co = NULL;
3752 PyObject *consts = NULL;
3753 PyObject *names = NULL;
3754 PyObject *varnames = NULL;
3755 PyObject *filename = NULL;
3756 PyObject *name = NULL;
3757 PyObject *freevars = NULL;
3758 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003759 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 tmp = dict_keys_inorder(c->u->u_consts, 0);
3763 if (!tmp)
3764 goto error;
3765 consts = PySequence_List(tmp); /* optimize_code requires a list */
3766 Py_DECREF(tmp);
3767
3768 names = dict_keys_inorder(c->u->u_names, 0);
3769 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3770 if (!consts || !names || !varnames)
3771 goto error;
3772
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3774 if (!cellvars)
3775 goto error;
3776 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3777 if (!freevars)
3778 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 filename = PyString_FromString(c->c_filename);
3780 if (!filename)
3781 goto error;
3782
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003783 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 flags = compute_code_flags(c);
3785 if (flags < 0)
3786 goto error;
3787
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003788 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 if (!bytecode)
3790 goto error;
3791
3792 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3793 if (!tmp)
3794 goto error;
3795 Py_DECREF(consts);
3796 consts = tmp;
3797
3798 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3799 bytecode, consts, names, varnames,
3800 freevars, cellvars,
3801 filename, c->u->u_name,
3802 c->u->u_firstlineno,
3803 a->a_lnotab);
3804 error:
3805 Py_XDECREF(consts);
3806 Py_XDECREF(names);
3807 Py_XDECREF(varnames);
3808 Py_XDECREF(filename);
3809 Py_XDECREF(name);
3810 Py_XDECREF(freevars);
3811 Py_XDECREF(cellvars);
3812 Py_XDECREF(bytecode);
3813 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003814}
3815
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003816
3817/* For debugging purposes only */
3818#if 0
3819static void
3820dump_instr(const struct instr *i)
3821{
3822 const char *jrel = i->i_jrel ? "jrel " : "";
3823 const char *jabs = i->i_jabs ? "jabs " : "";
3824 char arg[128];
3825
3826 *arg = '\0';
3827 if (i->i_hasarg)
3828 sprintf(arg, "arg: %d ", i->i_oparg);
3829
3830 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3831 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3832}
3833
3834static void
3835dump_basicblock(const basicblock *b)
3836{
3837 const char *seen = b->b_seen ? "seen " : "";
3838 const char *b_return = b->b_return ? "return " : "";
3839 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3840 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3841 if (b->b_instr) {
3842 int i;
3843 for (i = 0; i < b->b_iused; i++) {
3844 fprintf(stderr, " [%02d] ", i);
3845 dump_instr(b->b_instr + i);
3846 }
3847 }
3848}
3849#endif
3850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851static PyCodeObject *
3852assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003853{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 basicblock *b, *entryblock;
3855 struct assembler a;
3856 int i, j, nblocks;
3857 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 /* Make sure every block that falls off the end returns None.
3860 XXX NEXT_BLOCK() isn't quite right, because if the last
3861 block ends with a jump or return b_next shouldn't set.
3862 */
3863 if (!c->u->u_curblock->b_return) {
3864 NEXT_BLOCK(c);
3865 if (addNone)
3866 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3867 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003868 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 nblocks = 0;
3871 entryblock = NULL;
3872 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3873 nblocks++;
3874 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003875 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003876
Neal Norwitzed657552006-07-10 00:04:44 +00003877 /* Set firstlineno if it wasn't explicitly set. */
3878 if (!c->u->u_firstlineno) {
3879 if (entryblock && entryblock->b_instr)
3880 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3881 else
3882 c->u->u_firstlineno = 1;
3883 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3885 goto error;
3886 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003889 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003890
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 /* Emit code in reverse postorder from dfs. */
3892 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003893 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 for (j = 0; j < b->b_iused; j++)
3895 if (!assemble_emit(&a, &b->b_instr[j]))
3896 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003897 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3900 goto error;
3901 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3902 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 co = makecode(c, &a);
3905 error:
3906 assemble_free(&a);
3907 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003908}