blob: f051d13ee5e910cb2ef20aa25fcf807171336775 [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);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122 if (compiler_isdocstring(st)) {
1123 i = 1;
1124 VISIT(c, expr, st->v.Expr.value);
1125 if (!compiler_nameop(c, __doc__, Store))
1126 return 0;
1127 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001128 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001129 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 return 1;
1131}
1132
1133static PyCodeObject *
1134compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001135{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001136 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001137 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 static PyObject *module;
1139 if (!module) {
1140 module = PyString_FromString("<module>");
1141 if (!module)
1142 return NULL;
1143 }
Neal Norwitzed657552006-07-10 00:04:44 +00001144 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1145 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001146 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147 switch (mod->kind) {
1148 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001149 if (!compiler_body(c, mod->v.Module.body)) {
1150 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001152 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 break;
1154 case Interactive_kind:
1155 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001156 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001157 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001158 break;
1159 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001160 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001161 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 break;
1163 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001164 PyErr_SetString(PyExc_SystemError,
1165 "suite should not be possible");
1166 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001167 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001168 PyErr_Format(PyExc_SystemError,
1169 "module kind %d should not be possible",
1170 mod->kind);
1171 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001172 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173 co = assemble(c, addNone);
1174 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001175 return co;
1176}
1177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178/* The test for LOCAL must come before the test for FREE in order to
1179 handle classes where name is both local and free. The local var is
1180 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001181*/
1182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183static int
1184get_ref_type(struct compiler *c, PyObject *name)
1185{
1186 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001187 if (scope == 0) {
1188 char buf[350];
1189 PyOS_snprintf(buf, sizeof(buf),
1190 "unknown scope for %.100s in %.100s(%s) in %s\n"
1191 "symbols: %s\nlocals: %s\nglobals: %s\n",
1192 PyString_AS_STRING(name),
1193 PyString_AS_STRING(c->u->u_name),
1194 PyObject_REPR(c->u->u_ste->ste_id),
1195 c->c_filename,
1196 PyObject_REPR(c->u->u_ste->ste_symbols),
1197 PyObject_REPR(c->u->u_varnames),
1198 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001200 Py_FatalError(buf);
1201 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001202
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001203 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204}
1205
1206static int
1207compiler_lookup_arg(PyObject *dict, PyObject *name)
1208{
1209 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001210 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001212 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001214 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001216 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217 return PyInt_AS_LONG(v);
1218}
1219
1220static int
1221compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1222{
1223 int i, free = PyCode_GetNumFree(co);
1224 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001225 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1226 ADDOP_I(c, MAKE_FUNCTION, args);
1227 return 1;
1228 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229 for (i = 0; i < free; ++i) {
1230 /* Bypass com_addop_varname because it will generate
1231 LOAD_DEREF but LOAD_CLOSURE is needed.
1232 */
1233 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1234 int arg, reftype;
1235
1236 /* Special case: If a class contains a method with a
1237 free variable that has the same name as a method,
1238 the name will be considered free *and* local in the
1239 class. It should be handled by the closure, as
1240 well as by the normal name loookup logic.
1241 */
1242 reftype = get_ref_type(c, name);
1243 if (reftype == CELL)
1244 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1245 else /* (reftype == FREE) */
1246 arg = compiler_lookup_arg(c->u->u_freevars, name);
1247 if (arg == -1) {
1248 printf("lookup %s in %s %d %d\n"
1249 "freevars of %s: %s\n",
1250 PyObject_REPR(name),
1251 PyString_AS_STRING(c->u->u_name),
1252 reftype, arg,
1253 PyString_AS_STRING(co->co_name),
1254 PyObject_REPR(co->co_freevars));
1255 Py_FatalError("compiler_make_closure()");
1256 }
1257 ADDOP_I(c, LOAD_CLOSURE, arg);
1258 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001261 ADDOP_I(c, MAKE_CLOSURE, args);
1262 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263}
1264
1265static int
1266compiler_decorators(struct compiler *c, asdl_seq* decos)
1267{
1268 int i;
1269
1270 if (!decos)
1271 return 1;
1272
1273 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001274 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 }
1276 return 1;
1277}
1278
1279static int
1280compiler_arguments(struct compiler *c, arguments_ty args)
1281{
1282 int i;
1283 int n = asdl_seq_LEN(args->args);
1284 /* Correctly handle nested argument lists */
1285 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001286 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 if (arg->kind == Tuple_kind) {
1288 PyObject *id = PyString_FromFormat(".%d", i);
1289 if (id == NULL) {
1290 return 0;
1291 }
1292 if (!compiler_nameop(c, id, Load)) {
1293 Py_DECREF(id);
1294 return 0;
1295 }
1296 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001297 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 }
1299 }
1300 return 1;
1301}
1302
1303static int
1304compiler_function(struct compiler *c, stmt_ty s)
1305{
1306 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 arguments_ty args = s->v.FunctionDef.args;
1309 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001310 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311 int i, n, docstring;
1312
1313 assert(s->kind == FunctionDef_kind);
1314
1315 if (!compiler_decorators(c, decos))
1316 return 0;
1317 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001318 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001319 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1320 s->lineno))
1321 return 0;
1322
Anthony Baxter7b782b62006-04-11 12:01:56 +00001323 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001324 docstring = compiler_isdocstring(st);
1325 if (docstring)
1326 first_const = st->v.Expr.value->v.Str.s;
1327 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001328 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001329 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001332 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 compiler_arguments(c, args);
1334
1335 c->u->u_argcount = asdl_seq_LEN(args->args);
1336 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001337 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001338 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001339 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1340 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341 }
1342 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001343 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 if (co == NULL)
1345 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001347 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001348 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349
1350 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1351 ADDOP_I(c, CALL_FUNCTION, 1);
1352 }
1353
1354 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1355}
1356
1357static int
1358compiler_class(struct compiler *c, stmt_ty s)
1359{
1360 int n;
1361 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001362 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363 /* push class name on stack, needed by BUILD_CLASS */
1364 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1365 /* push the tuple of base classes on the stack */
1366 n = asdl_seq_LEN(s->v.ClassDef.bases);
1367 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001368 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 ADDOP_I(c, BUILD_TUPLE, n);
1370 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1371 s->lineno))
1372 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001373 c->u->u_private = s->v.ClassDef.name;
1374 Py_INCREF(c->u->u_private);
1375 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 if (!str || !compiler_nameop(c, str, Load)) {
1377 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001378 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 }
1381
1382 Py_DECREF(str);
1383 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384 if (!str || !compiler_nameop(c, str, Store)) {
1385 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001386 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001388 }
1389 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001391 if (!compiler_body(c, s->v.ClassDef.body)) {
1392 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001396 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1397 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001399 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400 if (co == NULL)
1401 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001402
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001403 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001404 Py_DECREF(co);
1405
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406 ADDOP_I(c, CALL_FUNCTION, 0);
1407 ADDOP(c, BUILD_CLASS);
1408 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1409 return 0;
1410 return 1;
1411}
1412
1413static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001414compiler_ifexp(struct compiler *c, expr_ty e)
1415{
1416 basicblock *end, *next;
1417
1418 assert(e->kind == IfExp_kind);
1419 end = compiler_new_block(c);
1420 if (end == NULL)
1421 return 0;
1422 next = compiler_new_block(c);
1423 if (next == NULL)
1424 return 0;
1425 VISIT(c, expr, e->v.IfExp.test);
1426 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1427 ADDOP(c, POP_TOP);
1428 VISIT(c, expr, e->v.IfExp.body);
1429 ADDOP_JREL(c, JUMP_FORWARD, end);
1430 compiler_use_next_block(c, next);
1431 ADDOP(c, POP_TOP);
1432 VISIT(c, expr, e->v.IfExp.orelse);
1433 compiler_use_next_block(c, end);
1434 return 1;
1435}
1436
1437static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438compiler_lambda(struct compiler *c, expr_ty e)
1439{
1440 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001441 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442 arguments_ty args = e->v.Lambda.args;
1443 assert(e->kind == Lambda_kind);
1444
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001445 if (!name) {
1446 name = PyString_InternFromString("<lambda>");
1447 if (!name)
1448 return 0;
1449 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450
1451 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001452 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1454 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001455
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001456 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457 compiler_arguments(c, args);
1458
1459 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001460 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1461 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001463 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464 if (co == NULL)
1465 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001467 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001468 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469
1470 return 1;
1471}
1472
1473static int
1474compiler_print(struct compiler *c, stmt_ty s)
1475{
1476 int i, n;
1477 bool dest;
1478
1479 assert(s->kind == Print_kind);
1480 n = asdl_seq_LEN(s->v.Print.values);
1481 dest = false;
1482 if (s->v.Print.dest) {
1483 VISIT(c, expr, s->v.Print.dest);
1484 dest = true;
1485 }
1486 for (i = 0; i < n; i++) {
1487 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1488 if (dest) {
1489 ADDOP(c, DUP_TOP);
1490 VISIT(c, expr, e);
1491 ADDOP(c, ROT_TWO);
1492 ADDOP(c, PRINT_ITEM_TO);
1493 }
1494 else {
1495 VISIT(c, expr, e);
1496 ADDOP(c, PRINT_ITEM);
1497 }
1498 }
1499 if (s->v.Print.nl) {
1500 if (dest)
1501 ADDOP(c, PRINT_NEWLINE_TO)
1502 else
1503 ADDOP(c, PRINT_NEWLINE)
1504 }
1505 else if (dest)
1506 ADDOP(c, POP_TOP);
1507 return 1;
1508}
1509
1510static int
1511compiler_if(struct compiler *c, stmt_ty s)
1512{
1513 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001514 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515 assert(s->kind == If_kind);
1516 end = compiler_new_block(c);
1517 if (end == NULL)
1518 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001519 next = compiler_new_block(c);
1520 if (next == NULL)
1521 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001522
1523 constant = expr_constant(s->v.If.test);
1524 /* constant = 0: "if 0"
1525 * constant = 1: "if 1", "if 2", ...
1526 * constant = -1: rest */
1527 if (constant == 0) {
1528 if (s->v.If.orelse)
1529 VISIT_SEQ(c, stmt, s->v.If.orelse);
1530 } else if (constant == 1) {
1531 VISIT_SEQ(c, stmt, s->v.If.body);
1532 } else {
1533 VISIT(c, expr, s->v.If.test);
1534 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1535 ADDOP(c, POP_TOP);
1536 VISIT_SEQ(c, stmt, s->v.If.body);
1537 ADDOP_JREL(c, JUMP_FORWARD, end);
1538 compiler_use_next_block(c, next);
1539 ADDOP(c, POP_TOP);
1540 if (s->v.If.orelse)
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001541 VISIT_SEQ(c, stmt, s->v.If.orelse);
Georg Brandlddbaa662006-06-04 21:56:52 +00001542 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001543 compiler_use_next_block(c, end);
1544 return 1;
1545}
1546
1547static int
1548compiler_for(struct compiler *c, stmt_ty s)
1549{
1550 basicblock *start, *cleanup, *end;
1551
1552 start = compiler_new_block(c);
1553 cleanup = compiler_new_block(c);
1554 end = compiler_new_block(c);
1555 if (start == NULL || end == NULL || cleanup == NULL)
1556 return 0;
1557 ADDOP_JREL(c, SETUP_LOOP, end);
1558 if (!compiler_push_fblock(c, LOOP, start))
1559 return 0;
1560 VISIT(c, expr, s->v.For.iter);
1561 ADDOP(c, GET_ITER);
1562 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001563 /* XXX(nnorwitz): is there a better way to handle this?
1564 for loops are special, we want to be able to trace them
1565 each time around, so we need to set an extra line number. */
1566 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567 ADDOP_JREL(c, FOR_ITER, cleanup);
1568 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001569 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1571 compiler_use_next_block(c, cleanup);
1572 ADDOP(c, POP_BLOCK);
1573 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001574 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575 compiler_use_next_block(c, end);
1576 return 1;
1577}
1578
1579static int
1580compiler_while(struct compiler *c, stmt_ty s)
1581{
1582 basicblock *loop, *orelse, *end, *anchor = NULL;
1583 int constant = expr_constant(s->v.While.test);
1584
1585 if (constant == 0)
1586 return 1;
1587 loop = compiler_new_block(c);
1588 end = compiler_new_block(c);
1589 if (constant == -1) {
1590 anchor = compiler_new_block(c);
1591 if (anchor == NULL)
1592 return 0;
1593 }
1594 if (loop == NULL || end == NULL)
1595 return 0;
1596 if (s->v.While.orelse) {
1597 orelse = compiler_new_block(c);
1598 if (orelse == NULL)
1599 return 0;
1600 }
1601 else
1602 orelse = NULL;
1603
1604 ADDOP_JREL(c, SETUP_LOOP, end);
1605 compiler_use_next_block(c, loop);
1606 if (!compiler_push_fblock(c, LOOP, loop))
1607 return 0;
1608 if (constant == -1) {
1609 VISIT(c, expr, s->v.While.test);
1610 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1611 ADDOP(c, POP_TOP);
1612 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001613 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1615
1616 /* XXX should the two POP instructions be in a separate block
1617 if there is no else clause ?
1618 */
1619
1620 if (constant == -1) {
1621 compiler_use_next_block(c, anchor);
1622 ADDOP(c, POP_TOP);
1623 ADDOP(c, POP_BLOCK);
1624 }
1625 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001626 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001627 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 compiler_use_next_block(c, end);
1629
1630 return 1;
1631}
1632
1633static int
1634compiler_continue(struct compiler *c)
1635{
1636 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001637 static const char IN_FINALLY_ERROR_MSG[] =
1638 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639 int i;
1640
1641 if (!c->u->u_nfblocks)
1642 return compiler_error(c, LOOP_ERROR_MSG);
1643 i = c->u->u_nfblocks - 1;
1644 switch (c->u->u_fblock[i].fb_type) {
1645 case LOOP:
1646 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1647 break;
1648 case EXCEPT:
1649 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001650 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1651 /* Prevent continue anywhere under a finally
1652 even if hidden in a sub-try or except. */
1653 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1654 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1655 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656 if (i == -1)
1657 return compiler_error(c, LOOP_ERROR_MSG);
1658 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1659 break;
1660 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001661 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001662 }
1663
1664 return 1;
1665}
1666
1667/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1668
1669 SETUP_FINALLY L
1670 <code for body>
1671 POP_BLOCK
1672 LOAD_CONST <None>
1673 L: <code for finalbody>
1674 END_FINALLY
1675
1676 The special instructions use the block stack. Each block
1677 stack entry contains the instruction that created it (here
1678 SETUP_FINALLY), the level of the value stack at the time the
1679 block stack entry was created, and a label (here L).
1680
1681 SETUP_FINALLY:
1682 Pushes the current value stack level and the label
1683 onto the block stack.
1684 POP_BLOCK:
1685 Pops en entry from the block stack, and pops the value
1686 stack until its level is the same as indicated on the
1687 block stack. (The label is ignored.)
1688 END_FINALLY:
1689 Pops a variable number of entries from the *value* stack
1690 and re-raises the exception they specify. The number of
1691 entries popped depends on the (pseudo) exception type.
1692
1693 The block stack is unwound when an exception is raised:
1694 when a SETUP_FINALLY entry is found, the exception is pushed
1695 onto the value stack (and the exception condition is cleared),
1696 and the interpreter jumps to the label gotten from the block
1697 stack.
1698*/
1699
1700static int
1701compiler_try_finally(struct compiler *c, stmt_ty s)
1702{
1703 basicblock *body, *end;
1704 body = compiler_new_block(c);
1705 end = compiler_new_block(c);
1706 if (body == NULL || end == NULL)
1707 return 0;
1708
1709 ADDOP_JREL(c, SETUP_FINALLY, end);
1710 compiler_use_next_block(c, body);
1711 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1712 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001713 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714 ADDOP(c, POP_BLOCK);
1715 compiler_pop_fblock(c, FINALLY_TRY, body);
1716
1717 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1718 compiler_use_next_block(c, end);
1719 if (!compiler_push_fblock(c, FINALLY_END, end))
1720 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001721 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 ADDOP(c, END_FINALLY);
1723 compiler_pop_fblock(c, FINALLY_END, end);
1724
1725 return 1;
1726}
1727
1728/*
1729 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1730 (The contents of the value stack is shown in [], with the top
1731 at the right; 'tb' is trace-back info, 'val' the exception's
1732 associated value, and 'exc' the exception.)
1733
1734 Value stack Label Instruction Argument
1735 [] SETUP_EXCEPT L1
1736 [] <code for S>
1737 [] POP_BLOCK
1738 [] JUMP_FORWARD L0
1739
1740 [tb, val, exc] L1: DUP )
1741 [tb, val, exc, exc] <evaluate E1> )
1742 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1743 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1744 [tb, val, exc, 1] POP )
1745 [tb, val, exc] POP
1746 [tb, val] <assign to V1> (or POP if no V1)
1747 [tb] POP
1748 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001749 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750
1751 [tb, val, exc, 0] L2: POP
1752 [tb, val, exc] DUP
1753 .............................etc.......................
1754
1755 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001756 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757
1758 [] L0: <next statement>
1759
1760 Of course, parts are not generated if Vi or Ei is not present.
1761*/
1762static int
1763compiler_try_except(struct compiler *c, stmt_ty s)
1764{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001765 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 int i, n;
1767
1768 body = compiler_new_block(c);
1769 except = compiler_new_block(c);
1770 orelse = compiler_new_block(c);
1771 end = compiler_new_block(c);
1772 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1773 return 0;
1774 ADDOP_JREL(c, SETUP_EXCEPT, except);
1775 compiler_use_next_block(c, body);
1776 if (!compiler_push_fblock(c, EXCEPT, body))
1777 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001778 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779 ADDOP(c, POP_BLOCK);
1780 compiler_pop_fblock(c, EXCEPT, body);
1781 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1782 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1783 compiler_use_next_block(c, except);
1784 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001785 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786 s->v.TryExcept.handlers, i);
1787 if (!handler->type && i < n-1)
1788 return compiler_error(c, "default 'except:' must be last");
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001789 c->u->u_lineno_set = false;
1790 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 except = compiler_new_block(c);
1792 if (except == NULL)
1793 return 0;
1794 if (handler->type) {
1795 ADDOP(c, DUP_TOP);
1796 VISIT(c, expr, handler->type);
1797 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1798 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1799 ADDOP(c, POP_TOP);
1800 }
1801 ADDOP(c, POP_TOP);
1802 if (handler->name) {
1803 VISIT(c, expr, handler->name);
1804 }
1805 else {
1806 ADDOP(c, POP_TOP);
1807 }
1808 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001809 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 ADDOP_JREL(c, JUMP_FORWARD, end);
1811 compiler_use_next_block(c, except);
1812 if (handler->type)
1813 ADDOP(c, POP_TOP);
1814 }
1815 ADDOP(c, END_FINALLY);
1816 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001817 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818 compiler_use_next_block(c, end);
1819 return 1;
1820}
1821
1822static int
1823compiler_import_as(struct compiler *c, identifier name, identifier asname)
1824{
1825 /* The IMPORT_NAME opcode was already generated. This function
1826 merely needs to bind the result to a name.
1827
1828 If there is a dot in name, we need to split it and emit a
1829 LOAD_ATTR for each name.
1830 */
1831 const char *src = PyString_AS_STRING(name);
1832 const char *dot = strchr(src, '.');
1833 if (dot) {
1834 /* Consume the base module name to get the first attribute */
1835 src = dot + 1;
1836 while (dot) {
1837 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001838 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001840 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001842 if (!attr)
1843 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001845 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 src = dot + 1;
1847 }
1848 }
1849 return compiler_nameop(c, asname, Store);
1850}
1851
1852static int
1853compiler_import(struct compiler *c, stmt_ty s)
1854{
1855 /* The Import node stores a module name like a.b.c as a single
1856 string. This is convenient for all cases except
1857 import a.b.c as d
1858 where we need to parse that string to extract the individual
1859 module names.
1860 XXX Perhaps change the representation to make this case simpler?
1861 */
1862 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001865 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001866 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001867 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001868
Neal Norwitzcbce2802006-04-03 06:26:32 +00001869 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001870 level = PyInt_FromLong(0);
1871 else
1872 level = PyInt_FromLong(-1);
1873
1874 if (level == NULL)
1875 return 0;
1876
1877 ADDOP_O(c, LOAD_CONST, level, consts);
1878 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1880 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1881
1882 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001883 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001884 if (!r)
1885 return r;
1886 }
1887 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888 identifier tmp = alias->name;
1889 const char *base = PyString_AS_STRING(alias->name);
1890 char *dot = strchr(base, '.');
1891 if (dot)
1892 tmp = PyString_FromStringAndSize(base,
1893 dot - base);
1894 r = compiler_nameop(c, tmp, Store);
1895 if (dot) {
1896 Py_DECREF(tmp);
1897 }
1898 if (!r)
1899 return r;
1900 }
1901 }
1902 return 1;
1903}
1904
1905static int
1906compiler_from_import(struct compiler *c, stmt_ty s)
1907{
1908 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909
1910 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001911 PyObject *level;
1912
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913 if (!names)
1914 return 0;
1915
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001916 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001917 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001918 level = PyInt_FromLong(-1);
1919 else
1920 level = PyInt_FromLong(s->v.ImportFrom.level);
1921
1922 if (!level) {
1923 Py_DECREF(names);
1924 return 0;
1925 }
1926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 /* build up the names */
1928 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001929 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930 Py_INCREF(alias->name);
1931 PyTuple_SET_ITEM(names, i, alias->name);
1932 }
1933
1934 if (s->lineno > c->c_future->ff_lineno) {
1935 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1936 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001937 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 Py_DECREF(names);
1939 return compiler_error(c,
1940 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001941 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942
1943 }
1944 }
1945
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001946 ADDOP_O(c, LOAD_CONST, level, consts);
1947 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001949 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1951 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001952 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953 identifier store_name;
1954
1955 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1956 assert(n == 1);
1957 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 }
1960
1961 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1962 store_name = alias->name;
1963 if (alias->asname)
1964 store_name = alias->asname;
1965
1966 if (!compiler_nameop(c, store_name, Store)) {
1967 Py_DECREF(names);
1968 return 0;
1969 }
1970 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001971 /* remove imported module */
1972 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 return 1;
1974}
1975
1976static int
1977compiler_assert(struct compiler *c, stmt_ty s)
1978{
1979 static PyObject *assertion_error = NULL;
1980 basicblock *end;
1981
1982 if (Py_OptimizeFlag)
1983 return 1;
1984 if (assertion_error == NULL) {
1985 assertion_error = PyString_FromString("AssertionError");
1986 if (assertion_error == NULL)
1987 return 0;
1988 }
1989 VISIT(c, expr, s->v.Assert.test);
1990 end = compiler_new_block(c);
1991 if (end == NULL)
1992 return 0;
1993 ADDOP_JREL(c, JUMP_IF_TRUE, end);
1994 ADDOP(c, POP_TOP);
1995 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
1996 if (s->v.Assert.msg) {
1997 VISIT(c, expr, s->v.Assert.msg);
1998 ADDOP_I(c, RAISE_VARARGS, 2);
1999 }
2000 else {
2001 ADDOP_I(c, RAISE_VARARGS, 1);
2002 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002003 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 ADDOP(c, POP_TOP);
2005 return 1;
2006}
2007
2008static int
2009compiler_visit_stmt(struct compiler *c, stmt_ty s)
2010{
2011 int i, n;
2012
Neal Norwitzf733a012006-10-29 18:30:10 +00002013 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 c->u->u_lineno = s->lineno;
2015 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002018 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002020 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002022 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 if (c->u->u_ste->ste_type != FunctionBlock)
2024 return compiler_error(c, "'return' outside function");
2025 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 VISIT(c, expr, s->v.Return.value);
2027 }
2028 else
2029 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2030 ADDOP(c, RETURN_VALUE);
2031 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002032 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002033 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002035 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 n = asdl_seq_LEN(s->v.Assign.targets);
2037 VISIT(c, expr, s->v.Assign.value);
2038 for (i = 0; i < n; i++) {
2039 if (i < n - 1)
2040 ADDOP(c, DUP_TOP);
2041 VISIT(c, expr,
2042 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2043 }
2044 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002045 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002047 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002049 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002051 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002053 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002055 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 n = 0;
2057 if (s->v.Raise.type) {
2058 VISIT(c, expr, s->v.Raise.type);
2059 n++;
2060 if (s->v.Raise.inst) {
2061 VISIT(c, expr, s->v.Raise.inst);
2062 n++;
2063 if (s->v.Raise.tback) {
2064 VISIT(c, expr, s->v.Raise.tback);
2065 n++;
2066 }
2067 }
2068 }
2069 ADDOP_I(c, RAISE_VARARGS, n);
2070 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002073 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002075 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 VISIT(c, expr, s->v.Exec.body);
2083 if (s->v.Exec.globals) {
2084 VISIT(c, expr, s->v.Exec.globals);
2085 if (s->v.Exec.locals) {
2086 VISIT(c, expr, s->v.Exec.locals);
2087 } else {
2088 ADDOP(c, DUP_TOP);
2089 }
2090 } else {
2091 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2092 ADDOP(c, DUP_TOP);
2093 }
2094 ADDOP(c, EXEC_STMT);
2095 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002096 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002098 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002100 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002101 ADDOP(c, PRINT_EXPR);
2102 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002103 else if (s->v.Expr.value->kind != Str_kind &&
2104 s->v.Expr.value->kind != Num_kind) {
2105 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 ADDOP(c, POP_TOP);
2107 }
2108 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002112 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 return compiler_error(c, "'break' outside loop");
2114 ADDOP(c, BREAK_LOOP);
2115 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002116 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002118 case With_kind:
2119 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 }
2121 return 1;
2122}
2123
2124static int
2125unaryop(unaryop_ty op)
2126{
2127 switch (op) {
2128 case Invert:
2129 return UNARY_INVERT;
2130 case Not:
2131 return UNARY_NOT;
2132 case UAdd:
2133 return UNARY_POSITIVE;
2134 case USub:
2135 return UNARY_NEGATIVE;
2136 }
2137 return 0;
2138}
2139
2140static int
2141binop(struct compiler *c, operator_ty op)
2142{
2143 switch (op) {
2144 case Add:
2145 return BINARY_ADD;
2146 case Sub:
2147 return BINARY_SUBTRACT;
2148 case Mult:
2149 return BINARY_MULTIPLY;
2150 case Div:
2151 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2152 return BINARY_TRUE_DIVIDE;
2153 else
2154 return BINARY_DIVIDE;
2155 case Mod:
2156 return BINARY_MODULO;
2157 case Pow:
2158 return BINARY_POWER;
2159 case LShift:
2160 return BINARY_LSHIFT;
2161 case RShift:
2162 return BINARY_RSHIFT;
2163 case BitOr:
2164 return BINARY_OR;
2165 case BitXor:
2166 return BINARY_XOR;
2167 case BitAnd:
2168 return BINARY_AND;
2169 case FloorDiv:
2170 return BINARY_FLOOR_DIVIDE;
2171 }
2172 return 0;
2173}
2174
2175static int
2176cmpop(cmpop_ty op)
2177{
2178 switch (op) {
2179 case Eq:
2180 return PyCmp_EQ;
2181 case NotEq:
2182 return PyCmp_NE;
2183 case Lt:
2184 return PyCmp_LT;
2185 case LtE:
2186 return PyCmp_LE;
2187 case Gt:
2188 return PyCmp_GT;
2189 case GtE:
2190 return PyCmp_GE;
2191 case Is:
2192 return PyCmp_IS;
2193 case IsNot:
2194 return PyCmp_IS_NOT;
2195 case In:
2196 return PyCmp_IN;
2197 case NotIn:
2198 return PyCmp_NOT_IN;
2199 }
2200 return PyCmp_BAD;
2201}
2202
2203static int
2204inplace_binop(struct compiler *c, operator_ty op)
2205{
2206 switch (op) {
2207 case Add:
2208 return INPLACE_ADD;
2209 case Sub:
2210 return INPLACE_SUBTRACT;
2211 case Mult:
2212 return INPLACE_MULTIPLY;
2213 case Div:
2214 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2215 return INPLACE_TRUE_DIVIDE;
2216 else
2217 return INPLACE_DIVIDE;
2218 case Mod:
2219 return INPLACE_MODULO;
2220 case Pow:
2221 return INPLACE_POWER;
2222 case LShift:
2223 return INPLACE_LSHIFT;
2224 case RShift:
2225 return INPLACE_RSHIFT;
2226 case BitOr:
2227 return INPLACE_OR;
2228 case BitXor:
2229 return INPLACE_XOR;
2230 case BitAnd:
2231 return INPLACE_AND;
2232 case FloorDiv:
2233 return INPLACE_FLOOR_DIVIDE;
2234 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002235 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002236 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237 return 0;
2238}
2239
2240static int
2241compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2242{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002243 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2245
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002246 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002247 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 /* XXX AugStore isn't used anywhere! */
2249
2250 /* First check for assignment to __debug__. Param? */
2251 if ((ctx == Store || ctx == AugStore || ctx == Del)
2252 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2253 return compiler_error(c, "can not assign to __debug__");
2254 }
2255
Jeremy Hylton37075c52007-02-27 01:01:59 +00002256mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002257 if (!mangled)
2258 return 0;
2259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 op = 0;
2261 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002262 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 switch (scope) {
2264 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002265 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 optype = OP_DEREF;
2267 break;
2268 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002269 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 optype = OP_DEREF;
2271 break;
2272 case LOCAL:
2273 if (c->u->u_ste->ste_type == FunctionBlock)
2274 optype = OP_FAST;
2275 break;
2276 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002277 if (c->u->u_ste->ste_type == FunctionBlock &&
2278 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 optype = OP_GLOBAL;
2280 break;
2281 case GLOBAL_EXPLICIT:
2282 optype = OP_GLOBAL;
2283 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002284 default:
2285 /* scope can be 0 */
2286 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 }
2288
2289 /* XXX Leave assert here, but handle __doc__ and the like better */
2290 assert(scope || PyString_AS_STRING(name)[0] == '_');
2291
2292 switch (optype) {
2293 case OP_DEREF:
2294 switch (ctx) {
2295 case Load: op = LOAD_DEREF; break;
2296 case Store: op = STORE_DEREF; break;
2297 case AugLoad:
2298 case AugStore:
2299 break;
2300 case Del:
2301 PyErr_Format(PyExc_SyntaxError,
2302 "can not delete variable '%s' referenced "
2303 "in nested scope",
2304 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002305 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002308 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002309 PyErr_SetString(PyExc_SystemError,
2310 "param invalid for deref variable");
2311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 }
2313 break;
2314 case OP_FAST:
2315 switch (ctx) {
2316 case Load: op = LOAD_FAST; break;
2317 case Store: op = STORE_FAST; break;
2318 case Del: op = DELETE_FAST; break;
2319 case AugLoad:
2320 case AugStore:
2321 break;
2322 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002323 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002324 PyErr_SetString(PyExc_SystemError,
2325 "param invalid for local variable");
2326 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002328 ADDOP_O(c, op, mangled, varnames);
2329 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 return 1;
2331 case OP_GLOBAL:
2332 switch (ctx) {
2333 case Load: op = LOAD_GLOBAL; break;
2334 case Store: op = STORE_GLOBAL; break;
2335 case Del: op = DELETE_GLOBAL; break;
2336 case AugLoad:
2337 case AugStore:
2338 break;
2339 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002340 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002341 PyErr_SetString(PyExc_SystemError,
2342 "param invalid for global variable");
2343 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 }
2345 break;
2346 case OP_NAME:
2347 switch (ctx) {
2348 case Load: op = LOAD_NAME; break;
2349 case Store: op = STORE_NAME; break;
2350 case Del: op = DELETE_NAME; break;
2351 case AugLoad:
2352 case AugStore:
2353 break;
2354 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002355 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002356 PyErr_SetString(PyExc_SystemError,
2357 "param invalid for name variable");
2358 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 }
2360 break;
2361 }
2362
2363 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002364 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002365 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002366 if (arg < 0)
2367 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002368 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369}
2370
2371static int
2372compiler_boolop(struct compiler *c, expr_ty e)
2373{
2374 basicblock *end;
2375 int jumpi, i, n;
2376 asdl_seq *s;
2377
2378 assert(e->kind == BoolOp_kind);
2379 if (e->v.BoolOp.op == And)
2380 jumpi = JUMP_IF_FALSE;
2381 else
2382 jumpi = JUMP_IF_TRUE;
2383 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002384 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 return 0;
2386 s = e->v.BoolOp.values;
2387 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002388 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002390 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002391 ADDOP_JREL(c, jumpi, end);
2392 ADDOP(c, POP_TOP)
2393 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002394 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 compiler_use_next_block(c, end);
2396 return 1;
2397}
2398
2399static int
2400compiler_list(struct compiler *c, expr_ty e)
2401{
2402 int n = asdl_seq_LEN(e->v.List.elts);
2403 if (e->v.List.ctx == Store) {
2404 ADDOP_I(c, UNPACK_SEQUENCE, n);
2405 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002406 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 if (e->v.List.ctx == Load) {
2408 ADDOP_I(c, BUILD_LIST, n);
2409 }
2410 return 1;
2411}
2412
2413static int
2414compiler_tuple(struct compiler *c, expr_ty e)
2415{
2416 int n = asdl_seq_LEN(e->v.Tuple.elts);
2417 if (e->v.Tuple.ctx == Store) {
2418 ADDOP_I(c, UNPACK_SEQUENCE, n);
2419 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002420 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421 if (e->v.Tuple.ctx == Load) {
2422 ADDOP_I(c, BUILD_TUPLE, n);
2423 }
2424 return 1;
2425}
2426
2427static int
2428compiler_compare(struct compiler *c, expr_ty e)
2429{
2430 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002431 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432
2433 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2434 VISIT(c, expr, e->v.Compare.left);
2435 n = asdl_seq_LEN(e->v.Compare.ops);
2436 assert(n > 0);
2437 if (n > 1) {
2438 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002439 if (cleanup == NULL)
2440 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002441 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002442 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443 }
2444 for (i = 1; i < n; i++) {
2445 ADDOP(c, DUP_TOP);
2446 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002448 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002449 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2451 NEXT_BLOCK(c);
2452 ADDOP(c, POP_TOP);
2453 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002454 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002455 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002457 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002459 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 if (n > 1) {
2461 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002462 if (end == NULL)
2463 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 ADDOP_JREL(c, JUMP_FORWARD, end);
2465 compiler_use_next_block(c, cleanup);
2466 ADDOP(c, ROT_TWO);
2467 ADDOP(c, POP_TOP);
2468 compiler_use_next_block(c, end);
2469 }
2470 return 1;
2471}
2472
2473static int
2474compiler_call(struct compiler *c, expr_ty e)
2475{
2476 int n, code = 0;
2477
2478 VISIT(c, expr, e->v.Call.func);
2479 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002480 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002482 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2484 }
2485 if (e->v.Call.starargs) {
2486 VISIT(c, expr, e->v.Call.starargs);
2487 code |= 1;
2488 }
2489 if (e->v.Call.kwargs) {
2490 VISIT(c, expr, e->v.Call.kwargs);
2491 code |= 2;
2492 }
2493 switch (code) {
2494 case 0:
2495 ADDOP_I(c, CALL_FUNCTION, n);
2496 break;
2497 case 1:
2498 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2499 break;
2500 case 2:
2501 ADDOP_I(c, CALL_FUNCTION_KW, n);
2502 break;
2503 case 3:
2504 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2505 break;
2506 }
2507 return 1;
2508}
2509
2510static int
2511compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002512 asdl_seq *generators, int gen_index,
2513 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514{
2515 /* generate code for the iterator, then each of the ifs,
2516 and then write to the element */
2517
2518 comprehension_ty l;
2519 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002520 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
2522 start = compiler_new_block(c);
2523 skip = compiler_new_block(c);
2524 if_cleanup = compiler_new_block(c);
2525 anchor = compiler_new_block(c);
2526
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002527 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2528 anchor == NULL)
2529 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530
Anthony Baxter7b782b62006-04-11 12:01:56 +00002531 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 VISIT(c, expr, l->iter);
2533 ADDOP(c, GET_ITER);
2534 compiler_use_next_block(c, start);
2535 ADDOP_JREL(c, FOR_ITER, anchor);
2536 NEXT_BLOCK(c);
2537 VISIT(c, expr, l->target);
2538
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540 n = asdl_seq_LEN(l->ifs);
2541 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002542 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 VISIT(c, expr, e);
2544 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2545 NEXT_BLOCK(c);
2546 ADDOP(c, POP_TOP);
2547 }
2548
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002549 if (++gen_index < asdl_seq_LEN(generators))
2550 if (!compiler_listcomp_generator(c, tmpname,
2551 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002554 /* only append after the last for generator */
2555 if (gen_index >= asdl_seq_LEN(generators)) {
2556 if (!compiler_nameop(c, tmpname, Load))
2557 return 0;
2558 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002559 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002560
2561 compiler_use_next_block(c, skip);
2562 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563 for (i = 0; i < n; i++) {
2564 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002565 if (i == 0)
2566 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 ADDOP(c, POP_TOP);
2568 }
2569 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2570 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002571 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002573 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574 return 0;
2575
2576 return 1;
2577}
2578
2579static int
2580compiler_listcomp(struct compiler *c, expr_ty e)
2581{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 asdl_seq *generators = e->v.ListComp.generators;
2585
2586 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002587 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 if (!tmp)
2589 return 0;
2590 ADDOP_I(c, BUILD_LIST, 0);
2591 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2594 e->v.ListComp.elt);
2595 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 return rc;
2597}
2598
2599static int
2600compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 asdl_seq *generators, int gen_index,
2602 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603{
2604 /* generate code for the iterator, then each of the ifs,
2605 and then write to the element */
2606
2607 comprehension_ty ge;
2608 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
2611 start = compiler_new_block(c);
2612 skip = compiler_new_block(c);
2613 if_cleanup = compiler_new_block(c);
2614 anchor = compiler_new_block(c);
2615 end = compiler_new_block(c);
2616
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 anchor == NULL || end == NULL)
2619 return 0;
2620
Anthony Baxter7b782b62006-04-11 12:01:56 +00002621 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 ADDOP_JREL(c, SETUP_LOOP, end);
2623 if (!compiler_push_fblock(c, LOOP, start))
2624 return 0;
2625
2626 if (gen_index == 0) {
2627 /* Receive outermost iter as an implicit argument */
2628 c->u->u_argcount = 1;
2629 ADDOP_I(c, LOAD_FAST, 0);
2630 }
2631 else {
2632 /* Sub-iter - calculate on the fly */
2633 VISIT(c, expr, ge->iter);
2634 ADDOP(c, GET_ITER);
2635 }
2636 compiler_use_next_block(c, start);
2637 ADDOP_JREL(c, FOR_ITER, anchor);
2638 NEXT_BLOCK(c);
2639 VISIT(c, expr, ge->target);
2640
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002641 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 n = asdl_seq_LEN(ge->ifs);
2643 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002644 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 VISIT(c, expr, e);
2646 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2647 NEXT_BLOCK(c);
2648 ADDOP(c, POP_TOP);
2649 }
2650
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2653 return 0;
2654
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 /* only append after the last 'for' generator */
2656 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 VISIT(c, expr, elt);
2658 ADDOP(c, YIELD_VALUE);
2659 ADDOP(c, POP_TOP);
2660
2661 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 for (i = 0; i < n; i++) {
2664 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 compiler_use_next_block(c, if_cleanup);
2667
2668 ADDOP(c, POP_TOP);
2669 }
2670 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2671 compiler_use_next_block(c, anchor);
2672 ADDOP(c, POP_BLOCK);
2673 compiler_pop_fblock(c, LOOP, start);
2674 compiler_use_next_block(c, end);
2675
2676 return 1;
2677}
2678
2679static int
2680compiler_genexp(struct compiler *c, expr_ty e)
2681{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002682 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 PyCodeObject *co;
2684 expr_ty outermost_iter = ((comprehension_ty)
2685 (asdl_seq_GET(e->v.GeneratorExp.generators,
2686 0)))->iter;
2687
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002688 if (!name) {
2689 name = PyString_FromString("<genexpr>");
2690 if (!name)
2691 return 0;
2692 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
2694 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2695 return 0;
2696 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2697 e->v.GeneratorExp.elt);
2698 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002699 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 if (co == NULL)
2701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002704 Py_DECREF(co);
2705
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 VISIT(c, expr, outermost_iter);
2707 ADDOP(c, GET_ITER);
2708 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
2710 return 1;
2711}
2712
2713static int
2714compiler_visit_keyword(struct compiler *c, keyword_ty k)
2715{
2716 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2717 VISIT(c, expr, k->value);
2718 return 1;
2719}
2720
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 whether they are true or false.
2723
2724 Return values: 1 for true, 0 for false, -1 for non-constant.
2725 */
2726
2727static int
2728expr_constant(expr_ty e)
2729{
2730 switch (e->kind) {
2731 case Num_kind:
2732 return PyObject_IsTrue(e->v.Num.n);
2733 case Str_kind:
2734 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002735 case Name_kind:
2736 /* __debug__ is not assignable, so we can optimize
2737 * it away in if and while statements */
2738 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002739 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002740 return ! Py_OptimizeFlag;
2741 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742 default:
2743 return -1;
2744 }
2745}
2746
Guido van Rossumc2e20742006-02-27 22:32:47 +00002747/*
2748 Implements the with statement from PEP 343.
2749
2750 The semantics outlined in that PEP are as follows:
2751
2752 with EXPR as VAR:
2753 BLOCK
2754
2755 It is implemented roughly as:
2756
Guido van Rossumda5b7012006-05-02 19:47:52 +00002757 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002758 exit = context.__exit__ # not calling it
2759 value = context.__enter__()
2760 try:
2761 VAR = value # if VAR present in the syntax
2762 BLOCK
2763 finally:
2764 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002765 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002766 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002767 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002768 exit(*exc)
2769 */
2770static int
2771compiler_with(struct compiler *c, stmt_ty s)
2772{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002773 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002774 basicblock *block, *finally;
2775 identifier tmpexit, tmpvalue = NULL;
2776
2777 assert(s->kind == With_kind);
2778
Guido van Rossumc2e20742006-02-27 22:32:47 +00002779 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002780 enter_attr = PyString_InternFromString("__enter__");
2781 if (!enter_attr)
2782 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002783 }
2784 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002785 exit_attr = PyString_InternFromString("__exit__");
2786 if (!exit_attr)
2787 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002788 }
2789
2790 block = compiler_new_block(c);
2791 finally = compiler_new_block(c);
2792 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002793 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002794
2795 /* Create a temporary variable to hold context.__exit__ */
2796 tmpexit = compiler_new_tmpname(c);
2797 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002798 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002799 PyArena_AddPyObject(c->c_arena, tmpexit);
2800
2801 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002803 We need to do this rather than preserving it on the stack
2804 because SETUP_FINALLY remembers the stack level.
2805 We need to do the assignment *inside* the try/finally
2806 so that context.__exit__() is called when the assignment
2807 fails. But we need to call context.__enter__() *before*
2808 the try/finally so that if it fails we won't call
2809 context.__exit__().
2810 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002811 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812 if (tmpvalue == NULL)
2813 return 0;
2814 PyArena_AddPyObject(c->c_arena, tmpvalue);
2815 }
2816
Guido van Rossumda5b7012006-05-02 19:47:52 +00002817 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819
2820 /* Squirrel away context.__exit__ */
2821 ADDOP(c, DUP_TOP);
2822 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2823 if (!compiler_nameop(c, tmpexit, Store))
2824 return 0;
2825
2826 /* Call context.__enter__() */
2827 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2828 ADDOP_I(c, CALL_FUNCTION, 0);
2829
2830 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002831 /* Store it in tmpvalue */
2832 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002833 return 0;
2834 }
2835 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 /* Discard result from context.__enter__() */
2837 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838 }
2839
2840 /* Start the try block */
2841 ADDOP_JREL(c, SETUP_FINALLY, finally);
2842
2843 compiler_use_next_block(c, block);
2844 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002846 }
2847
2848 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002849 /* Bind saved result of context.__enter__() to VAR */
2850 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851 !compiler_nameop(c, tmpvalue, Del))
2852 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002853 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854 }
2855
2856 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002857 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002858
2859 /* End of try block; start the finally block */
2860 ADDOP(c, POP_BLOCK);
2861 compiler_pop_fblock(c, FINALLY_TRY, block);
2862
2863 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2864 compiler_use_next_block(c, finally);
2865 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002867
2868 /* Finally block starts; push tmpexit and issue our magic opcode. */
2869 if (!compiler_nameop(c, tmpexit, Load) ||
2870 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002872 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873
2874 /* Finally block ends. */
2875 ADDOP(c, END_FINALLY);
2876 compiler_pop_fblock(c, FINALLY_END, finally);
2877 return 1;
2878}
2879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880static int
2881compiler_visit_expr(struct compiler *c, expr_ty e)
2882{
2883 int i, n;
2884
Neal Norwitzf733a012006-10-29 18:30:10 +00002885 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002886 set a new line number for the next instruction.
2887 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888 if (e->lineno > c->u->u_lineno) {
2889 c->u->u_lineno = e->lineno;
2890 c->u->u_lineno_set = false;
2891 }
2892 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002895 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896 VISIT(c, expr, e->v.BinOp.left);
2897 VISIT(c, expr, e->v.BinOp.right);
2898 ADDOP(c, binop(c, e->v.BinOp.op));
2899 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 VISIT(c, expr, e->v.UnaryOp.operand);
2902 ADDOP(c, unaryop(e->v.UnaryOp.op));
2903 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002904 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002906 case IfExp_kind:
2907 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002908 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909 /* XXX get rid of arg? */
2910 ADDOP_I(c, BUILD_MAP, 0);
2911 n = asdl_seq_LEN(e->v.Dict.values);
2912 /* We must arrange things just right for STORE_SUBSCR.
2913 It wants the stack to look like (value) (dict) (key) */
2914 for (i = 0; i < n; i++) {
2915 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002916 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002917 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002919 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002920 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 ADDOP(c, STORE_SUBSCR);
2922 }
2923 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002924 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 return compiler_genexp(c, e);
2928 case Yield_kind:
2929 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 if (e->v.Yield.value) {
2932 VISIT(c, expr, e->v.Yield.value);
2933 }
2934 else {
2935 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2936 }
2937 ADDOP(c, YIELD_VALUE);
2938 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002939 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002941 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 VISIT(c, expr, e->v.Repr.value);
2945 ADDOP(c, UNARY_CONVERT);
2946 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002947 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2949 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2952 break;
2953 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002954 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 if (e->v.Attribute.ctx != AugStore)
2956 VISIT(c, expr, e->v.Attribute.value);
2957 switch (e->v.Attribute.ctx) {
2958 case AugLoad:
2959 ADDOP(c, DUP_TOP);
2960 /* Fall through to load */
2961 case Load:
2962 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2963 break;
2964 case AugStore:
2965 ADDOP(c, ROT_TWO);
2966 /* Fall through to save */
2967 case Store:
2968 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2969 break;
2970 case Del:
2971 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2972 break;
2973 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002974 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002975 PyErr_SetString(PyExc_SystemError,
2976 "param invalid in attribute expression");
2977 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 }
2979 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002980 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981 switch (e->v.Subscript.ctx) {
2982 case AugLoad:
2983 VISIT(c, expr, e->v.Subscript.value);
2984 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2985 break;
2986 case Load:
2987 VISIT(c, expr, e->v.Subscript.value);
2988 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2989 break;
2990 case AugStore:
2991 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2992 break;
2993 case Store:
2994 VISIT(c, expr, e->v.Subscript.value);
2995 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2996 break;
2997 case Del:
2998 VISIT(c, expr, e->v.Subscript.value);
2999 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3000 break;
3001 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003002 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003003 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003004 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003005 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006 }
3007 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003008 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003009 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3010 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003011 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003013 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 return compiler_tuple(c, e);
3015 }
3016 return 1;
3017}
3018
3019static int
3020compiler_augassign(struct compiler *c, stmt_ty s)
3021{
3022 expr_ty e = s->v.AugAssign.target;
3023 expr_ty auge;
3024
3025 assert(s->kind == AugAssign_kind);
3026
3027 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003028 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003030 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003031 if (auge == NULL)
3032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 VISIT(c, expr, auge);
3034 VISIT(c, expr, s->v.AugAssign.value);
3035 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3036 auge->v.Attribute.ctx = AugStore;
3037 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 break;
3039 case Subscript_kind:
3040 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003041 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 if (auge == NULL)
3043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 VISIT(c, expr, auge);
3045 VISIT(c, expr, s->v.AugAssign.value);
3046 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003047 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003048 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003051 if (!compiler_nameop(c, e->v.Name.id, Load))
3052 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 VISIT(c, expr, s->v.AugAssign.value);
3054 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3055 return compiler_nameop(c, e->v.Name.id, Store);
3056 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003057 PyErr_Format(PyExc_SystemError,
3058 "invalid node type (%d) for augmented assignment",
3059 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003060 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061 }
3062 return 1;
3063}
3064
3065static int
3066compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3067{
3068 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003069 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3070 PyErr_SetString(PyExc_SystemError,
3071 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 f = &c->u->u_fblock[c->u->u_nfblocks++];
3075 f->fb_type = t;
3076 f->fb_block = b;
3077 return 1;
3078}
3079
3080static void
3081compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3082{
3083 struct compiler_unit *u = c->u;
3084 assert(u->u_nfblocks > 0);
3085 u->u_nfblocks--;
3086 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3087 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3088}
3089
Jeremy Hylton82271f12006-10-04 02:24:52 +00003090static int
3091compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003092 int i;
3093 struct compiler_unit *u = c->u;
3094 for (i = 0; i < u->u_nfblocks; ++i) {
3095 if (u->u_fblock[i].fb_type == LOOP)
3096 return 1;
3097 }
3098 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003099}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003100/* Raises a SyntaxError and returns 0.
3101 If something goes wrong, a different exception may be raised.
3102*/
3103
3104static int
3105compiler_error(struct compiler *c, const char *errstr)
3106{
3107 PyObject *loc;
3108 PyObject *u = NULL, *v = NULL;
3109
3110 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3111 if (!loc) {
3112 Py_INCREF(Py_None);
3113 loc = Py_None;
3114 }
3115 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3116 Py_None, loc);
3117 if (!u)
3118 goto exit;
3119 v = Py_BuildValue("(zO)", errstr, u);
3120 if (!v)
3121 goto exit;
3122 PyErr_SetObject(PyExc_SyntaxError, v);
3123 exit:
3124 Py_DECREF(loc);
3125 Py_XDECREF(u);
3126 Py_XDECREF(v);
3127 return 0;
3128}
3129
3130static int
3131compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003132 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003136 /* XXX this code is duplicated */
3137 switch (ctx) {
3138 case AugLoad: /* fall through to Load */
3139 case Load: op = BINARY_SUBSCR; break;
3140 case AugStore:/* fall through to Store */
3141 case Store: op = STORE_SUBSCR; break;
3142 case Del: op = DELETE_SUBSCR; break;
3143 case Param:
3144 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003145 "invalid %s kind %d in subscript\n",
3146 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 return 0;
3148 }
3149 if (ctx == AugLoad) {
3150 ADDOP_I(c, DUP_TOPX, 2);
3151 }
3152 else if (ctx == AugStore) {
3153 ADDOP(c, ROT_THREE);
3154 }
3155 ADDOP(c, op);
3156 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157}
3158
3159static int
3160compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3161{
3162 int n = 2;
3163 assert(s->kind == Slice_kind);
3164
3165 /* only handles the cases where BUILD_SLICE is emitted */
3166 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 }
3169 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003170 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003174 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175 }
3176 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 }
3179
3180 if (s->v.Slice.step) {
3181 n++;
3182 VISIT(c, expr, s->v.Slice.step);
3183 }
3184 ADDOP_I(c, BUILD_SLICE, n);
3185 return 1;
3186}
3187
3188static int
3189compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3190{
3191 int op = 0, slice_offset = 0, stack_count = 0;
3192
3193 assert(s->v.Slice.step == NULL);
3194 if (s->v.Slice.lower) {
3195 slice_offset++;
3196 stack_count++;
3197 if (ctx != AugStore)
3198 VISIT(c, expr, s->v.Slice.lower);
3199 }
3200 if (s->v.Slice.upper) {
3201 slice_offset += 2;
3202 stack_count++;
3203 if (ctx != AugStore)
3204 VISIT(c, expr, s->v.Slice.upper);
3205 }
3206
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 if (ctx == AugLoad) {
3208 switch (stack_count) {
3209 case 0: ADDOP(c, DUP_TOP); break;
3210 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3211 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3212 }
3213 }
3214 else if (ctx == AugStore) {
3215 switch (stack_count) {
3216 case 0: ADDOP(c, ROT_TWO); break;
3217 case 1: ADDOP(c, ROT_THREE); break;
3218 case 2: ADDOP(c, ROT_FOUR); break;
3219 }
3220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221
3222 switch (ctx) {
3223 case AugLoad: /* fall through to Load */
3224 case Load: op = SLICE; break;
3225 case AugStore:/* fall through to Store */
3226 case Store: op = STORE_SLICE; break;
3227 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003228 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003229 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003230 PyErr_SetString(PyExc_SystemError,
3231 "param invalid in simple slice");
3232 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233 }
3234
3235 ADDOP(c, op + slice_offset);
3236 return 1;
3237}
3238
3239static int
3240compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3241 expr_context_ty ctx)
3242{
3243 switch (s->kind) {
3244 case Ellipsis_kind:
3245 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3246 break;
3247 case Slice_kind:
3248 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249 case Index_kind:
3250 VISIT(c, expr, s->v.Index.value);
3251 break;
3252 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003253 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003254 PyErr_SetString(PyExc_SystemError,
3255 "extended slice invalid in nested slice");
3256 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 }
3258 return 1;
3259}
3260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261static int
3262compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3263{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003264 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003266 case Index_kind:
3267 kindname = "index";
3268 if (ctx != AugStore) {
3269 VISIT(c, expr, s->v.Index.value);
3270 }
3271 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003273 kindname = "ellipsis";
3274 if (ctx != AugStore) {
3275 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3276 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 break;
3278 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003279 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 if (!s->v.Slice.step)
3281 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003282 if (ctx != AugStore) {
3283 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 return 0;
3285 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003286 break;
3287 case ExtSlice_kind:
3288 kindname = "extended slice";
3289 if (ctx != AugStore) {
3290 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3291 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003292 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003293 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003294 if (!compiler_visit_nested_slice(c, sub, ctx))
3295 return 0;
3296 }
3297 ADDOP_I(c, BUILD_TUPLE, n);
3298 }
3299 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003300 default:
3301 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003302 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003303 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003305 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306}
3307
Neal Norwitzf733a012006-10-29 18:30:10 +00003308
3309/* End of the compiler section, beginning of the assembler section */
3310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311/* do depth-first search of basic block graph, starting with block.
3312 post records the block indices in post-order.
3313
3314 XXX must handle implicit jumps from one block to next
3315*/
3316
Neal Norwitzf733a012006-10-29 18:30:10 +00003317struct assembler {
3318 PyObject *a_bytecode; /* string containing bytecode */
3319 int a_offset; /* offset into bytecode */
3320 int a_nblocks; /* number of reachable blocks */
3321 basicblock **a_postorder; /* list of blocks in dfs postorder */
3322 PyObject *a_lnotab; /* string containing lnotab */
3323 int a_lnotab_off; /* offset into lnotab */
3324 int a_lineno; /* last lineno of emitted instruction */
3325 int a_lineno_off; /* bytecode offset of last lineno */
3326};
3327
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328static void
3329dfs(struct compiler *c, basicblock *b, struct assembler *a)
3330{
3331 int i;
3332 struct instr *instr = NULL;
3333
3334 if (b->b_seen)
3335 return;
3336 b->b_seen = 1;
3337 if (b->b_next != NULL)
3338 dfs(c, b->b_next, a);
3339 for (i = 0; i < b->b_iused; i++) {
3340 instr = &b->b_instr[i];
3341 if (instr->i_jrel || instr->i_jabs)
3342 dfs(c, instr->i_target, a);
3343 }
3344 a->a_postorder[a->a_nblocks++] = b;
3345}
3346
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003347static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003348stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3349{
3350 int i;
3351 struct instr *instr;
3352 if (b->b_seen || b->b_startdepth >= depth)
3353 return maxdepth;
3354 b->b_seen = 1;
3355 b->b_startdepth = depth;
3356 for (i = 0; i < b->b_iused; i++) {
3357 instr = &b->b_instr[i];
3358 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3359 if (depth > maxdepth)
3360 maxdepth = depth;
3361 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3362 if (instr->i_jrel || instr->i_jabs) {
3363 maxdepth = stackdepth_walk(c, instr->i_target,
3364 depth, maxdepth);
3365 if (instr->i_opcode == JUMP_ABSOLUTE ||
3366 instr->i_opcode == JUMP_FORWARD) {
3367 goto out; /* remaining code is dead */
3368 }
3369 }
3370 }
3371 if (b->b_next)
3372 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3373out:
3374 b->b_seen = 0;
3375 return maxdepth;
3376}
3377
3378/* Find the flow path that needs the largest stack. We assume that
3379 * cycles in the flow graph have no net effect on the stack depth.
3380 */
3381static int
3382stackdepth(struct compiler *c)
3383{
3384 basicblock *b, *entryblock;
3385 entryblock = NULL;
3386 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3387 b->b_seen = 0;
3388 b->b_startdepth = INT_MIN;
3389 entryblock = b;
3390 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003391 if (!entryblock)
3392 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 return stackdepth_walk(c, entryblock, 0, 0);
3394}
3395
3396static int
3397assemble_init(struct assembler *a, int nblocks, int firstlineno)
3398{
3399 memset(a, 0, sizeof(struct assembler));
3400 a->a_lineno = firstlineno;
3401 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3402 if (!a->a_bytecode)
3403 return 0;
3404 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3405 if (!a->a_lnotab)
3406 return 0;
3407 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003408 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003409 if (!a->a_postorder) {
3410 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003412 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003413 return 1;
3414}
3415
3416static void
3417assemble_free(struct assembler *a)
3418{
3419 Py_XDECREF(a->a_bytecode);
3420 Py_XDECREF(a->a_lnotab);
3421 if (a->a_postorder)
3422 PyObject_Free(a->a_postorder);
3423}
3424
3425/* Return the size of a basic block in bytes. */
3426
3427static int
3428instrsize(struct instr *instr)
3429{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003430 if (!instr->i_hasarg)
3431 return 1;
3432 if (instr->i_oparg > 0xffff)
3433 return 6;
3434 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003435}
3436
3437static int
3438blocksize(basicblock *b)
3439{
3440 int i;
3441 int size = 0;
3442
3443 for (i = 0; i < b->b_iused; i++)
3444 size += instrsize(&b->b_instr[i]);
3445 return size;
3446}
3447
3448/* All about a_lnotab.
3449
3450c_lnotab is an array of unsigned bytes disguised as a Python string.
3451It is used to map bytecode offsets to source code line #s (when needed
3452for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003453
Tim Peters2a7f3842001-06-09 09:26:21 +00003454The array is conceptually a list of
3455 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003456pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003457
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003458 byte code offset source code line number
3459 0 1
3460 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003461 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003462 350 307
3463 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003464
3465The first trick is that these numbers aren't stored, only the increments
3466from one row to the next (this doesn't really work, but it's a start):
3467
3468 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3469
3470The second trick is that an unsigned byte can't hold negative values, or
3471values larger than 255, so (a) there's a deep assumption that byte code
3472offsets and their corresponding line #s both increase monotonically, and (b)
3473if at least one column jumps by more than 255 from one row to the next, more
3474than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003475from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003476part. A user of c_lnotab desiring to find the source line number
3477corresponding to a bytecode address A should do something like this
3478
3479 lineno = addr = 0
3480 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003481 addr += addr_incr
3482 if addr > A:
3483 return lineno
3484 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003485
3486In order for this to work, when the addr field increments by more than 255,
3487the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003488increment is < 256. So, in the example above, assemble_lnotab (it used
3489to be called com_set_lineno) should not (as was actually done until 2.2)
3490expand 300, 300 to 255, 255, 45, 45,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003491 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003492*/
3493
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003494static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003496{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 int d_bytecode, d_lineno;
3498 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003499 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500
3501 d_bytecode = a->a_offset - a->a_lineno_off;
3502 d_lineno = i->i_lineno - a->a_lineno;
3503
3504 assert(d_bytecode >= 0);
3505 assert(d_lineno >= 0);
3506
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003507 /* XXX(nnorwitz): is there a better way to handle this?
3508 for loops are special, we want to be able to trace them
3509 each time around, so we need to set an extra line number. */
3510 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003511 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003514 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515 nbytes = a->a_lnotab_off + 2 * ncodes;
3516 len = PyString_GET_SIZE(a->a_lnotab);
3517 if (nbytes >= len) {
3518 if (len * 2 < nbytes)
3519 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003520 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 len *= 2;
3522 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3523 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003524 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003525 lnotab = (unsigned char *)
3526 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003527 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 *lnotab++ = 255;
3529 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 d_bytecode -= ncodes * 255;
3532 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003533 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 assert(d_bytecode <= 255);
3535 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003536 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 nbytes = a->a_lnotab_off + 2 * ncodes;
3538 len = PyString_GET_SIZE(a->a_lnotab);
3539 if (nbytes >= len) {
3540 if (len * 2 < nbytes)
3541 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003542 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 len *= 2;
3544 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3545 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003546 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003547 lnotab = (unsigned char *)
3548 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003550 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003552 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003554 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003555 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 d_lineno -= ncodes * 255;
3557 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003558 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 len = PyString_GET_SIZE(a->a_lnotab);
3561 if (a->a_lnotab_off + 2 >= len) {
3562 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003563 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003564 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003565 lnotab = (unsigned char *)
3566 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003567
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 a->a_lnotab_off += 2;
3569 if (d_bytecode) {
3570 *lnotab++ = d_bytecode;
3571 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003572 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003573 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574 *lnotab++ = 0;
3575 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003576 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 a->a_lineno = i->i_lineno;
3578 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003579 return 1;
3580}
3581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582/* assemble_emit()
3583 Extend the bytecode with a new instruction.
3584 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003585*/
3586
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003587static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003589{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003590 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003591 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 char *code;
3593
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003594 size = instrsize(i);
3595 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003597 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003598 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003600 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 if (a->a_offset + size >= len) {
3602 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003603 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3606 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003607 if (size == 6) {
3608 assert(i->i_hasarg);
3609 *code++ = (char)EXTENDED_ARG;
3610 *code++ = ext & 0xff;
3611 *code++ = ext >> 8;
3612 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003615 if (i->i_hasarg) {
3616 assert(size == 3 || size == 6);
3617 *code++ = arg & 0xff;
3618 *code++ = arg >> 8;
3619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003621}
3622
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003623static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003625{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003627 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003628 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003629
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 /* Compute the size of each block and fixup jump args.
3631 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003632start:
3633 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003635 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 bsize = blocksize(b);
3637 b->b_offset = totsize;
3638 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003639 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003640 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3642 bsize = b->b_offset;
3643 for (i = 0; i < b->b_iused; i++) {
3644 struct instr *instr = &b->b_instr[i];
3645 /* Relative jumps are computed relative to
3646 the instruction pointer after fetching
3647 the jump instruction.
3648 */
3649 bsize += instrsize(instr);
3650 if (instr->i_jabs)
3651 instr->i_oparg = instr->i_target->b_offset;
3652 else if (instr->i_jrel) {
3653 int delta = instr->i_target->b_offset - bsize;
3654 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003655 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003656 else
3657 continue;
3658 if (instr->i_oparg > 0xffff)
3659 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003660 }
3661 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003662
3663 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003664 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003665 with a better solution.
3666
3667 In the meantime, should the goto be dropped in favor
3668 of a loop?
3669
3670 The issue is that in the first loop blocksize() is called
3671 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003672 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003673 i_oparg is calculated in the second loop above.
3674
3675 So we loop until we stop seeing new EXTENDED_ARGs.
3676 The only EXTENDED_ARGs that could be popping up are
3677 ones in jump instructions. So this should converge
3678 fairly quickly.
3679 */
3680 if (last_extended_arg_count != extended_arg_count) {
3681 last_extended_arg_count = extended_arg_count;
3682 goto start;
3683 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003684}
3685
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003686static PyObject *
3687dict_keys_inorder(PyObject *dict, int offset)
3688{
3689 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003690 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003691
3692 tuple = PyTuple_New(size);
3693 if (tuple == NULL)
3694 return NULL;
3695 while (PyDict_Next(dict, &pos, &k, &v)) {
3696 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003697 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003698 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003699 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003700 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003701 PyTuple_SET_ITEM(tuple, i - offset, k);
3702 }
3703 return tuple;
3704}
3705
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003706static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003708{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709 PySTEntryObject *ste = c->u->u_ste;
3710 int flags = 0, n;
3711 if (ste->ste_type != ModuleBlock)
3712 flags |= CO_NEWLOCALS;
3713 if (ste->ste_type == FunctionBlock) {
3714 if (!ste->ste_unoptimized)
3715 flags |= CO_OPTIMIZED;
3716 if (ste->ste_nested)
3717 flags |= CO_NESTED;
3718 if (ste->ste_generator)
3719 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003720 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 if (ste->ste_varargs)
3722 flags |= CO_VARARGS;
3723 if (ste->ste_varkeywords)
3724 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003725 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003727
3728 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003729 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 n = PyDict_Size(c->u->u_freevars);
3732 if (n < 0)
3733 return -1;
3734 if (n == 0) {
3735 n = PyDict_Size(c->u->u_cellvars);
3736 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003737 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 if (n == 0) {
3739 flags |= CO_NOFREE;
3740 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003741 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003742
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003743 return flags;
3744}
3745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746static PyCodeObject *
3747makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003748{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749 PyObject *tmp;
3750 PyCodeObject *co = NULL;
3751 PyObject *consts = NULL;
3752 PyObject *names = NULL;
3753 PyObject *varnames = NULL;
3754 PyObject *filename = NULL;
3755 PyObject *name = NULL;
3756 PyObject *freevars = NULL;
3757 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003758 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 tmp = dict_keys_inorder(c->u->u_consts, 0);
3762 if (!tmp)
3763 goto error;
3764 consts = PySequence_List(tmp); /* optimize_code requires a list */
3765 Py_DECREF(tmp);
3766
3767 names = dict_keys_inorder(c->u->u_names, 0);
3768 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3769 if (!consts || !names || !varnames)
3770 goto error;
3771
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003772 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3773 if (!cellvars)
3774 goto error;
3775 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3776 if (!freevars)
3777 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 filename = PyString_FromString(c->c_filename);
3779 if (!filename)
3780 goto error;
3781
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003782 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783 flags = compute_code_flags(c);
3784 if (flags < 0)
3785 goto error;
3786
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003787 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788 if (!bytecode)
3789 goto error;
3790
3791 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3792 if (!tmp)
3793 goto error;
3794 Py_DECREF(consts);
3795 consts = tmp;
3796
3797 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3798 bytecode, consts, names, varnames,
3799 freevars, cellvars,
3800 filename, c->u->u_name,
3801 c->u->u_firstlineno,
3802 a->a_lnotab);
3803 error:
3804 Py_XDECREF(consts);
3805 Py_XDECREF(names);
3806 Py_XDECREF(varnames);
3807 Py_XDECREF(filename);
3808 Py_XDECREF(name);
3809 Py_XDECREF(freevars);
3810 Py_XDECREF(cellvars);
3811 Py_XDECREF(bytecode);
3812 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003813}
3814
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003815
3816/* For debugging purposes only */
3817#if 0
3818static void
3819dump_instr(const struct instr *i)
3820{
3821 const char *jrel = i->i_jrel ? "jrel " : "";
3822 const char *jabs = i->i_jabs ? "jabs " : "";
3823 char arg[128];
3824
3825 *arg = '\0';
3826 if (i->i_hasarg)
3827 sprintf(arg, "arg: %d ", i->i_oparg);
3828
3829 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3830 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3831}
3832
3833static void
3834dump_basicblock(const basicblock *b)
3835{
3836 const char *seen = b->b_seen ? "seen " : "";
3837 const char *b_return = b->b_return ? "return " : "";
3838 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3839 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3840 if (b->b_instr) {
3841 int i;
3842 for (i = 0; i < b->b_iused; i++) {
3843 fprintf(stderr, " [%02d] ", i);
3844 dump_instr(b->b_instr + i);
3845 }
3846 }
3847}
3848#endif
3849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850static PyCodeObject *
3851assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003852{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 basicblock *b, *entryblock;
3854 struct assembler a;
3855 int i, j, nblocks;
3856 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003858 /* Make sure every block that falls off the end returns None.
3859 XXX NEXT_BLOCK() isn't quite right, because if the last
3860 block ends with a jump or return b_next shouldn't set.
3861 */
3862 if (!c->u->u_curblock->b_return) {
3863 NEXT_BLOCK(c);
3864 if (addNone)
3865 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3866 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003867 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869 nblocks = 0;
3870 entryblock = NULL;
3871 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3872 nblocks++;
3873 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003874 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003875
Neal Norwitzed657552006-07-10 00:04:44 +00003876 /* Set firstlineno if it wasn't explicitly set. */
3877 if (!c->u->u_firstlineno) {
3878 if (entryblock && entryblock->b_instr)
3879 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3880 else
3881 c->u->u_firstlineno = 1;
3882 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3884 goto error;
3885 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003888 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003889
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 /* Emit code in reverse postorder from dfs. */
3891 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003892 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 for (j = 0; j < b->b_iused; j++)
3894 if (!assemble_emit(&a, &b->b_instr[j]))
3895 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003896 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3899 goto error;
3900 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3901 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003902
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903 co = makecode(c, &a);
3904 error:
3905 assemble_free(&a);
3906 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003907}