blob: 36ad8a48e0ec32d835e094b7d0be3a556d047a26 [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;
Raymond Hettingereffde122007-12-18 18:26:18 +0000732 case STORE_MAP:
733 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734 case DELETE_SUBSCR:
735 return -2;
736
737 case BINARY_LSHIFT:
738 case BINARY_RSHIFT:
739 case BINARY_AND:
740 case BINARY_XOR:
741 case BINARY_OR:
742 return -1;
743 case INPLACE_POWER:
744 return -1;
745 case GET_ITER:
746 return 0;
747
748 case PRINT_EXPR:
749 return -1;
750 case PRINT_ITEM:
751 return -1;
752 case PRINT_NEWLINE:
753 return 0;
754 case PRINT_ITEM_TO:
755 return -2;
756 case PRINT_NEWLINE_TO:
757 return -1;
758 case INPLACE_LSHIFT:
759 case INPLACE_RSHIFT:
760 case INPLACE_AND:
761 case INPLACE_XOR:
762 case INPLACE_OR:
763 return -1;
764 case BREAK_LOOP:
765 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000766 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000767 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768 case LOAD_LOCALS:
769 return 1;
770 case RETURN_VALUE:
771 return -1;
772 case IMPORT_STAR:
773 return -1;
774 case EXEC_STMT:
775 return -3;
776 case YIELD_VALUE:
777 return 0;
778
779 case POP_BLOCK:
780 return 0;
781 case END_FINALLY:
782 return -1; /* or -2 or -3 if exception occurred */
783 case BUILD_CLASS:
784 return -2;
785
786 case STORE_NAME:
787 return -1;
788 case DELETE_NAME:
789 return 0;
790 case UNPACK_SEQUENCE:
791 return oparg-1;
792 case FOR_ITER:
793 return 1;
794
795 case STORE_ATTR:
796 return -2;
797 case DELETE_ATTR:
798 return -1;
799 case STORE_GLOBAL:
800 return -1;
801 case DELETE_GLOBAL:
802 return 0;
803 case DUP_TOPX:
804 return oparg;
805 case LOAD_CONST:
806 return 1;
807 case LOAD_NAME:
808 return 1;
809 case BUILD_TUPLE:
810 case BUILD_LIST:
811 return 1-oparg;
812 case BUILD_MAP:
813 return 1;
814 case LOAD_ATTR:
815 return 0;
816 case COMPARE_OP:
817 return -1;
818 case IMPORT_NAME:
819 return 0;
820 case IMPORT_FROM:
821 return 1;
822
823 case JUMP_FORWARD:
824 case JUMP_IF_FALSE:
825 case JUMP_IF_TRUE:
826 case JUMP_ABSOLUTE:
827 return 0;
828
829 case LOAD_GLOBAL:
830 return 1;
831
832 case CONTINUE_LOOP:
833 return 0;
834 case SETUP_LOOP:
835 return 0;
836 case SETUP_EXCEPT:
837 case SETUP_FINALLY:
838 return 3; /* actually pushed by an exception */
839
840 case LOAD_FAST:
841 return 1;
842 case STORE_FAST:
843 return -1;
844 case DELETE_FAST:
845 return 0;
846
847 case RAISE_VARARGS:
848 return -oparg;
849#define NARGS(o) (((o) % 256) + 2*((o) / 256))
850 case CALL_FUNCTION:
851 return -NARGS(oparg);
852 case CALL_FUNCTION_VAR:
853 case CALL_FUNCTION_KW:
854 return -NARGS(oparg)-1;
855 case CALL_FUNCTION_VAR_KW:
856 return -NARGS(oparg)-2;
857#undef NARGS
858 case MAKE_FUNCTION:
859 return -oparg;
860 case BUILD_SLICE:
861 if (oparg == 3)
862 return -2;
863 else
864 return -1;
865
866 case MAKE_CLOSURE:
867 return -oparg;
868 case LOAD_CLOSURE:
869 return 1;
870 case LOAD_DEREF:
871 return 1;
872 case STORE_DEREF:
873 return -1;
874 default:
875 fprintf(stderr, "opcode = %d\n", opcode);
876 Py_FatalError("opcode_stack_effect()");
877
878 }
879 return 0; /* not reachable */
880}
881
882/* Add an opcode with no argument.
883 Returns 0 on failure, 1 on success.
884*/
885
886static int
887compiler_addop(struct compiler *c, int opcode)
888{
889 basicblock *b;
890 struct instr *i;
891 int off;
892 off = compiler_next_instr(c, c->u->u_curblock);
893 if (off < 0)
894 return 0;
895 b = c->u->u_curblock;
896 i = &b->b_instr[off];
897 i->i_opcode = opcode;
898 i->i_hasarg = 0;
899 if (opcode == RETURN_VALUE)
900 b->b_return = 1;
901 compiler_set_lineno(c, off);
902 return 1;
903}
904
905static int
906compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
907{
908 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000909 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000910
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000911 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000912 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
913 if (PyFloat_Check(o)) {
914 double d = PyFloat_AS_DOUBLE(o);
915 unsigned char* p = (unsigned char*) &d;
916 /* all we need is to make the tuple different in either the 0.0
917 * or -0.0 case from all others, just to avoid the "coercion".
918 */
919 if (*p==0 && p[sizeof(double)-1]==0)
920 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
921 else
922 t = PyTuple_Pack(2, o, o->ob_type);
923 } else {
924 t = PyTuple_Pack(2, o, o->ob_type);
925 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000926 if (t == NULL)
927 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000928
929 v = PyDict_GetItem(dict, t);
930 if (!v) {
931 arg = PyDict_Size(dict);
932 v = PyInt_FromLong(arg);
933 if (!v) {
934 Py_DECREF(t);
935 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000936 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937 if (PyDict_SetItem(dict, t, v) < 0) {
938 Py_DECREF(t);
939 Py_DECREF(v);
940 return -1;
941 }
942 Py_DECREF(v);
943 }
944 else
945 arg = PyInt_AsLong(v);
946 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000947 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948}
949
950static int
951compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
952 PyObject *o)
953{
954 int arg = compiler_add_o(c, dict, o);
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
960static int
961compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000962 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963{
964 int arg;
965 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
966 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 arg = compiler_add_o(c, dict, mangled);
969 Py_DECREF(mangled);
970 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 return compiler_addop_i(c, opcode, arg);
973}
974
975/* Add an opcode with an integer argument.
976 Returns 0 on failure, 1 on success.
977*/
978
979static int
980compiler_addop_i(struct compiler *c, int opcode, int oparg)
981{
982 struct instr *i;
983 int off;
984 off = compiler_next_instr(c, c->u->u_curblock);
985 if (off < 0)
986 return 0;
987 i = &c->u->u_curblock->b_instr[off];
988 i->i_opcode = opcode;
989 i->i_oparg = oparg;
990 i->i_hasarg = 1;
991 compiler_set_lineno(c, off);
992 return 1;
993}
994
995static int
996compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
997{
998 struct instr *i;
999 int off;
1000
1001 assert(b != NULL);
1002 off = compiler_next_instr(c, c->u->u_curblock);
1003 if (off < 0)
1004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 i = &c->u->u_curblock->b_instr[off];
1006 i->i_opcode = opcode;
1007 i->i_target = b;
1008 i->i_hasarg = 1;
1009 if (absolute)
1010 i->i_jabs = 1;
1011 else
1012 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001013 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014 return 1;
1015}
1016
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001017/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1018 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019 it as the current block. NEXT_BLOCK() also creates an implicit jump
1020 from the current block to the new block.
1021*/
1022
Neal Norwitzf733a012006-10-29 18:30:10 +00001023/* The returns inside these macros make it impossible to decref objects
1024 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025*/
1026
1027
1028#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001029 if (compiler_use_new_block((C)) == NULL) \
1030 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031}
1032
1033#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001034 if (compiler_next_block((C)) == NULL) \
1035 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036}
1037
1038#define ADDOP(C, OP) { \
1039 if (!compiler_addop((C), (OP))) \
1040 return 0; \
1041}
1042
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001043#define ADDOP_IN_SCOPE(C, OP) { \
1044 if (!compiler_addop((C), (OP))) { \
1045 compiler_exit_scope(c); \
1046 return 0; \
1047 } \
1048}
1049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050#define ADDOP_O(C, OP, O, TYPE) { \
1051 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1052 return 0; \
1053}
1054
1055#define ADDOP_NAME(C, OP, O, TYPE) { \
1056 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1057 return 0; \
1058}
1059
1060#define ADDOP_I(C, OP, O) { \
1061 if (!compiler_addop_i((C), (OP), (O))) \
1062 return 0; \
1063}
1064
1065#define ADDOP_JABS(C, OP, O) { \
1066 if (!compiler_addop_j((C), (OP), (O), 1)) \
1067 return 0; \
1068}
1069
1070#define ADDOP_JREL(C, OP, O) { \
1071 if (!compiler_addop_j((C), (OP), (O), 0)) \
1072 return 0; \
1073}
1074
1075/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1076 the ASDL name to synthesize the name of the C type and the visit function.
1077*/
1078
1079#define VISIT(C, TYPE, V) {\
1080 if (!compiler_visit_ ## TYPE((C), (V))) \
1081 return 0; \
1082}
1083
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001084#define VISIT_IN_SCOPE(C, TYPE, V) {\
1085 if (!compiler_visit_ ## TYPE((C), (V))) { \
1086 compiler_exit_scope(c); \
1087 return 0; \
1088 } \
1089}
1090
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091#define VISIT_SLICE(C, V, CTX) {\
1092 if (!compiler_visit_slice((C), (V), (CTX))) \
1093 return 0; \
1094}
1095
1096#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001097 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001099 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001100 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001101 if (!compiler_visit_ ## TYPE((C), elt)) \
1102 return 0; \
1103 } \
1104}
1105
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001106#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001107 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001108 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001109 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001110 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001111 if (!compiler_visit_ ## TYPE((C), elt)) { \
1112 compiler_exit_scope(c); \
1113 return 0; \
1114 } \
1115 } \
1116}
1117
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118static int
1119compiler_isdocstring(stmt_ty s)
1120{
1121 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001122 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123 return s->v.Expr.value->kind == Str_kind;
1124}
1125
1126/* Compile a sequence of statements, checking for a docstring. */
1127
1128static int
1129compiler_body(struct compiler *c, asdl_seq *stmts)
1130{
1131 int i = 0;
1132 stmt_ty st;
1133
1134 if (!asdl_seq_LEN(stmts))
1135 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001136 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001137 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1138 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 i = 1;
1140 VISIT(c, expr, st->v.Expr.value);
1141 if (!compiler_nameop(c, __doc__, Store))
1142 return 0;
1143 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001144 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001145 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 return 1;
1147}
1148
1149static PyCodeObject *
1150compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001151{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001152 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 static PyObject *module;
1155 if (!module) {
1156 module = PyString_FromString("<module>");
1157 if (!module)
1158 return NULL;
1159 }
Neal Norwitzed657552006-07-10 00:04:44 +00001160 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1161 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001162 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 switch (mod->kind) {
1164 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001165 if (!compiler_body(c, mod->v.Module.body)) {
1166 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001168 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 break;
1170 case Interactive_kind:
1171 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001172 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001173 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 break;
1175 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001176 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001177 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 break;
1179 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001180 PyErr_SetString(PyExc_SystemError,
1181 "suite should not be possible");
1182 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001184 PyErr_Format(PyExc_SystemError,
1185 "module kind %d should not be possible",
1186 mod->kind);
1187 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001188 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 co = assemble(c, addNone);
1190 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001191 return co;
1192}
1193
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194/* The test for LOCAL must come before the test for FREE in order to
1195 handle classes where name is both local and free. The local var is
1196 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001197*/
1198
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199static int
1200get_ref_type(struct compiler *c, PyObject *name)
1201{
1202 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001203 if (scope == 0) {
1204 char buf[350];
1205 PyOS_snprintf(buf, sizeof(buf),
1206 "unknown scope for %.100s in %.100s(%s) in %s\n"
1207 "symbols: %s\nlocals: %s\nglobals: %s\n",
1208 PyString_AS_STRING(name),
1209 PyString_AS_STRING(c->u->u_name),
1210 PyObject_REPR(c->u->u_ste->ste_id),
1211 c->c_filename,
1212 PyObject_REPR(c->u->u_ste->ste_symbols),
1213 PyObject_REPR(c->u->u_varnames),
1214 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001215 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001216 Py_FatalError(buf);
1217 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001218
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001219 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220}
1221
1222static int
1223compiler_lookup_arg(PyObject *dict, PyObject *name)
1224{
1225 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001226 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001228 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001230 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001232 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001233 return PyInt_AS_LONG(v);
1234}
1235
1236static int
1237compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1238{
1239 int i, free = PyCode_GetNumFree(co);
1240 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001241 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1242 ADDOP_I(c, MAKE_FUNCTION, args);
1243 return 1;
1244 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 for (i = 0; i < free; ++i) {
1246 /* Bypass com_addop_varname because it will generate
1247 LOAD_DEREF but LOAD_CLOSURE is needed.
1248 */
1249 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1250 int arg, reftype;
1251
1252 /* Special case: If a class contains a method with a
1253 free variable that has the same name as a method,
1254 the name will be considered free *and* local in the
1255 class. It should be handled by the closure, as
1256 well as by the normal name loookup logic.
1257 */
1258 reftype = get_ref_type(c, name);
1259 if (reftype == CELL)
1260 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1261 else /* (reftype == FREE) */
1262 arg = compiler_lookup_arg(c->u->u_freevars, name);
1263 if (arg == -1) {
1264 printf("lookup %s in %s %d %d\n"
1265 "freevars of %s: %s\n",
1266 PyObject_REPR(name),
1267 PyString_AS_STRING(c->u->u_name),
1268 reftype, arg,
1269 PyString_AS_STRING(co->co_name),
1270 PyObject_REPR(co->co_freevars));
1271 Py_FatalError("compiler_make_closure()");
1272 }
1273 ADDOP_I(c, LOAD_CLOSURE, arg);
1274 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001275 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001277 ADDOP_I(c, MAKE_CLOSURE, args);
1278 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281static int
1282compiler_decorators(struct compiler *c, asdl_seq* decos)
1283{
1284 int i;
1285
1286 if (!decos)
1287 return 1;
1288
1289 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001290 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001291 }
1292 return 1;
1293}
1294
1295static int
1296compiler_arguments(struct compiler *c, arguments_ty args)
1297{
1298 int i;
1299 int n = asdl_seq_LEN(args->args);
1300 /* Correctly handle nested argument lists */
1301 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001302 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303 if (arg->kind == Tuple_kind) {
1304 PyObject *id = PyString_FromFormat(".%d", i);
1305 if (id == NULL) {
1306 return 0;
1307 }
1308 if (!compiler_nameop(c, id, Load)) {
1309 Py_DECREF(id);
1310 return 0;
1311 }
1312 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001313 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001314 }
1315 }
1316 return 1;
1317}
1318
1319static int
1320compiler_function(struct compiler *c, stmt_ty s)
1321{
1322 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001323 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001324 arguments_ty args = s->v.FunctionDef.args;
1325 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001326 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327 int i, n, docstring;
1328
1329 assert(s->kind == FunctionDef_kind);
1330
1331 if (!compiler_decorators(c, decos))
1332 return 0;
1333 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001334 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1336 s->lineno))
1337 return 0;
1338
Anthony Baxter7b782b62006-04-11 12:01:56 +00001339 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001340 docstring = compiler_isdocstring(st);
Georg Brandl5a5bc7b2007-09-19 06:37:19 +00001341 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001342 first_const = st->v.Expr.value->v.Str.s;
1343 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001344 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001345 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001348 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001349 compiler_arguments(c, args);
1350
1351 c->u->u_argcount = asdl_seq_LEN(args->args);
1352 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001353 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001355 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1356 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 }
1358 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001359 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 if (co == NULL)
1361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001363 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001364 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365
1366 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1367 ADDOP_I(c, CALL_FUNCTION, 1);
1368 }
1369
1370 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1371}
1372
1373static int
1374compiler_class(struct compiler *c, stmt_ty s)
1375{
1376 int n;
1377 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001378 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 /* push class name on stack, needed by BUILD_CLASS */
1380 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1381 /* push the tuple of base classes on the stack */
1382 n = asdl_seq_LEN(s->v.ClassDef.bases);
1383 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001384 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 ADDOP_I(c, BUILD_TUPLE, n);
1386 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1387 s->lineno))
1388 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001389 c->u->u_private = s->v.ClassDef.name;
1390 Py_INCREF(c->u->u_private);
1391 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 if (!str || !compiler_nameop(c, str, Load)) {
1393 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001394 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001396 }
1397
1398 Py_DECREF(str);
1399 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001400 if (!str || !compiler_nameop(c, str, Store)) {
1401 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001402 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001403 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001404 }
1405 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001407 if (!compiler_body(c, s->v.ClassDef.body)) {
1408 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001410 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001412 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1413 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001415 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416 if (co == NULL)
1417 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001419 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001420 Py_DECREF(co);
1421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422 ADDOP_I(c, CALL_FUNCTION, 0);
1423 ADDOP(c, BUILD_CLASS);
1424 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1425 return 0;
1426 return 1;
1427}
1428
1429static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001430compiler_ifexp(struct compiler *c, expr_ty e)
1431{
1432 basicblock *end, *next;
1433
1434 assert(e->kind == IfExp_kind);
1435 end = compiler_new_block(c);
1436 if (end == NULL)
1437 return 0;
1438 next = compiler_new_block(c);
1439 if (next == NULL)
1440 return 0;
1441 VISIT(c, expr, e->v.IfExp.test);
1442 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1443 ADDOP(c, POP_TOP);
1444 VISIT(c, expr, e->v.IfExp.body);
1445 ADDOP_JREL(c, JUMP_FORWARD, end);
1446 compiler_use_next_block(c, next);
1447 ADDOP(c, POP_TOP);
1448 VISIT(c, expr, e->v.IfExp.orelse);
1449 compiler_use_next_block(c, end);
1450 return 1;
1451}
1452
1453static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454compiler_lambda(struct compiler *c, expr_ty e)
1455{
1456 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001457 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458 arguments_ty args = e->v.Lambda.args;
1459 assert(e->kind == Lambda_kind);
1460
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001461 if (!name) {
1462 name = PyString_InternFromString("<lambda>");
1463 if (!name)
1464 return 0;
1465 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466
1467 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001468 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1470 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001471
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001472 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 compiler_arguments(c, args);
1474
1475 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001476 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1477 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001479 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 if (co == NULL)
1481 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001483 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001484 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485
1486 return 1;
1487}
1488
1489static int
1490compiler_print(struct compiler *c, stmt_ty s)
1491{
1492 int i, n;
1493 bool dest;
1494
1495 assert(s->kind == Print_kind);
1496 n = asdl_seq_LEN(s->v.Print.values);
1497 dest = false;
1498 if (s->v.Print.dest) {
1499 VISIT(c, expr, s->v.Print.dest);
1500 dest = true;
1501 }
1502 for (i = 0; i < n; i++) {
1503 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1504 if (dest) {
1505 ADDOP(c, DUP_TOP);
1506 VISIT(c, expr, e);
1507 ADDOP(c, ROT_TWO);
1508 ADDOP(c, PRINT_ITEM_TO);
1509 }
1510 else {
1511 VISIT(c, expr, e);
1512 ADDOP(c, PRINT_ITEM);
1513 }
1514 }
1515 if (s->v.Print.nl) {
1516 if (dest)
1517 ADDOP(c, PRINT_NEWLINE_TO)
1518 else
1519 ADDOP(c, PRINT_NEWLINE)
1520 }
1521 else if (dest)
1522 ADDOP(c, POP_TOP);
1523 return 1;
1524}
1525
1526static int
1527compiler_if(struct compiler *c, stmt_ty s)
1528{
1529 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001530 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 assert(s->kind == If_kind);
1532 end = compiler_new_block(c);
1533 if (end == NULL)
1534 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001535 next = compiler_new_block(c);
1536 if (next == NULL)
1537 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001538
1539 constant = expr_constant(s->v.If.test);
1540 /* constant = 0: "if 0"
1541 * constant = 1: "if 1", "if 2", ...
1542 * constant = -1: rest */
1543 if (constant == 0) {
1544 if (s->v.If.orelse)
1545 VISIT_SEQ(c, stmt, s->v.If.orelse);
1546 } else if (constant == 1) {
1547 VISIT_SEQ(c, stmt, s->v.If.body);
1548 } else {
1549 VISIT(c, expr, s->v.If.test);
1550 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1551 ADDOP(c, POP_TOP);
1552 VISIT_SEQ(c, stmt, s->v.If.body);
1553 ADDOP_JREL(c, JUMP_FORWARD, end);
1554 compiler_use_next_block(c, next);
1555 ADDOP(c, POP_TOP);
1556 if (s->v.If.orelse)
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001557 VISIT_SEQ(c, stmt, s->v.If.orelse);
Georg Brandlddbaa662006-06-04 21:56:52 +00001558 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559 compiler_use_next_block(c, end);
1560 return 1;
1561}
1562
1563static int
1564compiler_for(struct compiler *c, stmt_ty s)
1565{
1566 basicblock *start, *cleanup, *end;
1567
1568 start = compiler_new_block(c);
1569 cleanup = compiler_new_block(c);
1570 end = compiler_new_block(c);
1571 if (start == NULL || end == NULL || cleanup == NULL)
1572 return 0;
1573 ADDOP_JREL(c, SETUP_LOOP, end);
1574 if (!compiler_push_fblock(c, LOOP, start))
1575 return 0;
1576 VISIT(c, expr, s->v.For.iter);
1577 ADDOP(c, GET_ITER);
1578 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001579 /* XXX(nnorwitz): is there a better way to handle this?
1580 for loops are special, we want to be able to trace them
1581 each time around, so we need to set an extra line number. */
1582 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001583 ADDOP_JREL(c, FOR_ITER, cleanup);
1584 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001585 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001586 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1587 compiler_use_next_block(c, cleanup);
1588 ADDOP(c, POP_BLOCK);
1589 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001590 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591 compiler_use_next_block(c, end);
1592 return 1;
1593}
1594
1595static int
1596compiler_while(struct compiler *c, stmt_ty s)
1597{
1598 basicblock *loop, *orelse, *end, *anchor = NULL;
1599 int constant = expr_constant(s->v.While.test);
1600
1601 if (constant == 0)
1602 return 1;
1603 loop = compiler_new_block(c);
1604 end = compiler_new_block(c);
1605 if (constant == -1) {
1606 anchor = compiler_new_block(c);
1607 if (anchor == NULL)
1608 return 0;
1609 }
1610 if (loop == NULL || end == NULL)
1611 return 0;
1612 if (s->v.While.orelse) {
1613 orelse = compiler_new_block(c);
1614 if (orelse == NULL)
1615 return 0;
1616 }
1617 else
1618 orelse = NULL;
1619
1620 ADDOP_JREL(c, SETUP_LOOP, end);
Nick Coghlanb90f52e2007-08-25 04:35:54 +00001621 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 if (!compiler_push_fblock(c, LOOP, loop))
1623 return 0;
1624 if (constant == -1) {
1625 VISIT(c, expr, s->v.While.test);
1626 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1627 ADDOP(c, POP_TOP);
1628 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001629 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1631
1632 /* XXX should the two POP instructions be in a separate block
1633 if there is no else clause ?
1634 */
1635
1636 if (constant == -1) {
1637 compiler_use_next_block(c, anchor);
1638 ADDOP(c, POP_TOP);
1639 ADDOP(c, POP_BLOCK);
1640 }
1641 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001642 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001643 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644 compiler_use_next_block(c, end);
1645
1646 return 1;
1647}
1648
1649static int
1650compiler_continue(struct compiler *c)
1651{
1652 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001653 static const char IN_FINALLY_ERROR_MSG[] =
1654 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 int i;
1656
1657 if (!c->u->u_nfblocks)
1658 return compiler_error(c, LOOP_ERROR_MSG);
1659 i = c->u->u_nfblocks - 1;
1660 switch (c->u->u_fblock[i].fb_type) {
1661 case LOOP:
1662 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1663 break;
1664 case EXCEPT:
1665 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001666 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1667 /* Prevent continue anywhere under a finally
1668 even if hidden in a sub-try or except. */
1669 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1670 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1671 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001672 if (i == -1)
1673 return compiler_error(c, LOOP_ERROR_MSG);
1674 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1675 break;
1676 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001677 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678 }
1679
1680 return 1;
1681}
1682
1683/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1684
1685 SETUP_FINALLY L
1686 <code for body>
1687 POP_BLOCK
1688 LOAD_CONST <None>
1689 L: <code for finalbody>
1690 END_FINALLY
1691
1692 The special instructions use the block stack. Each block
1693 stack entry contains the instruction that created it (here
1694 SETUP_FINALLY), the level of the value stack at the time the
1695 block stack entry was created, and a label (here L).
1696
1697 SETUP_FINALLY:
1698 Pushes the current value stack level and the label
1699 onto the block stack.
1700 POP_BLOCK:
1701 Pops en entry from the block stack, and pops the value
1702 stack until its level is the same as indicated on the
1703 block stack. (The label is ignored.)
1704 END_FINALLY:
1705 Pops a variable number of entries from the *value* stack
1706 and re-raises the exception they specify. The number of
1707 entries popped depends on the (pseudo) exception type.
1708
1709 The block stack is unwound when an exception is raised:
1710 when a SETUP_FINALLY entry is found, the exception is pushed
1711 onto the value stack (and the exception condition is cleared),
1712 and the interpreter jumps to the label gotten from the block
1713 stack.
1714*/
1715
1716static int
1717compiler_try_finally(struct compiler *c, stmt_ty s)
1718{
1719 basicblock *body, *end;
1720 body = compiler_new_block(c);
1721 end = compiler_new_block(c);
1722 if (body == NULL || end == NULL)
1723 return 0;
1724
1725 ADDOP_JREL(c, SETUP_FINALLY, end);
1726 compiler_use_next_block(c, body);
1727 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1728 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001729 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730 ADDOP(c, POP_BLOCK);
1731 compiler_pop_fblock(c, FINALLY_TRY, body);
1732
1733 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1734 compiler_use_next_block(c, end);
1735 if (!compiler_push_fblock(c, FINALLY_END, end))
1736 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001737 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001738 ADDOP(c, END_FINALLY);
1739 compiler_pop_fblock(c, FINALLY_END, end);
1740
1741 return 1;
1742}
1743
1744/*
1745 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1746 (The contents of the value stack is shown in [], with the top
1747 at the right; 'tb' is trace-back info, 'val' the exception's
1748 associated value, and 'exc' the exception.)
1749
1750 Value stack Label Instruction Argument
1751 [] SETUP_EXCEPT L1
1752 [] <code for S>
1753 [] POP_BLOCK
1754 [] JUMP_FORWARD L0
1755
1756 [tb, val, exc] L1: DUP )
1757 [tb, val, exc, exc] <evaluate E1> )
1758 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1759 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1760 [tb, val, exc, 1] POP )
1761 [tb, val, exc] POP
1762 [tb, val] <assign to V1> (or POP if no V1)
1763 [tb] POP
1764 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001765 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766
1767 [tb, val, exc, 0] L2: POP
1768 [tb, val, exc] DUP
1769 .............................etc.......................
1770
1771 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001772 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773
1774 [] L0: <next statement>
1775
1776 Of course, parts are not generated if Vi or Ei is not present.
1777*/
1778static int
1779compiler_try_except(struct compiler *c, stmt_ty s)
1780{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001781 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 int i, n;
1783
1784 body = compiler_new_block(c);
1785 except = compiler_new_block(c);
1786 orelse = compiler_new_block(c);
1787 end = compiler_new_block(c);
1788 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1789 return 0;
1790 ADDOP_JREL(c, SETUP_EXCEPT, except);
1791 compiler_use_next_block(c, body);
1792 if (!compiler_push_fblock(c, EXCEPT, body))
1793 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001794 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 ADDOP(c, POP_BLOCK);
1796 compiler_pop_fblock(c, EXCEPT, body);
1797 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1798 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1799 compiler_use_next_block(c, except);
1800 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001801 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 s->v.TryExcept.handlers, i);
1803 if (!handler->type && i < n-1)
1804 return compiler_error(c, "default 'except:' must be last");
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001805 c->u->u_lineno_set = false;
1806 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 except = compiler_new_block(c);
1808 if (except == NULL)
1809 return 0;
1810 if (handler->type) {
1811 ADDOP(c, DUP_TOP);
1812 VISIT(c, expr, handler->type);
1813 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1814 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1815 ADDOP(c, POP_TOP);
1816 }
1817 ADDOP(c, POP_TOP);
1818 if (handler->name) {
1819 VISIT(c, expr, handler->name);
1820 }
1821 else {
1822 ADDOP(c, POP_TOP);
1823 }
1824 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001825 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826 ADDOP_JREL(c, JUMP_FORWARD, end);
1827 compiler_use_next_block(c, except);
1828 if (handler->type)
1829 ADDOP(c, POP_TOP);
1830 }
1831 ADDOP(c, END_FINALLY);
1832 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001833 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 compiler_use_next_block(c, end);
1835 return 1;
1836}
1837
1838static int
1839compiler_import_as(struct compiler *c, identifier name, identifier asname)
1840{
1841 /* The IMPORT_NAME opcode was already generated. This function
1842 merely needs to bind the result to a name.
1843
1844 If there is a dot in name, we need to split it and emit a
1845 LOAD_ATTR for each name.
1846 */
1847 const char *src = PyString_AS_STRING(name);
1848 const char *dot = strchr(src, '.');
1849 if (dot) {
1850 /* Consume the base module name to get the first attribute */
1851 src = dot + 1;
1852 while (dot) {
1853 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001854 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001856 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001858 if (!attr)
1859 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001861 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 src = dot + 1;
1863 }
1864 }
1865 return compiler_nameop(c, asname, Store);
1866}
1867
1868static int
1869compiler_import(struct compiler *c, stmt_ty s)
1870{
1871 /* The Import node stores a module name like a.b.c as a single
1872 string. This is convenient for all cases except
1873 import a.b.c as d
1874 where we need to parse that string to extract the individual
1875 module names.
1876 XXX Perhaps change the representation to make this case simpler?
1877 */
1878 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001881 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001883 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884
Neal Norwitzcbce2802006-04-03 06:26:32 +00001885 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001886 level = PyInt_FromLong(0);
1887 else
1888 level = PyInt_FromLong(-1);
1889
1890 if (level == NULL)
1891 return 0;
1892
1893 ADDOP_O(c, LOAD_CONST, level, consts);
1894 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1896 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1897
1898 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001899 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001900 if (!r)
1901 return r;
1902 }
1903 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904 identifier tmp = alias->name;
1905 const char *base = PyString_AS_STRING(alias->name);
1906 char *dot = strchr(base, '.');
1907 if (dot)
1908 tmp = PyString_FromStringAndSize(base,
1909 dot - base);
1910 r = compiler_nameop(c, tmp, Store);
1911 if (dot) {
1912 Py_DECREF(tmp);
1913 }
1914 if (!r)
1915 return r;
1916 }
1917 }
1918 return 1;
1919}
1920
1921static int
1922compiler_from_import(struct compiler *c, stmt_ty s)
1923{
1924 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925
1926 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001927 PyObject *level;
1928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 if (!names)
1930 return 0;
1931
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001932 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001933 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001934 level = PyInt_FromLong(-1);
1935 else
1936 level = PyInt_FromLong(s->v.ImportFrom.level);
1937
1938 if (!level) {
1939 Py_DECREF(names);
1940 return 0;
1941 }
1942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 /* build up the names */
1944 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001945 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946 Py_INCREF(alias->name);
1947 PyTuple_SET_ITEM(names, i, alias->name);
1948 }
1949
1950 if (s->lineno > c->c_future->ff_lineno) {
1951 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1952 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001953 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954 Py_DECREF(names);
1955 return compiler_error(c,
1956 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001957 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
1959 }
1960 }
1961
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001962 ADDOP_O(c, LOAD_CONST, level, consts);
1963 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001965 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1967 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001968 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969 identifier store_name;
1970
1971 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1972 assert(n == 1);
1973 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975 }
1976
1977 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1978 store_name = alias->name;
1979 if (alias->asname)
1980 store_name = alias->asname;
1981
1982 if (!compiler_nameop(c, store_name, Store)) {
1983 Py_DECREF(names);
1984 return 0;
1985 }
1986 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001987 /* remove imported module */
1988 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 return 1;
1990}
1991
1992static int
1993compiler_assert(struct compiler *c, stmt_ty s)
1994{
1995 static PyObject *assertion_error = NULL;
1996 basicblock *end;
1997
1998 if (Py_OptimizeFlag)
1999 return 1;
2000 if (assertion_error == NULL) {
2001 assertion_error = PyString_FromString("AssertionError");
2002 if (assertion_error == NULL)
2003 return 0;
2004 }
2005 VISIT(c, expr, s->v.Assert.test);
2006 end = compiler_new_block(c);
2007 if (end == NULL)
2008 return 0;
2009 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2010 ADDOP(c, POP_TOP);
2011 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2012 if (s->v.Assert.msg) {
2013 VISIT(c, expr, s->v.Assert.msg);
2014 ADDOP_I(c, RAISE_VARARGS, 2);
2015 }
2016 else {
2017 ADDOP_I(c, RAISE_VARARGS, 1);
2018 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002019 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 ADDOP(c, POP_TOP);
2021 return 1;
2022}
2023
2024static int
2025compiler_visit_stmt(struct compiler *c, stmt_ty s)
2026{
2027 int i, n;
2028
Neal Norwitzf733a012006-10-29 18:30:10 +00002029 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030 c->u->u_lineno = s->lineno;
2031 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002032
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002034 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002036 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002038 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039 if (c->u->u_ste->ste_type != FunctionBlock)
2040 return compiler_error(c, "'return' outside function");
2041 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 VISIT(c, expr, s->v.Return.value);
2043 }
2044 else
2045 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2046 ADDOP(c, RETURN_VALUE);
2047 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002048 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002049 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002051 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 n = asdl_seq_LEN(s->v.Assign.targets);
2053 VISIT(c, expr, s->v.Assign.value);
2054 for (i = 0; i < n; i++) {
2055 if (i < n - 1)
2056 ADDOP(c, DUP_TOP);
2057 VISIT(c, expr,
2058 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2059 }
2060 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002061 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002063 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002069 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 n = 0;
2073 if (s->v.Raise.type) {
2074 VISIT(c, expr, s->v.Raise.type);
2075 n++;
2076 if (s->v.Raise.inst) {
2077 VISIT(c, expr, s->v.Raise.inst);
2078 n++;
2079 if (s->v.Raise.tback) {
2080 VISIT(c, expr, s->v.Raise.tback);
2081 n++;
2082 }
2083 }
2084 }
2085 ADDOP_I(c, RAISE_VARARGS, n);
2086 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002091 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002093 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 VISIT(c, expr, s->v.Exec.body);
2099 if (s->v.Exec.globals) {
2100 VISIT(c, expr, s->v.Exec.globals);
2101 if (s->v.Exec.locals) {
2102 VISIT(c, expr, s->v.Exec.locals);
2103 } else {
2104 ADDOP(c, DUP_TOP);
2105 }
2106 } else {
2107 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2108 ADDOP(c, DUP_TOP);
2109 }
2110 ADDOP(c, EXEC_STMT);
2111 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002112 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002116 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 ADDOP(c, PRINT_EXPR);
2118 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002119 else if (s->v.Expr.value->kind != Str_kind &&
2120 s->v.Expr.value->kind != Num_kind) {
2121 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 ADDOP(c, POP_TOP);
2123 }
2124 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002125 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002128 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 return compiler_error(c, "'break' outside loop");
2130 ADDOP(c, BREAK_LOOP);
2131 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 case With_kind:
2135 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 }
2137 return 1;
2138}
2139
2140static int
2141unaryop(unaryop_ty op)
2142{
2143 switch (op) {
2144 case Invert:
2145 return UNARY_INVERT;
2146 case Not:
2147 return UNARY_NOT;
2148 case UAdd:
2149 return UNARY_POSITIVE;
2150 case USub:
2151 return UNARY_NEGATIVE;
2152 }
2153 return 0;
2154}
2155
2156static int
2157binop(struct compiler *c, operator_ty op)
2158{
2159 switch (op) {
2160 case Add:
2161 return BINARY_ADD;
2162 case Sub:
2163 return BINARY_SUBTRACT;
2164 case Mult:
2165 return BINARY_MULTIPLY;
2166 case Div:
2167 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2168 return BINARY_TRUE_DIVIDE;
2169 else
2170 return BINARY_DIVIDE;
2171 case Mod:
2172 return BINARY_MODULO;
2173 case Pow:
2174 return BINARY_POWER;
2175 case LShift:
2176 return BINARY_LSHIFT;
2177 case RShift:
2178 return BINARY_RSHIFT;
2179 case BitOr:
2180 return BINARY_OR;
2181 case BitXor:
2182 return BINARY_XOR;
2183 case BitAnd:
2184 return BINARY_AND;
2185 case FloorDiv:
2186 return BINARY_FLOOR_DIVIDE;
2187 }
2188 return 0;
2189}
2190
2191static int
2192cmpop(cmpop_ty op)
2193{
2194 switch (op) {
2195 case Eq:
2196 return PyCmp_EQ;
2197 case NotEq:
2198 return PyCmp_NE;
2199 case Lt:
2200 return PyCmp_LT;
2201 case LtE:
2202 return PyCmp_LE;
2203 case Gt:
2204 return PyCmp_GT;
2205 case GtE:
2206 return PyCmp_GE;
2207 case Is:
2208 return PyCmp_IS;
2209 case IsNot:
2210 return PyCmp_IS_NOT;
2211 case In:
2212 return PyCmp_IN;
2213 case NotIn:
2214 return PyCmp_NOT_IN;
2215 }
2216 return PyCmp_BAD;
2217}
2218
2219static int
2220inplace_binop(struct compiler *c, operator_ty op)
2221{
2222 switch (op) {
2223 case Add:
2224 return INPLACE_ADD;
2225 case Sub:
2226 return INPLACE_SUBTRACT;
2227 case Mult:
2228 return INPLACE_MULTIPLY;
2229 case Div:
2230 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2231 return INPLACE_TRUE_DIVIDE;
2232 else
2233 return INPLACE_DIVIDE;
2234 case Mod:
2235 return INPLACE_MODULO;
2236 case Pow:
2237 return INPLACE_POWER;
2238 case LShift:
2239 return INPLACE_LSHIFT;
2240 case RShift:
2241 return INPLACE_RSHIFT;
2242 case BitOr:
2243 return INPLACE_OR;
2244 case BitXor:
2245 return INPLACE_XOR;
2246 case BitAnd:
2247 return INPLACE_AND;
2248 case FloorDiv:
2249 return INPLACE_FLOOR_DIVIDE;
2250 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002251 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002252 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 return 0;
2254}
2255
2256static int
2257compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2258{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002259 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2261
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002263 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 /* XXX AugStore isn't used anywhere! */
2265
2266 /* First check for assignment to __debug__. Param? */
2267 if ((ctx == Store || ctx == AugStore || ctx == Del)
2268 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2269 return compiler_error(c, "can not assign to __debug__");
2270 }
2271
Jeremy Hylton37075c52007-02-27 01:01:59 +00002272mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002273 if (!mangled)
2274 return 0;
2275
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 op = 0;
2277 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002278 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 switch (scope) {
2280 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 optype = OP_DEREF;
2283 break;
2284 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002285 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286 optype = OP_DEREF;
2287 break;
2288 case LOCAL:
2289 if (c->u->u_ste->ste_type == FunctionBlock)
2290 optype = OP_FAST;
2291 break;
2292 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002293 if (c->u->u_ste->ste_type == FunctionBlock &&
2294 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295 optype = OP_GLOBAL;
2296 break;
2297 case GLOBAL_EXPLICIT:
2298 optype = OP_GLOBAL;
2299 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002300 default:
2301 /* scope can be 0 */
2302 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 }
2304
2305 /* XXX Leave assert here, but handle __doc__ and the like better */
2306 assert(scope || PyString_AS_STRING(name)[0] == '_');
2307
2308 switch (optype) {
2309 case OP_DEREF:
2310 switch (ctx) {
2311 case Load: op = LOAD_DEREF; break;
2312 case Store: op = STORE_DEREF; break;
2313 case AugLoad:
2314 case AugStore:
2315 break;
2316 case Del:
2317 PyErr_Format(PyExc_SyntaxError,
2318 "can not delete variable '%s' referenced "
2319 "in nested scope",
2320 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002321 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002324 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002325 PyErr_SetString(PyExc_SystemError,
2326 "param invalid for deref variable");
2327 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328 }
2329 break;
2330 case OP_FAST:
2331 switch (ctx) {
2332 case Load: op = LOAD_FAST; break;
2333 case Store: op = STORE_FAST; break;
2334 case Del: op = DELETE_FAST; break;
2335 case AugLoad:
2336 case AugStore:
2337 break;
2338 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002339 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002340 PyErr_SetString(PyExc_SystemError,
2341 "param invalid for local variable");
2342 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002344 ADDOP_O(c, op, mangled, varnames);
2345 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002346 return 1;
2347 case OP_GLOBAL:
2348 switch (ctx) {
2349 case Load: op = LOAD_GLOBAL; break;
2350 case Store: op = STORE_GLOBAL; break;
2351 case Del: op = DELETE_GLOBAL; break;
2352 case AugLoad:
2353 case AugStore:
2354 break;
2355 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002356 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002357 PyErr_SetString(PyExc_SystemError,
2358 "param invalid for global variable");
2359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 }
2361 break;
2362 case OP_NAME:
2363 switch (ctx) {
2364 case Load: op = LOAD_NAME; break;
2365 case Store: op = STORE_NAME; break;
2366 case Del: op = DELETE_NAME; break;
2367 case AugLoad:
2368 case AugStore:
2369 break;
2370 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002371 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002372 PyErr_SetString(PyExc_SystemError,
2373 "param invalid for name variable");
2374 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 }
2376 break;
2377 }
2378
2379 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002380 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002381 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002382 if (arg < 0)
2383 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002384 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385}
2386
2387static int
2388compiler_boolop(struct compiler *c, expr_ty e)
2389{
2390 basicblock *end;
2391 int jumpi, i, n;
2392 asdl_seq *s;
2393
2394 assert(e->kind == BoolOp_kind);
2395 if (e->v.BoolOp.op == And)
2396 jumpi = JUMP_IF_FALSE;
2397 else
2398 jumpi = JUMP_IF_TRUE;
2399 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002400 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401 return 0;
2402 s = e->v.BoolOp.values;
2403 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002404 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002406 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 ADDOP_JREL(c, jumpi, end);
2408 ADDOP(c, POP_TOP)
2409 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002410 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 compiler_use_next_block(c, end);
2412 return 1;
2413}
2414
2415static int
2416compiler_list(struct compiler *c, expr_ty e)
2417{
2418 int n = asdl_seq_LEN(e->v.List.elts);
2419 if (e->v.List.ctx == Store) {
2420 ADDOP_I(c, UNPACK_SEQUENCE, n);
2421 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002422 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423 if (e->v.List.ctx == Load) {
2424 ADDOP_I(c, BUILD_LIST, n);
2425 }
2426 return 1;
2427}
2428
2429static int
2430compiler_tuple(struct compiler *c, expr_ty e)
2431{
2432 int n = asdl_seq_LEN(e->v.Tuple.elts);
2433 if (e->v.Tuple.ctx == Store) {
2434 ADDOP_I(c, UNPACK_SEQUENCE, n);
2435 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002436 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 if (e->v.Tuple.ctx == Load) {
2438 ADDOP_I(c, BUILD_TUPLE, n);
2439 }
2440 return 1;
2441}
2442
2443static int
2444compiler_compare(struct compiler *c, expr_ty e)
2445{
2446 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002447 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448
2449 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2450 VISIT(c, expr, e->v.Compare.left);
2451 n = asdl_seq_LEN(e->v.Compare.ops);
2452 assert(n > 0);
2453 if (n > 1) {
2454 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002455 if (cleanup == NULL)
2456 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002457 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002458 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 }
2460 for (i = 1; i < n; i++) {
2461 ADDOP(c, DUP_TOP);
2462 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002464 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002465 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2467 NEXT_BLOCK(c);
2468 ADDOP(c, POP_TOP);
2469 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002470 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002471 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002473 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002475 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 if (n > 1) {
2477 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002478 if (end == NULL)
2479 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480 ADDOP_JREL(c, JUMP_FORWARD, end);
2481 compiler_use_next_block(c, cleanup);
2482 ADDOP(c, ROT_TWO);
2483 ADDOP(c, POP_TOP);
2484 compiler_use_next_block(c, end);
2485 }
2486 return 1;
2487}
2488
2489static int
2490compiler_call(struct compiler *c, expr_ty e)
2491{
2492 int n, code = 0;
2493
2494 VISIT(c, expr, e->v.Call.func);
2495 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002496 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002498 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2500 }
2501 if (e->v.Call.starargs) {
2502 VISIT(c, expr, e->v.Call.starargs);
2503 code |= 1;
2504 }
2505 if (e->v.Call.kwargs) {
2506 VISIT(c, expr, e->v.Call.kwargs);
2507 code |= 2;
2508 }
2509 switch (code) {
2510 case 0:
2511 ADDOP_I(c, CALL_FUNCTION, n);
2512 break;
2513 case 1:
2514 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2515 break;
2516 case 2:
2517 ADDOP_I(c, CALL_FUNCTION_KW, n);
2518 break;
2519 case 3:
2520 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2521 break;
2522 }
2523 return 1;
2524}
2525
2526static int
2527compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002528 asdl_seq *generators, int gen_index,
2529 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530{
2531 /* generate code for the iterator, then each of the ifs,
2532 and then write to the element */
2533
2534 comprehension_ty l;
2535 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002536 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537
2538 start = compiler_new_block(c);
2539 skip = compiler_new_block(c);
2540 if_cleanup = compiler_new_block(c);
2541 anchor = compiler_new_block(c);
2542
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002543 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2544 anchor == NULL)
2545 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546
Anthony Baxter7b782b62006-04-11 12:01:56 +00002547 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 VISIT(c, expr, l->iter);
2549 ADDOP(c, GET_ITER);
2550 compiler_use_next_block(c, start);
2551 ADDOP_JREL(c, FOR_ITER, anchor);
2552 NEXT_BLOCK(c);
2553 VISIT(c, expr, l->target);
2554
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556 n = asdl_seq_LEN(l->ifs);
2557 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002558 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 VISIT(c, expr, e);
2560 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2561 NEXT_BLOCK(c);
2562 ADDOP(c, POP_TOP);
2563 }
2564
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002565 if (++gen_index < asdl_seq_LEN(generators))
2566 if (!compiler_listcomp_generator(c, tmpname,
2567 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002570 /* only append after the last for generator */
2571 if (gen_index >= asdl_seq_LEN(generators)) {
2572 if (!compiler_nameop(c, tmpname, Load))
2573 return 0;
2574 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002575 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002576
2577 compiler_use_next_block(c, skip);
2578 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 for (i = 0; i < n; i++) {
2580 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002581 if (i == 0)
2582 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 ADDOP(c, POP_TOP);
2584 }
2585 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2586 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002587 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002589 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 return 0;
2591
2592 return 1;
2593}
2594
2595static int
2596compiler_listcomp(struct compiler *c, expr_ty e)
2597{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002599 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 asdl_seq *generators = e->v.ListComp.generators;
2601
2602 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002603 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604 if (!tmp)
2605 return 0;
2606 ADDOP_I(c, BUILD_LIST, 0);
2607 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002609 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2610 e->v.ListComp.elt);
2611 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 return rc;
2613}
2614
2615static int
2616compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 asdl_seq *generators, int gen_index,
2618 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619{
2620 /* generate code for the iterator, then each of the ifs,
2621 and then write to the element */
2622
2623 comprehension_ty ge;
2624 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002625 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626
2627 start = compiler_new_block(c);
2628 skip = compiler_new_block(c);
2629 if_cleanup = compiler_new_block(c);
2630 anchor = compiler_new_block(c);
2631 end = compiler_new_block(c);
2632
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002633 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634 anchor == NULL || end == NULL)
2635 return 0;
2636
Anthony Baxter7b782b62006-04-11 12:01:56 +00002637 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 ADDOP_JREL(c, SETUP_LOOP, end);
2639 if (!compiler_push_fblock(c, LOOP, start))
2640 return 0;
2641
2642 if (gen_index == 0) {
2643 /* Receive outermost iter as an implicit argument */
2644 c->u->u_argcount = 1;
2645 ADDOP_I(c, LOAD_FAST, 0);
2646 }
2647 else {
2648 /* Sub-iter - calculate on the fly */
2649 VISIT(c, expr, ge->iter);
2650 ADDOP(c, GET_ITER);
2651 }
2652 compiler_use_next_block(c, start);
2653 ADDOP_JREL(c, FOR_ITER, anchor);
2654 NEXT_BLOCK(c);
2655 VISIT(c, expr, ge->target);
2656
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 n = asdl_seq_LEN(ge->ifs);
2659 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002660 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661 VISIT(c, expr, e);
2662 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2663 NEXT_BLOCK(c);
2664 ADDOP(c, POP_TOP);
2665 }
2666
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2669 return 0;
2670
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002671 /* only append after the last 'for' generator */
2672 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 VISIT(c, expr, elt);
2674 ADDOP(c, YIELD_VALUE);
2675 ADDOP(c, POP_TOP);
2676
2677 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 for (i = 0; i < n; i++) {
2680 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002681 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 compiler_use_next_block(c, if_cleanup);
2683
2684 ADDOP(c, POP_TOP);
2685 }
2686 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2687 compiler_use_next_block(c, anchor);
2688 ADDOP(c, POP_BLOCK);
2689 compiler_pop_fblock(c, LOOP, start);
2690 compiler_use_next_block(c, end);
2691
2692 return 1;
2693}
2694
2695static int
2696compiler_genexp(struct compiler *c, expr_ty e)
2697{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002698 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 PyCodeObject *co;
2700 expr_ty outermost_iter = ((comprehension_ty)
2701 (asdl_seq_GET(e->v.GeneratorExp.generators,
2702 0)))->iter;
2703
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002704 if (!name) {
2705 name = PyString_FromString("<genexpr>");
2706 if (!name)
2707 return 0;
2708 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709
2710 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2711 return 0;
2712 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2713 e->v.GeneratorExp.elt);
2714 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002715 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 if (co == NULL)
2717 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002720 Py_DECREF(co);
2721
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 VISIT(c, expr, outermost_iter);
2723 ADDOP(c, GET_ITER);
2724 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725
2726 return 1;
2727}
2728
2729static int
2730compiler_visit_keyword(struct compiler *c, keyword_ty k)
2731{
2732 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2733 VISIT(c, expr, k->value);
2734 return 1;
2735}
2736
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002737/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738 whether they are true or false.
2739
2740 Return values: 1 for true, 0 for false, -1 for non-constant.
2741 */
2742
2743static int
2744expr_constant(expr_ty e)
2745{
2746 switch (e->kind) {
2747 case Num_kind:
2748 return PyObject_IsTrue(e->v.Num.n);
2749 case Str_kind:
2750 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002751 case Name_kind:
2752 /* __debug__ is not assignable, so we can optimize
2753 * it away in if and while statements */
2754 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002755 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002756 return ! Py_OptimizeFlag;
2757 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758 default:
2759 return -1;
2760 }
2761}
2762
Guido van Rossumc2e20742006-02-27 22:32:47 +00002763/*
2764 Implements the with statement from PEP 343.
2765
2766 The semantics outlined in that PEP are as follows:
2767
2768 with EXPR as VAR:
2769 BLOCK
2770
2771 It is implemented roughly as:
2772
Guido van Rossumda5b7012006-05-02 19:47:52 +00002773 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002774 exit = context.__exit__ # not calling it
2775 value = context.__enter__()
2776 try:
2777 VAR = value # if VAR present in the syntax
2778 BLOCK
2779 finally:
2780 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002782 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002783 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002784 exit(*exc)
2785 */
2786static int
2787compiler_with(struct compiler *c, stmt_ty s)
2788{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002789 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002790 basicblock *block, *finally;
2791 identifier tmpexit, tmpvalue = NULL;
2792
2793 assert(s->kind == With_kind);
2794
Guido van Rossumc2e20742006-02-27 22:32:47 +00002795 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002796 enter_attr = PyString_InternFromString("__enter__");
2797 if (!enter_attr)
2798 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002799 }
2800 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 exit_attr = PyString_InternFromString("__exit__");
2802 if (!exit_attr)
2803 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002804 }
2805
2806 block = compiler_new_block(c);
2807 finally = compiler_new_block(c);
2808 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002809 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002810
2811 /* Create a temporary variable to hold context.__exit__ */
2812 tmpexit = compiler_new_tmpname(c);
2813 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002814 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002815 PyArena_AddPyObject(c->c_arena, tmpexit);
2816
2817 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002818 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002819 We need to do this rather than preserving it on the stack
2820 because SETUP_FINALLY remembers the stack level.
2821 We need to do the assignment *inside* the try/finally
2822 so that context.__exit__() is called when the assignment
2823 fails. But we need to call context.__enter__() *before*
2824 the try/finally so that if it fails we won't call
2825 context.__exit__().
2826 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 if (tmpvalue == NULL)
2829 return 0;
2830 PyArena_AddPyObject(c->c_arena, tmpvalue);
2831 }
2832
Guido van Rossumda5b7012006-05-02 19:47:52 +00002833 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002835
2836 /* Squirrel away context.__exit__ */
2837 ADDOP(c, DUP_TOP);
2838 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2839 if (!compiler_nameop(c, tmpexit, Store))
2840 return 0;
2841
2842 /* Call context.__enter__() */
2843 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2844 ADDOP_I(c, CALL_FUNCTION, 0);
2845
2846 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847 /* Store it in tmpvalue */
2848 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002849 return 0;
2850 }
2851 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002852 /* Discard result from context.__enter__() */
2853 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854 }
2855
2856 /* Start the try block */
2857 ADDOP_JREL(c, SETUP_FINALLY, finally);
2858
2859 compiler_use_next_block(c, block);
2860 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002862 }
2863
2864 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 /* Bind saved result of context.__enter__() to VAR */
2866 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002867 !compiler_nameop(c, tmpvalue, Del))
2868 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002869 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002870 }
2871
2872 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002873 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002874
2875 /* End of try block; start the finally block */
2876 ADDOP(c, POP_BLOCK);
2877 compiler_pop_fblock(c, FINALLY_TRY, block);
2878
2879 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2880 compiler_use_next_block(c, finally);
2881 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002883
2884 /* Finally block starts; push tmpexit and issue our magic opcode. */
2885 if (!compiler_nameop(c, tmpexit, Load) ||
2886 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002887 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002888 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889
2890 /* Finally block ends. */
2891 ADDOP(c, END_FINALLY);
2892 compiler_pop_fblock(c, FINALLY_END, finally);
2893 return 1;
2894}
2895
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896static int
2897compiler_visit_expr(struct compiler *c, expr_ty e)
2898{
2899 int i, n;
2900
Neal Norwitzf733a012006-10-29 18:30:10 +00002901 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002902 set a new line number for the next instruction.
2903 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 if (e->lineno > c->u->u_lineno) {
2905 c->u->u_lineno = e->lineno;
2906 c->u->u_lineno_set = false;
2907 }
2908 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002909 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 VISIT(c, expr, e->v.BinOp.left);
2913 VISIT(c, expr, e->v.BinOp.right);
2914 ADDOP(c, binop(c, e->v.BinOp.op));
2915 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002916 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 VISIT(c, expr, e->v.UnaryOp.operand);
2918 ADDOP(c, unaryop(e->v.UnaryOp.op));
2919 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002922 case IfExp_kind:
2923 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002924 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 n = asdl_seq_LEN(e->v.Dict.values);
Raymond Hettingerfd7ed402007-12-18 21:24:09 +00002926 ADDOP_I(c, BUILD_MAP, (n>255 ? 255 : n));
2927 n = asdl_seq_LEN(e->v.Dict.values);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002929 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002930 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Anthony Baxter7b782b62006-04-11 12:01:56 +00002931 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002932 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Raymond Hettingereffde122007-12-18 18:26:18 +00002933 ADDOP(c, STORE_MAP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 }
2935 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002936 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002938 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 return compiler_genexp(c, e);
2940 case Yield_kind:
2941 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002942 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 if (e->v.Yield.value) {
2944 VISIT(c, expr, e->v.Yield.value);
2945 }
2946 else {
2947 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2948 }
2949 ADDOP(c, YIELD_VALUE);
2950 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002951 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002955 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 VISIT(c, expr, e->v.Repr.value);
2957 ADDOP(c, UNARY_CONVERT);
2958 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2961 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2964 break;
2965 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002966 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 if (e->v.Attribute.ctx != AugStore)
2968 VISIT(c, expr, e->v.Attribute.value);
2969 switch (e->v.Attribute.ctx) {
2970 case AugLoad:
2971 ADDOP(c, DUP_TOP);
2972 /* Fall through to load */
2973 case Load:
2974 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2975 break;
2976 case AugStore:
2977 ADDOP(c, ROT_TWO);
2978 /* Fall through to save */
2979 case Store:
2980 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2981 break;
2982 case Del:
2983 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2984 break;
2985 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002986 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002987 PyErr_SetString(PyExc_SystemError,
2988 "param invalid in attribute expression");
2989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 }
2991 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 switch (e->v.Subscript.ctx) {
2994 case AugLoad:
2995 VISIT(c, expr, e->v.Subscript.value);
2996 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2997 break;
2998 case Load:
2999 VISIT(c, expr, e->v.Subscript.value);
3000 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3001 break;
3002 case AugStore:
3003 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3004 break;
3005 case Store:
3006 VISIT(c, expr, e->v.Subscript.value);
3007 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3008 break;
3009 case Del:
3010 VISIT(c, expr, e->v.Subscript.value);
3011 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3012 break;
3013 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003014 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003015 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003016 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003017 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018 }
3019 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003020 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3022 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003023 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003025 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026 return compiler_tuple(c, e);
3027 }
3028 return 1;
3029}
3030
3031static int
3032compiler_augassign(struct compiler *c, stmt_ty s)
3033{
3034 expr_ty e = s->v.AugAssign.target;
3035 expr_ty auge;
3036
3037 assert(s->kind == AugAssign_kind);
3038
3039 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003040 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003042 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003043 if (auge == NULL)
3044 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 VISIT(c, expr, auge);
3046 VISIT(c, expr, s->v.AugAssign.value);
3047 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3048 auge->v.Attribute.ctx = AugStore;
3049 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 break;
3051 case Subscript_kind:
3052 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003053 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003054 if (auge == NULL)
3055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 VISIT(c, expr, auge);
3057 VISIT(c, expr, s->v.AugAssign.value);
3058 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003059 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003061 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003063 if (!compiler_nameop(c, e->v.Name.id, Load))
3064 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065 VISIT(c, expr, s->v.AugAssign.value);
3066 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3067 return compiler_nameop(c, e->v.Name.id, Store);
3068 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003069 PyErr_Format(PyExc_SystemError,
3070 "invalid node type (%d) for augmented assignment",
3071 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 }
3074 return 1;
3075}
3076
3077static int
3078compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3079{
3080 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003081 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3082 PyErr_SetString(PyExc_SystemError,
3083 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003084 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003085 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 f = &c->u->u_fblock[c->u->u_nfblocks++];
3087 f->fb_type = t;
3088 f->fb_block = b;
3089 return 1;
3090}
3091
3092static void
3093compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3094{
3095 struct compiler_unit *u = c->u;
3096 assert(u->u_nfblocks > 0);
3097 u->u_nfblocks--;
3098 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3099 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3100}
3101
Jeremy Hylton82271f12006-10-04 02:24:52 +00003102static int
3103compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003104 int i;
3105 struct compiler_unit *u = c->u;
3106 for (i = 0; i < u->u_nfblocks; ++i) {
3107 if (u->u_fblock[i].fb_type == LOOP)
3108 return 1;
3109 }
3110 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003111}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112/* Raises a SyntaxError and returns 0.
3113 If something goes wrong, a different exception may be raised.
3114*/
3115
3116static int
3117compiler_error(struct compiler *c, const char *errstr)
3118{
3119 PyObject *loc;
3120 PyObject *u = NULL, *v = NULL;
3121
3122 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3123 if (!loc) {
3124 Py_INCREF(Py_None);
3125 loc = Py_None;
3126 }
3127 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3128 Py_None, loc);
3129 if (!u)
3130 goto exit;
3131 v = Py_BuildValue("(zO)", errstr, u);
3132 if (!v)
3133 goto exit;
3134 PyErr_SetObject(PyExc_SyntaxError, v);
3135 exit:
3136 Py_DECREF(loc);
3137 Py_XDECREF(u);
3138 Py_XDECREF(v);
3139 return 0;
3140}
3141
3142static int
3143compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003144 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 /* XXX this code is duplicated */
3149 switch (ctx) {
3150 case AugLoad: /* fall through to Load */
3151 case Load: op = BINARY_SUBSCR; break;
3152 case AugStore:/* fall through to Store */
3153 case Store: op = STORE_SUBSCR; break;
3154 case Del: op = DELETE_SUBSCR; break;
3155 case Param:
3156 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003157 "invalid %s kind %d in subscript\n",
3158 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 return 0;
3160 }
3161 if (ctx == AugLoad) {
3162 ADDOP_I(c, DUP_TOPX, 2);
3163 }
3164 else if (ctx == AugStore) {
3165 ADDOP(c, ROT_THREE);
3166 }
3167 ADDOP(c, op);
3168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169}
3170
3171static int
3172compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3173{
3174 int n = 2;
3175 assert(s->kind == Slice_kind);
3176
3177 /* only handles the cases where BUILD_SLICE is emitted */
3178 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 }
3181 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003186 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187 }
3188 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003189 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 }
3191
3192 if (s->v.Slice.step) {
3193 n++;
3194 VISIT(c, expr, s->v.Slice.step);
3195 }
3196 ADDOP_I(c, BUILD_SLICE, n);
3197 return 1;
3198}
3199
3200static int
3201compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3202{
3203 int op = 0, slice_offset = 0, stack_count = 0;
3204
3205 assert(s->v.Slice.step == NULL);
3206 if (s->v.Slice.lower) {
3207 slice_offset++;
3208 stack_count++;
3209 if (ctx != AugStore)
3210 VISIT(c, expr, s->v.Slice.lower);
3211 }
3212 if (s->v.Slice.upper) {
3213 slice_offset += 2;
3214 stack_count++;
3215 if (ctx != AugStore)
3216 VISIT(c, expr, s->v.Slice.upper);
3217 }
3218
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 if (ctx == AugLoad) {
3220 switch (stack_count) {
3221 case 0: ADDOP(c, DUP_TOP); break;
3222 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3223 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3224 }
3225 }
3226 else if (ctx == AugStore) {
3227 switch (stack_count) {
3228 case 0: ADDOP(c, ROT_TWO); break;
3229 case 1: ADDOP(c, ROT_THREE); break;
3230 case 2: ADDOP(c, ROT_FOUR); break;
3231 }
3232 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233
3234 switch (ctx) {
3235 case AugLoad: /* fall through to Load */
3236 case Load: op = SLICE; break;
3237 case AugStore:/* fall through to Store */
3238 case Store: op = STORE_SLICE; break;
3239 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003240 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003241 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003242 PyErr_SetString(PyExc_SystemError,
3243 "param invalid in simple slice");
3244 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245 }
3246
3247 ADDOP(c, op + slice_offset);
3248 return 1;
3249}
3250
3251static int
3252compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3253 expr_context_ty ctx)
3254{
3255 switch (s->kind) {
3256 case Ellipsis_kind:
3257 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3258 break;
3259 case Slice_kind:
3260 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 case Index_kind:
3262 VISIT(c, expr, s->v.Index.value);
3263 break;
3264 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003265 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003266 PyErr_SetString(PyExc_SystemError,
3267 "extended slice invalid in nested slice");
3268 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269 }
3270 return 1;
3271}
3272
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273static int
3274compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3275{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003276 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003278 case Index_kind:
3279 kindname = "index";
3280 if (ctx != AugStore) {
3281 VISIT(c, expr, s->v.Index.value);
3282 }
3283 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003285 kindname = "ellipsis";
3286 if (ctx != AugStore) {
3287 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289 break;
3290 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003291 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 if (!s->v.Slice.step)
3293 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003294 if (ctx != AugStore) {
3295 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 return 0;
3297 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003298 break;
3299 case ExtSlice_kind:
3300 kindname = "extended slice";
3301 if (ctx != AugStore) {
3302 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3303 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003304 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003305 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003306 if (!compiler_visit_nested_slice(c, sub, ctx))
3307 return 0;
3308 }
3309 ADDOP_I(c, BUILD_TUPLE, n);
3310 }
3311 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003312 default:
3313 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003314 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003315 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003317 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318}
3319
Neal Norwitzf733a012006-10-29 18:30:10 +00003320
3321/* End of the compiler section, beginning of the assembler section */
3322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323/* do depth-first search of basic block graph, starting with block.
3324 post records the block indices in post-order.
3325
3326 XXX must handle implicit jumps from one block to next
3327*/
3328
Neal Norwitzf733a012006-10-29 18:30:10 +00003329struct assembler {
3330 PyObject *a_bytecode; /* string containing bytecode */
3331 int a_offset; /* offset into bytecode */
3332 int a_nblocks; /* number of reachable blocks */
3333 basicblock **a_postorder; /* list of blocks in dfs postorder */
3334 PyObject *a_lnotab; /* string containing lnotab */
3335 int a_lnotab_off; /* offset into lnotab */
3336 int a_lineno; /* last lineno of emitted instruction */
3337 int a_lineno_off; /* bytecode offset of last lineno */
3338};
3339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340static void
3341dfs(struct compiler *c, basicblock *b, struct assembler *a)
3342{
3343 int i;
3344 struct instr *instr = NULL;
3345
3346 if (b->b_seen)
3347 return;
3348 b->b_seen = 1;
3349 if (b->b_next != NULL)
3350 dfs(c, b->b_next, a);
3351 for (i = 0; i < b->b_iused; i++) {
3352 instr = &b->b_instr[i];
3353 if (instr->i_jrel || instr->i_jabs)
3354 dfs(c, instr->i_target, a);
3355 }
3356 a->a_postorder[a->a_nblocks++] = b;
3357}
3358
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003359static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3361{
3362 int i;
3363 struct instr *instr;
3364 if (b->b_seen || b->b_startdepth >= depth)
3365 return maxdepth;
3366 b->b_seen = 1;
3367 b->b_startdepth = depth;
3368 for (i = 0; i < b->b_iused; i++) {
3369 instr = &b->b_instr[i];
3370 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3371 if (depth > maxdepth)
3372 maxdepth = depth;
3373 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3374 if (instr->i_jrel || instr->i_jabs) {
3375 maxdepth = stackdepth_walk(c, instr->i_target,
3376 depth, maxdepth);
3377 if (instr->i_opcode == JUMP_ABSOLUTE ||
3378 instr->i_opcode == JUMP_FORWARD) {
3379 goto out; /* remaining code is dead */
3380 }
3381 }
3382 }
3383 if (b->b_next)
3384 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3385out:
3386 b->b_seen = 0;
3387 return maxdepth;
3388}
3389
3390/* Find the flow path that needs the largest stack. We assume that
3391 * cycles in the flow graph have no net effect on the stack depth.
3392 */
3393static int
3394stackdepth(struct compiler *c)
3395{
3396 basicblock *b, *entryblock;
3397 entryblock = NULL;
3398 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3399 b->b_seen = 0;
3400 b->b_startdepth = INT_MIN;
3401 entryblock = b;
3402 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003403 if (!entryblock)
3404 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 return stackdepth_walk(c, entryblock, 0, 0);
3406}
3407
3408static int
3409assemble_init(struct assembler *a, int nblocks, int firstlineno)
3410{
3411 memset(a, 0, sizeof(struct assembler));
3412 a->a_lineno = firstlineno;
3413 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3414 if (!a->a_bytecode)
3415 return 0;
3416 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3417 if (!a->a_lnotab)
3418 return 0;
3419 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003420 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003421 if (!a->a_postorder) {
3422 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 return 1;
3426}
3427
3428static void
3429assemble_free(struct assembler *a)
3430{
3431 Py_XDECREF(a->a_bytecode);
3432 Py_XDECREF(a->a_lnotab);
3433 if (a->a_postorder)
3434 PyObject_Free(a->a_postorder);
3435}
3436
3437/* Return the size of a basic block in bytes. */
3438
3439static int
3440instrsize(struct instr *instr)
3441{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003442 if (!instr->i_hasarg)
3443 return 1;
3444 if (instr->i_oparg > 0xffff)
3445 return 6;
3446 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447}
3448
3449static int
3450blocksize(basicblock *b)
3451{
3452 int i;
3453 int size = 0;
3454
3455 for (i = 0; i < b->b_iused; i++)
3456 size += instrsize(&b->b_instr[i]);
3457 return size;
3458}
3459
3460/* All about a_lnotab.
3461
3462c_lnotab is an array of unsigned bytes disguised as a Python string.
3463It is used to map bytecode offsets to source code line #s (when needed
3464for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003465
Tim Peters2a7f3842001-06-09 09:26:21 +00003466The array is conceptually a list of
3467 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003469
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 byte code offset source code line number
3471 0 1
3472 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003473 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003474 350 307
3475 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003476
3477The first trick is that these numbers aren't stored, only the increments
3478from one row to the next (this doesn't really work, but it's a start):
3479
3480 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3481
3482The second trick is that an unsigned byte can't hold negative values, or
3483values larger than 255, so (a) there's a deep assumption that byte code
3484offsets and their corresponding line #s both increase monotonically, and (b)
3485if at least one column jumps by more than 255 from one row to the next, more
3486than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003488part. A user of c_lnotab desiring to find the source line number
3489corresponding to a bytecode address A should do something like this
3490
3491 lineno = addr = 0
3492 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 addr += addr_incr
3494 if addr > A:
3495 return lineno
3496 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003497
3498In order for this to work, when the addr field increments by more than 255,
3499the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003500increment is < 256. So, in the example above, assemble_lnotab (it used
3501to be called com_set_lineno) should not (as was actually done until 2.2)
3502expand 300, 300 to 255, 255, 45, 45,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003503 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003504*/
3505
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003506static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003508{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 int d_bytecode, d_lineno;
3510 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003511 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512
3513 d_bytecode = a->a_offset - a->a_lineno_off;
3514 d_lineno = i->i_lineno - a->a_lineno;
3515
3516 assert(d_bytecode >= 0);
3517 assert(d_lineno >= 0);
3518
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003519 /* XXX(nnorwitz): is there a better way to handle this?
3520 for loops are special, we want to be able to trace them
3521 each time around, so we need to set an extra line number. */
Nick Coghlanb90f52e2007-08-25 04:35:54 +00003522 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003523 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003526 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 nbytes = a->a_lnotab_off + 2 * ncodes;
3528 len = PyString_GET_SIZE(a->a_lnotab);
3529 if (nbytes >= len) {
3530 if (len * 2 < nbytes)
3531 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003532 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 len *= 2;
3534 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3535 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003536 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003537 lnotab = (unsigned char *)
3538 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003539 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 *lnotab++ = 255;
3541 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003542 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 d_bytecode -= ncodes * 255;
3544 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003545 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 assert(d_bytecode <= 255);
3547 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003548 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 nbytes = a->a_lnotab_off + 2 * ncodes;
3550 len = PyString_GET_SIZE(a->a_lnotab);
3551 if (nbytes >= len) {
3552 if (len * 2 < nbytes)
3553 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003554 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 len *= 2;
3556 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3557 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003558 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003559 lnotab = (unsigned char *)
3560 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003562 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003564 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003566 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003567 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 d_lineno -= ncodes * 255;
3569 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003570 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003571
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 len = PyString_GET_SIZE(a->a_lnotab);
3573 if (a->a_lnotab_off + 2 >= len) {
3574 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003575 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003576 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003577 lnotab = (unsigned char *)
3578 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 a->a_lnotab_off += 2;
3581 if (d_bytecode) {
3582 *lnotab++ = d_bytecode;
3583 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003584 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003585 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 *lnotab++ = 0;
3587 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 a->a_lineno = i->i_lineno;
3590 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003591 return 1;
3592}
3593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594/* assemble_emit()
3595 Extend the bytecode with a new instruction.
3596 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003597*/
3598
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003599static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003601{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003602 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003603 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604 char *code;
3605
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003606 size = instrsize(i);
3607 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003609 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 if (a->a_offset + size >= len) {
3614 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003615 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3618 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003619 if (size == 6) {
3620 assert(i->i_hasarg);
3621 *code++ = (char)EXTENDED_ARG;
3622 *code++ = ext & 0xff;
3623 *code++ = ext >> 8;
3624 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003627 if (i->i_hasarg) {
3628 assert(size == 3 || size == 6);
3629 *code++ = arg & 0xff;
3630 *code++ = arg >> 8;
3631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003633}
3634
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003635static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003637{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003639 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003640 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003641
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 /* Compute the size of each block and fixup jump args.
3643 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003644start:
3645 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003647 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 bsize = blocksize(b);
3649 b->b_offset = totsize;
3650 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003651 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003652 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3654 bsize = b->b_offset;
3655 for (i = 0; i < b->b_iused; i++) {
3656 struct instr *instr = &b->b_instr[i];
3657 /* Relative jumps are computed relative to
3658 the instruction pointer after fetching
3659 the jump instruction.
3660 */
3661 bsize += instrsize(instr);
3662 if (instr->i_jabs)
3663 instr->i_oparg = instr->i_target->b_offset;
3664 else if (instr->i_jrel) {
3665 int delta = instr->i_target->b_offset - bsize;
3666 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003667 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003668 else
3669 continue;
3670 if (instr->i_oparg > 0xffff)
3671 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003672 }
3673 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003674
3675 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003676 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003677 with a better solution.
3678
3679 In the meantime, should the goto be dropped in favor
3680 of a loop?
3681
3682 The issue is that in the first loop blocksize() is called
3683 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003684 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003685 i_oparg is calculated in the second loop above.
3686
3687 So we loop until we stop seeing new EXTENDED_ARGs.
3688 The only EXTENDED_ARGs that could be popping up are
3689 ones in jump instructions. So this should converge
3690 fairly quickly.
3691 */
3692 if (last_extended_arg_count != extended_arg_count) {
3693 last_extended_arg_count = extended_arg_count;
3694 goto start;
3695 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003696}
3697
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003698static PyObject *
3699dict_keys_inorder(PyObject *dict, int offset)
3700{
3701 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003702 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003703
3704 tuple = PyTuple_New(size);
3705 if (tuple == NULL)
3706 return NULL;
3707 while (PyDict_Next(dict, &pos, &k, &v)) {
3708 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003709 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003710 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003711 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003712 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003713 PyTuple_SET_ITEM(tuple, i - offset, k);
3714 }
3715 return tuple;
3716}
3717
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003718static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003720{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 PySTEntryObject *ste = c->u->u_ste;
3722 int flags = 0, n;
3723 if (ste->ste_type != ModuleBlock)
3724 flags |= CO_NEWLOCALS;
3725 if (ste->ste_type == FunctionBlock) {
3726 if (!ste->ste_unoptimized)
3727 flags |= CO_OPTIMIZED;
3728 if (ste->ste_nested)
3729 flags |= CO_NESTED;
3730 if (ste->ste_generator)
3731 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003732 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733 if (ste->ste_varargs)
3734 flags |= CO_VARARGS;
3735 if (ste->ste_varkeywords)
3736 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003737 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003739
3740 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003741 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 n = PyDict_Size(c->u->u_freevars);
3744 if (n < 0)
3745 return -1;
3746 if (n == 0) {
3747 n = PyDict_Size(c->u->u_cellvars);
3748 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003749 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 if (n == 0) {
3751 flags |= CO_NOFREE;
3752 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003753 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003754
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003755 return flags;
3756}
3757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758static PyCodeObject *
3759makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003760{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 PyObject *tmp;
3762 PyCodeObject *co = NULL;
3763 PyObject *consts = NULL;
3764 PyObject *names = NULL;
3765 PyObject *varnames = NULL;
3766 PyObject *filename = NULL;
3767 PyObject *name = NULL;
3768 PyObject *freevars = NULL;
3769 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003770 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 tmp = dict_keys_inorder(c->u->u_consts, 0);
3774 if (!tmp)
3775 goto error;
3776 consts = PySequence_List(tmp); /* optimize_code requires a list */
3777 Py_DECREF(tmp);
3778
3779 names = dict_keys_inorder(c->u->u_names, 0);
3780 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3781 if (!consts || !names || !varnames)
3782 goto error;
3783
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003784 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3785 if (!cellvars)
3786 goto error;
3787 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3788 if (!freevars)
3789 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790 filename = PyString_FromString(c->c_filename);
3791 if (!filename)
3792 goto error;
3793
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003794 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 flags = compute_code_flags(c);
3796 if (flags < 0)
3797 goto error;
3798
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003799 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 if (!bytecode)
3801 goto error;
3802
3803 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3804 if (!tmp)
3805 goto error;
3806 Py_DECREF(consts);
3807 consts = tmp;
3808
3809 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3810 bytecode, consts, names, varnames,
3811 freevars, cellvars,
3812 filename, c->u->u_name,
3813 c->u->u_firstlineno,
3814 a->a_lnotab);
3815 error:
3816 Py_XDECREF(consts);
3817 Py_XDECREF(names);
3818 Py_XDECREF(varnames);
3819 Py_XDECREF(filename);
3820 Py_XDECREF(name);
3821 Py_XDECREF(freevars);
3822 Py_XDECREF(cellvars);
3823 Py_XDECREF(bytecode);
3824 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003825}
3826
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003827
3828/* For debugging purposes only */
3829#if 0
3830static void
3831dump_instr(const struct instr *i)
3832{
3833 const char *jrel = i->i_jrel ? "jrel " : "";
3834 const char *jabs = i->i_jabs ? "jabs " : "";
3835 char arg[128];
3836
3837 *arg = '\0';
3838 if (i->i_hasarg)
3839 sprintf(arg, "arg: %d ", i->i_oparg);
3840
3841 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3842 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3843}
3844
3845static void
3846dump_basicblock(const basicblock *b)
3847{
3848 const char *seen = b->b_seen ? "seen " : "";
3849 const char *b_return = b->b_return ? "return " : "";
3850 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3851 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3852 if (b->b_instr) {
3853 int i;
3854 for (i = 0; i < b->b_iused; i++) {
3855 fprintf(stderr, " [%02d] ", i);
3856 dump_instr(b->b_instr + i);
3857 }
3858 }
3859}
3860#endif
3861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862static PyCodeObject *
3863assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003864{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 basicblock *b, *entryblock;
3866 struct assembler a;
3867 int i, j, nblocks;
3868 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 /* Make sure every block that falls off the end returns None.
3871 XXX NEXT_BLOCK() isn't quite right, because if the last
3872 block ends with a jump or return b_next shouldn't set.
3873 */
3874 if (!c->u->u_curblock->b_return) {
3875 NEXT_BLOCK(c);
3876 if (addNone)
3877 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3878 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003879 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 nblocks = 0;
3882 entryblock = NULL;
3883 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3884 nblocks++;
3885 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887
Neal Norwitzed657552006-07-10 00:04:44 +00003888 /* Set firstlineno if it wasn't explicitly set. */
3889 if (!c->u->u_firstlineno) {
3890 if (entryblock && entryblock->b_instr)
3891 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3892 else
3893 c->u->u_firstlineno = 1;
3894 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3896 goto error;
3897 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003900 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003901
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 /* Emit code in reverse postorder from dfs. */
3903 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003904 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 for (j = 0; j < b->b_iused; j++)
3906 if (!assemble_emit(&a, &b->b_instr[j]))
3907 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003908 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3911 goto error;
3912 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3913 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 co = makecode(c, &a);
3916 error:
3917 assemble_free(&a);
3918 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003919}