blob: cb6555ed38406a2ad8d7aeab9ca83f425dc803a1 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Neal Norwitzf733a012006-10-29 18:30:10 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hylton819de6c2007-02-27 16:13:23 +000011 * this file.
Neal Norwitzf733a012006-10-29 18:30:10 +000012 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Neal Norwitzf733a012006-10-29 18:30:10 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000110 /* Pointer to the most recently allocated block. By following b_list
111 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000112 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 basicblock *u_curblock; /* pointer to current block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
116 int u_nfblocks;
117 struct fblockinfo u_fblock[CO_MAXBLOCKS];
118
119 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000120 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 bool u_lineno_set; /* boolean to indicate whether instr
122 has been generated with current lineno */
123};
124
125/* This struct captures the global state of a compilation.
126
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000127The u pointer points to the current compilation unit, while units
128for enclosing blocks are stored in c_stack. The u and c_stack are
129managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130*/
131
132struct compiler {
133 const char *c_filename;
134 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136 PyCompilerFlags *c_flags;
137
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000138 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000139 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 struct compiler_unit *u; /* compiler state for current block */
142 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147static int compiler_enter_scope(struct compiler *, identifier, void *, int);
148static void compiler_free(struct compiler *);
149static basicblock *compiler_new_block(struct compiler *);
150static int compiler_next_instr(struct compiler *, basicblock *);
151static int compiler_addop(struct compiler *, int);
152static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
153static int compiler_addop_i(struct compiler *, int, int);
154static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155static basicblock *compiler_use_new_block(struct compiler *);
156static int compiler_error(struct compiler *, const char *);
157static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
158
159static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
160static int compiler_visit_stmt(struct compiler *, stmt_ty);
161static int compiler_visit_keyword(struct compiler *, keyword_ty);
162static int compiler_visit_expr(struct compiler *, expr_ty);
163static int compiler_augassign(struct compiler *, stmt_ty);
164static int compiler_visit_slice(struct compiler *, slice_ty,
165 expr_context_ty);
166
167static int compiler_push_fblock(struct compiler *, enum fblocktype,
168 basicblock *);
169static void compiler_pop_fblock(struct compiler *, enum fblocktype,
170 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000171/* Returns true if there is a loop on the fblock stack. */
172static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
174static int inplace_binop(struct compiler *, operator_ty);
175static int expr_constant(expr_ty e);
176
Guido van Rossumc2e20742006-02-27 22:32:47 +0000177static int compiler_with(struct compiler *, stmt_ty);
178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static PyCodeObject *assemble(struct compiler *, int addNone);
180static PyObject *__doc__;
181
182PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000183_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000184{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185 /* Name mangling: __private becomes _classname__private.
186 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000187 const char *p, *name = PyString_AsString(ident);
188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
191 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000192 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000194 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000195 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 nlen = strlen(name);
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000197 /* Don't mangle __id__ or names with dots.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000198
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000199 The only time a name with a dot can occur is when
200 we are compiling an import statement that has a
201 package name.
Jeremy Hylton37075c52007-02-27 01:01:59 +0000202
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000203 TODO(jhylton): Decide whether we want to support
204 mangling of the module name, e.g. __M.X.
205 */
Jeremy Hylton37075c52007-02-27 01:01:59 +0000206 if ((name[nlen-1] == '_' && name[nlen-2] == '_')
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000207 || strchr(name, '.')) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211 /* Strip leading underscores from class name */
212 while (*p == '_')
213 p++;
214 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
220 if (!ident)
221 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 buffer = PyString_AS_STRING(ident);
224 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 strncpy(buffer+1, p, plen);
226 strcpy(buffer+1+plen, name);
227 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000228}
229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230static int
231compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000232{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000233 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 c->c_stack = PyList_New(0);
236 if (!c->c_stack)
237 return 0;
238
239 return 1;
240}
241
242PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000243PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000244 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000245{
246 struct compiler c;
247 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyCompilerFlags local_flags;
249 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 if (!__doc__) {
252 __doc__ = PyString_InternFromString("__doc__");
253 if (!__doc__)
254 return NULL;
255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
257 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000258 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000260 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261 c.c_future = PyFuture_FromAST(mod, filename);
262 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000263 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000265 local_flags.cf_flags = 0;
266 flags = &local_flags;
267 }
268 merged = c.c_future->ff_features | flags->cf_flags;
269 c.c_future->ff_features = merged;
270 flags->cf_flags = merged;
271 c.c_flags = flags;
272 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273
274 c.c_st = PySymtable_Build(mod, filename, c.c_future);
275 if (c.c_st == NULL) {
276 if (!PyErr_Occurred())
277 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000278 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 }
280
281 /* XXX initialize to NULL for now, need to handle */
282 c.c_encoding = NULL;
283
284 co = compiler_mod(&c, mod);
285
Thomas Wouters1175c432006-02-27 22:49:54 +0000286 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000287 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000288 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000289 return co;
290}
291
292PyCodeObject *
293PyNode_Compile(struct _node *n, const char *filename)
294{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000295 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000296 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000297 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000298 if (!arena)
299 return NULL;
300 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 if (mod)
302 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000304 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000305}
306
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000307static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000309{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310 if (c->c_st)
311 PySymtable_Free(c->c_st);
312 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000313 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000315}
316
Guido van Rossum79f25d91997-04-29 20:08:16 +0000317static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000321 PyObject *v, *k;
322 PyObject *dict = PyDict_New();
323 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 n = PyList_Size(list);
326 for (i = 0; i < n; i++) {
327 v = PyInt_FromLong(i);
328 if (!v) {
329 Py_DECREF(dict);
330 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000331 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000332 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000333 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
335 Py_XDECREF(k);
336 Py_DECREF(v);
337 Py_DECREF(dict);
338 return NULL;
339 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000340 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000342 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 return dict;
344}
345
346/* Return new dict containing names from src that match scope(s).
347
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000348src is a symbol table dictionary. If the scope of a name matches
349either scope_type or flag is set, insert it into the new dict. The
350values are integers, starting at offset and increasing by one for
351each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352*/
353
354static PyObject *
355dictbytype(PyObject *src, int scope_type, int flag, int offset)
356{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000357 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358 PyObject *k, *v, *dest = PyDict_New();
359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 assert(offset >= 0);
361 if (dest == NULL)
362 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
364 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000365 /* XXX this should probably be a macro in symtable.h */
366 assert(PyInt_Check(v));
367 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
370 PyObject *tuple, *item = PyInt_FromLong(i);
371 if (item == NULL) {
372 Py_DECREF(dest);
373 return NULL;
374 }
375 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000376 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000377 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
378 Py_DECREF(item);
379 Py_DECREF(dest);
380 Py_XDECREF(tuple);
381 return NULL;
382 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 }
387 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000388}
389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390static void
391compiler_unit_check(struct compiler_unit *u)
392{
393 basicblock *block;
394 for (block = u->u_blocks; block != NULL; block = block->b_list) {
395 assert(block != (void *)0xcbcbcbcb);
396 assert(block != (void *)0xfbfbfbfb);
397 assert(block != (void *)0xdbdbdbdb);
398 if (block->b_instr != NULL) {
399 assert(block->b_ialloc > 0);
400 assert(block->b_iused > 0);
401 assert(block->b_ialloc >= block->b_iused);
402 }
403 else {
404 assert (block->b_iused == 0);
405 assert (block->b_ialloc == 0);
406 }
407 }
408}
409
410static void
411compiler_unit_free(struct compiler_unit *u)
412{
413 basicblock *b, *next;
414
415 compiler_unit_check(u);
416 b = u->u_blocks;
417 while (b != NULL) {
418 if (b->b_instr)
419 PyObject_Free((void *)b->b_instr);
420 next = b->b_list;
421 PyObject_Free((void *)b);
422 b = next;
423 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000424 Py_CLEAR(u->u_ste);
425 Py_CLEAR(u->u_name);
426 Py_CLEAR(u->u_consts);
427 Py_CLEAR(u->u_names);
428 Py_CLEAR(u->u_varnames);
429 Py_CLEAR(u->u_freevars);
430 Py_CLEAR(u->u_cellvars);
431 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000432 PyObject_Free(u);
433}
434
435static int
436compiler_enter_scope(struct compiler *c, identifier name, void *key,
437 int lineno)
438{
439 struct compiler_unit *u;
440
Anthony Baxter7b782b62006-04-11 12:01:56 +0000441 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000442 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000443 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000444 PyErr_NoMemory();
445 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000446 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000447 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000448 u->u_argcount = 0;
449 u->u_ste = PySymtable_Lookup(c->c_st, key);
450 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000451 compiler_unit_free(u);
452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453 }
454 Py_INCREF(name);
455 u->u_name = name;
456 u->u_varnames = list2dict(u->u_ste->ste_varnames);
457 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000458 if (!u->u_varnames || !u->u_cellvars) {
459 compiler_unit_free(u);
460 return 0;
461 }
462
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000465 if (!u->u_freevars) {
466 compiler_unit_free(u);
467 return 0;
468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
470 u->u_blocks = NULL;
471 u->u_tmpname = 0;
472 u->u_nfblocks = 0;
473 u->u_firstlineno = lineno;
474 u->u_lineno = 0;
475 u->u_lineno_set = false;
476 u->u_consts = PyDict_New();
477 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000479 return 0;
480 }
481 u->u_names = PyDict_New();
482 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000483 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484 return 0;
485 }
486
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000488
489 /* Push the old compiler_unit on the stack. */
490 if (c->u) {
491 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000492 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
493 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000494 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496 }
497 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000498 u->u_private = c->u->u_private;
499 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000500 }
501 c->u = u;
502
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000503 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000504 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000505 return 0;
506
507 return 1;
508}
509
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000510static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511compiler_exit_scope(struct compiler *c)
512{
513 int n;
514 PyObject *wrapper;
515
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000516 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 compiler_unit_free(c->u);
518 /* Restore c->u to the parent unit. */
519 n = PyList_GET_SIZE(c->c_stack) - 1;
520 if (n >= 0) {
521 wrapper = PyList_GET_ITEM(c->c_stack, n);
522 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000523 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000524 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000525 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000526 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 compiler_unit_check(c->u);
528 }
529 else
530 c->u = NULL;
531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532}
533
Guido van Rossumc2e20742006-02-27 22:32:47 +0000534/* Allocate a new "anonymous" local variable.
535 Used by list comprehensions and with statements.
536*/
537
538static PyObject *
539compiler_new_tmpname(struct compiler *c)
540{
541 char tmpname[256];
542 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
543 return PyString_FromString(tmpname);
544}
545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000546/* Allocate a new block and return a pointer to it.
547 Returns NULL on error.
548*/
549
550static basicblock *
551compiler_new_block(struct compiler *c)
552{
553 basicblock *b;
554 struct compiler_unit *u;
555
556 u = c->u;
557 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000558 if (b == NULL) {
559 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000561 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000563 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564 b->b_list = u->u_blocks;
565 u->u_blocks = b;
566 return b;
567}
568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569static basicblock *
570compiler_use_new_block(struct compiler *c)
571{
572 basicblock *block = compiler_new_block(c);
573 if (block == NULL)
574 return NULL;
575 c->u->u_curblock = block;
576 return block;
577}
578
579static basicblock *
580compiler_next_block(struct compiler *c)
581{
582 basicblock *block = compiler_new_block(c);
583 if (block == NULL)
584 return NULL;
585 c->u->u_curblock->b_next = block;
586 c->u->u_curblock = block;
587 return block;
588}
589
590static basicblock *
591compiler_use_next_block(struct compiler *c, basicblock *block)
592{
593 assert(block != NULL);
594 c->u->u_curblock->b_next = block;
595 c->u->u_curblock = block;
596 return block;
597}
598
599/* Returns the offset of the next instruction in the current block's
600 b_instr array. Resizes the b_instr as necessary.
601 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000602*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603
604static int
605compiler_next_instr(struct compiler *c, basicblock *b)
606{
607 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000608 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000609 b->b_instr = (struct instr *)PyObject_Malloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000610 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 if (b->b_instr == NULL) {
612 PyErr_NoMemory();
613 return -1;
614 }
615 b->b_ialloc = DEFAULT_BLOCK_SIZE;
616 memset((char *)b->b_instr, 0,
617 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000620 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000621 size_t oldsize, newsize;
622 oldsize = b->b_ialloc * sizeof(struct instr);
623 newsize = oldsize << 1;
624 if (newsize == 0) {
625 PyErr_NoMemory();
626 return -1;
627 }
628 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000629 tmp = (struct instr *)PyObject_Realloc(
Jeremy Hylton819de6c2007-02-27 16:13:23 +0000630 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000631 if (tmp == NULL) {
632 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000633 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000634 }
635 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
637 }
638 return b->b_iused++;
639}
640
Jeremy Hylton12603c42006-04-01 16:18:02 +0000641/* Set the i_lineno member of the instruction at offse off if the
642 line number for the current expression/statement (?) has not
643 already been set. If it has been set, the call has no effect.
644
645 Every time a new node is b
Neal Norwitzf733a012006-10-29 18:30:10 +0000646*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000648static void
649compiler_set_lineno(struct compiler *c, int off)
650{
651 basicblock *b;
652 if (c->u->u_lineno_set)
653 return;
654 c->u->u_lineno_set = true;
655 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657}
658
659static int
660opcode_stack_effect(int opcode, int oparg)
661{
662 switch (opcode) {
663 case POP_TOP:
664 return -1;
665 case ROT_TWO:
666 case ROT_THREE:
667 return 0;
668 case DUP_TOP:
669 return 1;
670 case ROT_FOUR:
671 return 0;
672
673 case UNARY_POSITIVE:
674 case UNARY_NEGATIVE:
675 case UNARY_NOT:
676 case UNARY_CONVERT:
677 case UNARY_INVERT:
678 return 0;
679
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000680 case LIST_APPEND:
681 return -2;
682
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 case BINARY_POWER:
684 case BINARY_MULTIPLY:
685 case BINARY_DIVIDE:
686 case BINARY_MODULO:
687 case BINARY_ADD:
688 case BINARY_SUBTRACT:
689 case BINARY_SUBSCR:
690 case BINARY_FLOOR_DIVIDE:
691 case BINARY_TRUE_DIVIDE:
692 return -1;
693 case INPLACE_FLOOR_DIVIDE:
694 case INPLACE_TRUE_DIVIDE:
695 return -1;
696
697 case SLICE+0:
698 return 1;
699 case SLICE+1:
700 return 0;
701 case SLICE+2:
702 return 0;
703 case SLICE+3:
704 return -1;
705
706 case STORE_SLICE+0:
707 return -2;
708 case STORE_SLICE+1:
709 return -3;
710 case STORE_SLICE+2:
711 return -3;
712 case STORE_SLICE+3:
713 return -4;
714
715 case DELETE_SLICE+0:
716 return -1;
717 case DELETE_SLICE+1:
718 return -2;
719 case DELETE_SLICE+2:
720 return -2;
721 case DELETE_SLICE+3:
722 return -3;
723
724 case INPLACE_ADD:
725 case INPLACE_SUBTRACT:
726 case INPLACE_MULTIPLY:
727 case INPLACE_DIVIDE:
728 case INPLACE_MODULO:
729 return -1;
730 case STORE_SUBSCR:
731 return -3;
732 case DELETE_SUBSCR:
733 return -2;
734
735 case BINARY_LSHIFT:
736 case BINARY_RSHIFT:
737 case BINARY_AND:
738 case BINARY_XOR:
739 case BINARY_OR:
740 return -1;
741 case INPLACE_POWER:
742 return -1;
743 case GET_ITER:
744 return 0;
745
746 case PRINT_EXPR:
747 return -1;
748 case PRINT_ITEM:
749 return -1;
750 case PRINT_NEWLINE:
751 return 0;
752 case PRINT_ITEM_TO:
753 return -2;
754 case PRINT_NEWLINE_TO:
755 return -1;
756 case INPLACE_LSHIFT:
757 case INPLACE_RSHIFT:
758 case INPLACE_AND:
759 case INPLACE_XOR:
760 case INPLACE_OR:
761 return -1;
762 case BREAK_LOOP:
763 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000764 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000765 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000766 case LOAD_LOCALS:
767 return 1;
768 case RETURN_VALUE:
769 return -1;
770 case IMPORT_STAR:
771 return -1;
772 case EXEC_STMT:
773 return -3;
774 case YIELD_VALUE:
775 return 0;
776
777 case POP_BLOCK:
778 return 0;
779 case END_FINALLY:
780 return -1; /* or -2 or -3 if exception occurred */
781 case BUILD_CLASS:
782 return -2;
783
784 case STORE_NAME:
785 return -1;
786 case DELETE_NAME:
787 return 0;
788 case UNPACK_SEQUENCE:
789 return oparg-1;
790 case FOR_ITER:
791 return 1;
792
793 case STORE_ATTR:
794 return -2;
795 case DELETE_ATTR:
796 return -1;
797 case STORE_GLOBAL:
798 return -1;
799 case DELETE_GLOBAL:
800 return 0;
801 case DUP_TOPX:
802 return oparg;
803 case LOAD_CONST:
804 return 1;
805 case LOAD_NAME:
806 return 1;
807 case BUILD_TUPLE:
808 case BUILD_LIST:
809 return 1-oparg;
810 case BUILD_MAP:
811 return 1;
812 case LOAD_ATTR:
813 return 0;
814 case COMPARE_OP:
815 return -1;
816 case IMPORT_NAME:
817 return 0;
818 case IMPORT_FROM:
819 return 1;
820
821 case JUMP_FORWARD:
822 case JUMP_IF_FALSE:
823 case JUMP_IF_TRUE:
824 case JUMP_ABSOLUTE:
825 return 0;
826
827 case LOAD_GLOBAL:
828 return 1;
829
830 case CONTINUE_LOOP:
831 return 0;
832 case SETUP_LOOP:
833 return 0;
834 case SETUP_EXCEPT:
835 case SETUP_FINALLY:
836 return 3; /* actually pushed by an exception */
837
838 case LOAD_FAST:
839 return 1;
840 case STORE_FAST:
841 return -1;
842 case DELETE_FAST:
843 return 0;
844
845 case RAISE_VARARGS:
846 return -oparg;
847#define NARGS(o) (((o) % 256) + 2*((o) / 256))
848 case CALL_FUNCTION:
849 return -NARGS(oparg);
850 case CALL_FUNCTION_VAR:
851 case CALL_FUNCTION_KW:
852 return -NARGS(oparg)-1;
853 case CALL_FUNCTION_VAR_KW:
854 return -NARGS(oparg)-2;
855#undef NARGS
856 case MAKE_FUNCTION:
857 return -oparg;
858 case BUILD_SLICE:
859 if (oparg == 3)
860 return -2;
861 else
862 return -1;
863
864 case MAKE_CLOSURE:
865 return -oparg;
866 case LOAD_CLOSURE:
867 return 1;
868 case LOAD_DEREF:
869 return 1;
870 case STORE_DEREF:
871 return -1;
872 default:
873 fprintf(stderr, "opcode = %d\n", opcode);
874 Py_FatalError("opcode_stack_effect()");
875
876 }
877 return 0; /* not reachable */
878}
879
880/* Add an opcode with no argument.
881 Returns 0 on failure, 1 on success.
882*/
883
884static int
885compiler_addop(struct compiler *c, int opcode)
886{
887 basicblock *b;
888 struct instr *i;
889 int off;
890 off = compiler_next_instr(c, c->u->u_curblock);
891 if (off < 0)
892 return 0;
893 b = c->u->u_curblock;
894 i = &b->b_instr[off];
895 i->i_opcode = opcode;
896 i->i_hasarg = 0;
897 if (opcode == RETURN_VALUE)
898 b->b_return = 1;
899 compiler_set_lineno(c, off);
900 return 1;
901}
902
903static int
904compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
905{
906 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000908
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000909 /* necessary to make sure types aren't coerced (e.g., int and long) */
Alex Martellid8672aa2007-08-22 21:14:17 +0000910 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
911 if (PyFloat_Check(o)) {
912 double d = PyFloat_AS_DOUBLE(o);
913 unsigned char* p = (unsigned char*) &d;
914 /* all we need is to make the tuple different in either the 0.0
915 * or -0.0 case from all others, just to avoid the "coercion".
916 */
917 if (*p==0 && p[sizeof(double)-1]==0)
918 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
919 else
920 t = PyTuple_Pack(2, o, o->ob_type);
921 } else {
922 t = PyTuple_Pack(2, o, o->ob_type);
923 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000924 if (t == NULL)
925 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
927 v = PyDict_GetItem(dict, t);
928 if (!v) {
929 arg = PyDict_Size(dict);
930 v = PyInt_FromLong(arg);
931 if (!v) {
932 Py_DECREF(t);
933 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000934 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935 if (PyDict_SetItem(dict, t, v) < 0) {
936 Py_DECREF(t);
937 Py_DECREF(v);
938 return -1;
939 }
940 Py_DECREF(v);
941 }
942 else
943 arg = PyInt_AsLong(v);
944 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000945 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000946}
947
948static int
949compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
950 PyObject *o)
951{
952 int arg = compiler_add_o(c, dict, o);
953 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000954 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000955 return compiler_addop_i(c, opcode, arg);
956}
957
958static int
959compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000960 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000961{
962 int arg;
963 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
964 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000965 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000966 arg = compiler_add_o(c, dict, mangled);
967 Py_DECREF(mangled);
968 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 return compiler_addop_i(c, opcode, arg);
971}
972
973/* Add an opcode with an integer argument.
974 Returns 0 on failure, 1 on success.
975*/
976
977static int
978compiler_addop_i(struct compiler *c, int opcode, int oparg)
979{
980 struct instr *i;
981 int off;
982 off = compiler_next_instr(c, c->u->u_curblock);
983 if (off < 0)
984 return 0;
985 i = &c->u->u_curblock->b_instr[off];
986 i->i_opcode = opcode;
987 i->i_oparg = oparg;
988 i->i_hasarg = 1;
989 compiler_set_lineno(c, off);
990 return 1;
991}
992
993static int
994compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
995{
996 struct instr *i;
997 int off;
998
999 assert(b != NULL);
1000 off = compiler_next_instr(c, c->u->u_curblock);
1001 if (off < 0)
1002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 i = &c->u->u_curblock->b_instr[off];
1004 i->i_opcode = opcode;
1005 i->i_target = b;
1006 i->i_hasarg = 1;
1007 if (absolute)
1008 i->i_jabs = 1;
1009 else
1010 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001011 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012 return 1;
1013}
1014
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001015/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1016 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017 it as the current block. NEXT_BLOCK() also creates an implicit jump
1018 from the current block to the new block.
1019*/
1020
Neal Norwitzf733a012006-10-29 18:30:10 +00001021/* The returns inside these macros make it impossible to decref objects
1022 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001023*/
1024
1025
1026#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001027 if (compiler_use_new_block((C)) == NULL) \
1028 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001029}
1030
1031#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001032 if (compiler_next_block((C)) == NULL) \
1033 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001034}
1035
1036#define ADDOP(C, OP) { \
1037 if (!compiler_addop((C), (OP))) \
1038 return 0; \
1039}
1040
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001041#define ADDOP_IN_SCOPE(C, OP) { \
1042 if (!compiler_addop((C), (OP))) { \
1043 compiler_exit_scope(c); \
1044 return 0; \
1045 } \
1046}
1047
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001048#define ADDOP_O(C, OP, O, TYPE) { \
1049 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1050 return 0; \
1051}
1052
1053#define ADDOP_NAME(C, OP, O, TYPE) { \
1054 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1055 return 0; \
1056}
1057
1058#define ADDOP_I(C, OP, O) { \
1059 if (!compiler_addop_i((C), (OP), (O))) \
1060 return 0; \
1061}
1062
1063#define ADDOP_JABS(C, OP, O) { \
1064 if (!compiler_addop_j((C), (OP), (O), 1)) \
1065 return 0; \
1066}
1067
1068#define ADDOP_JREL(C, OP, O) { \
1069 if (!compiler_addop_j((C), (OP), (O), 0)) \
1070 return 0; \
1071}
1072
1073/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1074 the ASDL name to synthesize the name of the C type and the visit function.
1075*/
1076
1077#define VISIT(C, TYPE, V) {\
1078 if (!compiler_visit_ ## TYPE((C), (V))) \
1079 return 0; \
1080}
1081
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001082#define VISIT_IN_SCOPE(C, TYPE, V) {\
1083 if (!compiler_visit_ ## TYPE((C), (V))) { \
1084 compiler_exit_scope(c); \
1085 return 0; \
1086 } \
1087}
1088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001089#define VISIT_SLICE(C, V, CTX) {\
1090 if (!compiler_visit_slice((C), (V), (CTX))) \
1091 return 0; \
1092}
1093
1094#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001095 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001097 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001098 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001099 if (!compiler_visit_ ## TYPE((C), elt)) \
1100 return 0; \
1101 } \
1102}
1103
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001104#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001105 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001106 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001107 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001108 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001109 if (!compiler_visit_ ## TYPE((C), elt)) { \
1110 compiler_exit_scope(c); \
1111 return 0; \
1112 } \
1113 } \
1114}
1115
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116static int
1117compiler_isdocstring(stmt_ty s)
1118{
1119 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001120 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 return s->v.Expr.value->kind == Str_kind;
1122}
1123
1124/* Compile a sequence of statements, checking for a docstring. */
1125
1126static int
1127compiler_body(struct compiler *c, asdl_seq *stmts)
1128{
1129 int i = 0;
1130 stmt_ty st;
1131
1132 if (!asdl_seq_LEN(stmts))
1133 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001134 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandla5ea6892007-06-01 11:33:33 +00001135 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1136 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 i = 1;
1138 VISIT(c, expr, st->v.Expr.value);
1139 if (!compiler_nameop(c, __doc__, Store))
1140 return 0;
1141 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001142 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001143 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 return 1;
1145}
1146
1147static PyCodeObject *
1148compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001149{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001150 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 static PyObject *module;
1153 if (!module) {
1154 module = PyString_FromString("<module>");
1155 if (!module)
1156 return NULL;
1157 }
Neal Norwitzed657552006-07-10 00:04:44 +00001158 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1159 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001160 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 switch (mod->kind) {
1162 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001163 if (!compiler_body(c, mod->v.Module.body)) {
1164 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 break;
1168 case Interactive_kind:
1169 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001170 VISIT_SEQ_IN_SCOPE(c, stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001171 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 break;
1173 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001174 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001175 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 break;
1177 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001178 PyErr_SetString(PyExc_SystemError,
1179 "suite should not be possible");
1180 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001181 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001182 PyErr_Format(PyExc_SystemError,
1183 "module kind %d should not be possible",
1184 mod->kind);
1185 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001186 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 co = assemble(c, addNone);
1188 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001189 return co;
1190}
1191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192/* The test for LOCAL must come before the test for FREE in order to
1193 handle classes where name is both local and free. The local var is
1194 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001195*/
1196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197static int
1198get_ref_type(struct compiler *c, PyObject *name)
1199{
1200 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001201 if (scope == 0) {
1202 char buf[350];
1203 PyOS_snprintf(buf, sizeof(buf),
1204 "unknown scope for %.100s in %.100s(%s) in %s\n"
1205 "symbols: %s\nlocals: %s\nglobals: %s\n",
1206 PyString_AS_STRING(name),
1207 PyString_AS_STRING(c->u->u_name),
1208 PyObject_REPR(c->u->u_ste->ste_id),
1209 c->c_filename,
1210 PyObject_REPR(c->u->u_ste->ste_symbols),
1211 PyObject_REPR(c->u->u_varnames),
1212 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001214 Py_FatalError(buf);
1215 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001216
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001217 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218}
1219
1220static int
1221compiler_lookup_arg(PyObject *dict, PyObject *name)
1222{
1223 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001224 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001226 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001227 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001228 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001230 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231 return PyInt_AS_LONG(v);
1232}
1233
1234static int
1235compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1236{
1237 int i, free = PyCode_GetNumFree(co);
1238 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001239 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1240 ADDOP_I(c, MAKE_FUNCTION, args);
1241 return 1;
1242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243 for (i = 0; i < free; ++i) {
1244 /* Bypass com_addop_varname because it will generate
1245 LOAD_DEREF but LOAD_CLOSURE is needed.
1246 */
1247 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1248 int arg, reftype;
1249
1250 /* Special case: If a class contains a method with a
1251 free variable that has the same name as a method,
1252 the name will be considered free *and* local in the
1253 class. It should be handled by the closure, as
1254 well as by the normal name loookup logic.
1255 */
1256 reftype = get_ref_type(c, name);
1257 if (reftype == CELL)
1258 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1259 else /* (reftype == FREE) */
1260 arg = compiler_lookup_arg(c->u->u_freevars, name);
1261 if (arg == -1) {
1262 printf("lookup %s in %s %d %d\n"
1263 "freevars of %s: %s\n",
1264 PyObject_REPR(name),
1265 PyString_AS_STRING(c->u->u_name),
1266 reftype, arg,
1267 PyString_AS_STRING(co->co_name),
1268 PyObject_REPR(co->co_freevars));
1269 Py_FatalError("compiler_make_closure()");
1270 }
1271 ADDOP_I(c, LOAD_CLOSURE, arg);
1272 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001274 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001275 ADDOP_I(c, MAKE_CLOSURE, args);
1276 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279static int
1280compiler_decorators(struct compiler *c, asdl_seq* decos)
1281{
1282 int i;
1283
1284 if (!decos)
1285 return 1;
1286
1287 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001288 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289 }
1290 return 1;
1291}
1292
1293static int
1294compiler_arguments(struct compiler *c, arguments_ty args)
1295{
1296 int i;
1297 int n = asdl_seq_LEN(args->args);
1298 /* Correctly handle nested argument lists */
1299 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001300 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301 if (arg->kind == Tuple_kind) {
1302 PyObject *id = PyString_FromFormat(".%d", i);
1303 if (id == NULL) {
1304 return 0;
1305 }
1306 if (!compiler_nameop(c, id, Load)) {
1307 Py_DECREF(id);
1308 return 0;
1309 }
1310 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001311 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001312 }
1313 }
1314 return 1;
1315}
1316
1317static int
1318compiler_function(struct compiler *c, stmt_ty s)
1319{
1320 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001321 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 arguments_ty args = s->v.FunctionDef.args;
1323 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001324 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325 int i, n, docstring;
1326
1327 assert(s->kind == FunctionDef_kind);
1328
1329 if (!compiler_decorators(c, decos))
1330 return 0;
1331 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001332 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1334 s->lineno))
1335 return 0;
1336
Anthony Baxter7b782b62006-04-11 12:01:56 +00001337 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001338 docstring = compiler_isdocstring(st);
1339 if (docstring)
1340 first_const = st->v.Expr.value->v.Str.s;
1341 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001342 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001343 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001344 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001346 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001347 compiler_arguments(c, args);
1348
1349 c->u->u_argcount = asdl_seq_LEN(args->args);
1350 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001351 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001353 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1354 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 }
1356 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001357 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 if (co == NULL)
1359 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001361 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001362 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363
1364 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1365 ADDOP_I(c, CALL_FUNCTION, 1);
1366 }
1367
1368 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1369}
1370
1371static int
1372compiler_class(struct compiler *c, stmt_ty s)
1373{
1374 int n;
1375 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001376 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 /* push class name on stack, needed by BUILD_CLASS */
1378 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1379 /* push the tuple of base classes on the stack */
1380 n = asdl_seq_LEN(s->v.ClassDef.bases);
1381 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001382 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 ADDOP_I(c, BUILD_TUPLE, n);
1384 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1385 s->lineno))
1386 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001387 c->u->u_private = s->v.ClassDef.name;
1388 Py_INCREF(c->u->u_private);
1389 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 if (!str || !compiler_nameop(c, str, Load)) {
1391 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001392 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001394 }
1395
1396 Py_DECREF(str);
1397 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 if (!str || !compiler_nameop(c, str, Store)) {
1399 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001400 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001402 }
1403 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001405 if (!compiler_body(c, s->v.ClassDef.body)) {
1406 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001408 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001410 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1411 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001412 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001413 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001414 if (co == NULL)
1415 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001417 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001418 Py_DECREF(co);
1419
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 ADDOP_I(c, CALL_FUNCTION, 0);
1421 ADDOP(c, BUILD_CLASS);
1422 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1423 return 0;
1424 return 1;
1425}
1426
1427static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001428compiler_ifexp(struct compiler *c, expr_ty e)
1429{
1430 basicblock *end, *next;
1431
1432 assert(e->kind == IfExp_kind);
1433 end = compiler_new_block(c);
1434 if (end == NULL)
1435 return 0;
1436 next = compiler_new_block(c);
1437 if (next == NULL)
1438 return 0;
1439 VISIT(c, expr, e->v.IfExp.test);
1440 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1441 ADDOP(c, POP_TOP);
1442 VISIT(c, expr, e->v.IfExp.body);
1443 ADDOP_JREL(c, JUMP_FORWARD, end);
1444 compiler_use_next_block(c, next);
1445 ADDOP(c, POP_TOP);
1446 VISIT(c, expr, e->v.IfExp.orelse);
1447 compiler_use_next_block(c, end);
1448 return 1;
1449}
1450
1451static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452compiler_lambda(struct compiler *c, expr_ty e)
1453{
1454 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001455 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456 arguments_ty args = e->v.Lambda.args;
1457 assert(e->kind == Lambda_kind);
1458
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001459 if (!name) {
1460 name = PyString_InternFromString("<lambda>");
1461 if (!name)
1462 return 0;
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464
1465 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001466 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1468 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001469
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001470 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 compiler_arguments(c, args);
1472
1473 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001474 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1475 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001477 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478 if (co == NULL)
1479 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001481 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001482 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001483
1484 return 1;
1485}
1486
1487static int
1488compiler_print(struct compiler *c, stmt_ty s)
1489{
1490 int i, n;
1491 bool dest;
1492
1493 assert(s->kind == Print_kind);
1494 n = asdl_seq_LEN(s->v.Print.values);
1495 dest = false;
1496 if (s->v.Print.dest) {
1497 VISIT(c, expr, s->v.Print.dest);
1498 dest = true;
1499 }
1500 for (i = 0; i < n; i++) {
1501 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1502 if (dest) {
1503 ADDOP(c, DUP_TOP);
1504 VISIT(c, expr, e);
1505 ADDOP(c, ROT_TWO);
1506 ADDOP(c, PRINT_ITEM_TO);
1507 }
1508 else {
1509 VISIT(c, expr, e);
1510 ADDOP(c, PRINT_ITEM);
1511 }
1512 }
1513 if (s->v.Print.nl) {
1514 if (dest)
1515 ADDOP(c, PRINT_NEWLINE_TO)
1516 else
1517 ADDOP(c, PRINT_NEWLINE)
1518 }
1519 else if (dest)
1520 ADDOP(c, POP_TOP);
1521 return 1;
1522}
1523
1524static int
1525compiler_if(struct compiler *c, stmt_ty s)
1526{
1527 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001528 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529 assert(s->kind == If_kind);
1530 end = compiler_new_block(c);
1531 if (end == NULL)
1532 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001533 next = compiler_new_block(c);
1534 if (next == NULL)
1535 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001536
1537 constant = expr_constant(s->v.If.test);
1538 /* constant = 0: "if 0"
1539 * constant = 1: "if 1", "if 2", ...
1540 * constant = -1: rest */
1541 if (constant == 0) {
1542 if (s->v.If.orelse)
1543 VISIT_SEQ(c, stmt, s->v.If.orelse);
1544 } else if (constant == 1) {
1545 VISIT_SEQ(c, stmt, s->v.If.body);
1546 } else {
1547 VISIT(c, expr, s->v.If.test);
1548 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1549 ADDOP(c, POP_TOP);
1550 VISIT_SEQ(c, stmt, s->v.If.body);
1551 ADDOP_JREL(c, JUMP_FORWARD, end);
1552 compiler_use_next_block(c, next);
1553 ADDOP(c, POP_TOP);
1554 if (s->v.If.orelse)
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001555 VISIT_SEQ(c, stmt, s->v.If.orelse);
Georg Brandlddbaa662006-06-04 21:56:52 +00001556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557 compiler_use_next_block(c, end);
1558 return 1;
1559}
1560
1561static int
1562compiler_for(struct compiler *c, stmt_ty s)
1563{
1564 basicblock *start, *cleanup, *end;
1565
1566 start = compiler_new_block(c);
1567 cleanup = compiler_new_block(c);
1568 end = compiler_new_block(c);
1569 if (start == NULL || end == NULL || cleanup == NULL)
1570 return 0;
1571 ADDOP_JREL(c, SETUP_LOOP, end);
1572 if (!compiler_push_fblock(c, LOOP, start))
1573 return 0;
1574 VISIT(c, expr, s->v.For.iter);
1575 ADDOP(c, GET_ITER);
1576 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001577 /* XXX(nnorwitz): is there a better way to handle this?
1578 for loops are special, we want to be able to trace them
1579 each time around, so we need to set an extra line number. */
1580 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581 ADDOP_JREL(c, FOR_ITER, cleanup);
1582 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001583 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1585 compiler_use_next_block(c, cleanup);
1586 ADDOP(c, POP_BLOCK);
1587 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001588 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589 compiler_use_next_block(c, end);
1590 return 1;
1591}
1592
1593static int
1594compiler_while(struct compiler *c, stmt_ty s)
1595{
1596 basicblock *loop, *orelse, *end, *anchor = NULL;
1597 int constant = expr_constant(s->v.While.test);
1598
1599 if (constant == 0)
1600 return 1;
1601 loop = compiler_new_block(c);
1602 end = compiler_new_block(c);
1603 if (constant == -1) {
1604 anchor = compiler_new_block(c);
1605 if (anchor == NULL)
1606 return 0;
1607 }
1608 if (loop == NULL || end == NULL)
1609 return 0;
1610 if (s->v.While.orelse) {
1611 orelse = compiler_new_block(c);
1612 if (orelse == NULL)
1613 return 0;
1614 }
1615 else
1616 orelse = NULL;
1617
1618 ADDOP_JREL(c, SETUP_LOOP, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001619 if (!compiler_push_fblock(c, LOOP, loop))
1620 return 0;
Nick Coghlan3af0e782007-08-25 04:32:07 +00001621 compiler_use_next_block(c, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 if (constant == -1) {
Nick Coghlan3af0e782007-08-25 04:32:07 +00001623 /* XXX(ncoghlan): SF bug #1750076
1624 Use same special casing as is used in for loops
1625 A test case for this would be nice... */
1626 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627 VISIT(c, expr, s->v.While.test);
1628 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1629 ADDOP(c, POP_TOP);
1630 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001631 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1633
1634 /* XXX should the two POP instructions be in a separate block
1635 if there is no else clause ?
1636 */
1637
1638 if (constant == -1) {
1639 compiler_use_next_block(c, anchor);
1640 ADDOP(c, POP_TOP);
1641 ADDOP(c, POP_BLOCK);
1642 }
1643 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001644 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001645 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 compiler_use_next_block(c, end);
1647
1648 return 1;
1649}
1650
1651static int
1652compiler_continue(struct compiler *c)
1653{
1654 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001655 static const char IN_FINALLY_ERROR_MSG[] =
1656 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657 int i;
1658
1659 if (!c->u->u_nfblocks)
1660 return compiler_error(c, LOOP_ERROR_MSG);
1661 i = c->u->u_nfblocks - 1;
1662 switch (c->u->u_fblock[i].fb_type) {
1663 case LOOP:
1664 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1665 break;
1666 case EXCEPT:
1667 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001668 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1669 /* Prevent continue anywhere under a finally
1670 even if hidden in a sub-try or except. */
1671 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1672 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 if (i == -1)
1675 return compiler_error(c, LOOP_ERROR_MSG);
1676 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1677 break;
1678 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001679 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680 }
1681
1682 return 1;
1683}
1684
1685/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1686
1687 SETUP_FINALLY L
1688 <code for body>
1689 POP_BLOCK
1690 LOAD_CONST <None>
1691 L: <code for finalbody>
1692 END_FINALLY
1693
1694 The special instructions use the block stack. Each block
1695 stack entry contains the instruction that created it (here
1696 SETUP_FINALLY), the level of the value stack at the time the
1697 block stack entry was created, and a label (here L).
1698
1699 SETUP_FINALLY:
1700 Pushes the current value stack level and the label
1701 onto the block stack.
1702 POP_BLOCK:
1703 Pops en entry from the block stack, and pops the value
1704 stack until its level is the same as indicated on the
1705 block stack. (The label is ignored.)
1706 END_FINALLY:
1707 Pops a variable number of entries from the *value* stack
1708 and re-raises the exception they specify. The number of
1709 entries popped depends on the (pseudo) exception type.
1710
1711 The block stack is unwound when an exception is raised:
1712 when a SETUP_FINALLY entry is found, the exception is pushed
1713 onto the value stack (and the exception condition is cleared),
1714 and the interpreter jumps to the label gotten from the block
1715 stack.
1716*/
1717
1718static int
1719compiler_try_finally(struct compiler *c, stmt_ty s)
1720{
1721 basicblock *body, *end;
1722 body = compiler_new_block(c);
1723 end = compiler_new_block(c);
1724 if (body == NULL || end == NULL)
1725 return 0;
1726
1727 ADDOP_JREL(c, SETUP_FINALLY, end);
1728 compiler_use_next_block(c, body);
1729 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1730 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001731 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732 ADDOP(c, POP_BLOCK);
1733 compiler_pop_fblock(c, FINALLY_TRY, body);
1734
1735 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1736 compiler_use_next_block(c, end);
1737 if (!compiler_push_fblock(c, FINALLY_END, end))
1738 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001739 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001740 ADDOP(c, END_FINALLY);
1741 compiler_pop_fblock(c, FINALLY_END, end);
1742
1743 return 1;
1744}
1745
1746/*
1747 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1748 (The contents of the value stack is shown in [], with the top
1749 at the right; 'tb' is trace-back info, 'val' the exception's
1750 associated value, and 'exc' the exception.)
1751
1752 Value stack Label Instruction Argument
1753 [] SETUP_EXCEPT L1
1754 [] <code for S>
1755 [] POP_BLOCK
1756 [] JUMP_FORWARD L0
1757
1758 [tb, val, exc] L1: DUP )
1759 [tb, val, exc, exc] <evaluate E1> )
1760 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1761 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1762 [tb, val, exc, 1] POP )
1763 [tb, val, exc] POP
1764 [tb, val] <assign to V1> (or POP if no V1)
1765 [tb] POP
1766 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001767 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768
1769 [tb, val, exc, 0] L2: POP
1770 [tb, val, exc] DUP
1771 .............................etc.......................
1772
1773 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001774 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775
1776 [] L0: <next statement>
1777
1778 Of course, parts are not generated if Vi or Ei is not present.
1779*/
1780static int
1781compiler_try_except(struct compiler *c, stmt_ty s)
1782{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001783 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 int i, n;
1785
1786 body = compiler_new_block(c);
1787 except = compiler_new_block(c);
1788 orelse = compiler_new_block(c);
1789 end = compiler_new_block(c);
1790 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1791 return 0;
1792 ADDOP_JREL(c, SETUP_EXCEPT, except);
1793 compiler_use_next_block(c, body);
1794 if (!compiler_push_fblock(c, EXCEPT, body))
1795 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001796 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 ADDOP(c, POP_BLOCK);
1798 compiler_pop_fblock(c, EXCEPT, body);
1799 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1800 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1801 compiler_use_next_block(c, except);
1802 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001803 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 s->v.TryExcept.handlers, i);
1805 if (!handler->type && i < n-1)
1806 return compiler_error(c, "default 'except:' must be last");
Jeremy Hylton819de6c2007-02-27 16:13:23 +00001807 c->u->u_lineno_set = false;
1808 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 except = compiler_new_block(c);
1810 if (except == NULL)
1811 return 0;
1812 if (handler->type) {
1813 ADDOP(c, DUP_TOP);
1814 VISIT(c, expr, handler->type);
1815 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1816 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1817 ADDOP(c, POP_TOP);
1818 }
1819 ADDOP(c, POP_TOP);
1820 if (handler->name) {
1821 VISIT(c, expr, handler->name);
1822 }
1823 else {
1824 ADDOP(c, POP_TOP);
1825 }
1826 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001827 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 ADDOP_JREL(c, JUMP_FORWARD, end);
1829 compiler_use_next_block(c, except);
1830 if (handler->type)
1831 ADDOP(c, POP_TOP);
1832 }
1833 ADDOP(c, END_FINALLY);
1834 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001835 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 compiler_use_next_block(c, end);
1837 return 1;
1838}
1839
1840static int
1841compiler_import_as(struct compiler *c, identifier name, identifier asname)
1842{
1843 /* The IMPORT_NAME opcode was already generated. This function
1844 merely needs to bind the result to a name.
1845
1846 If there is a dot in name, we need to split it and emit a
1847 LOAD_ATTR for each name.
1848 */
1849 const char *src = PyString_AS_STRING(name);
1850 const char *dot = strchr(src, '.');
1851 if (dot) {
1852 /* Consume the base module name to get the first attribute */
1853 src = dot + 1;
1854 while (dot) {
1855 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001856 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001858 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001860 if (!attr)
1861 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001863 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 src = dot + 1;
1865 }
1866 }
1867 return compiler_nameop(c, asname, Store);
1868}
1869
1870static int
1871compiler_import(struct compiler *c, stmt_ty s)
1872{
1873 /* The Import node stores a module name like a.b.c as a single
1874 string. This is convenient for all cases except
1875 import a.b.c as d
1876 where we need to parse that string to extract the individual
1877 module names.
1878 XXX Perhaps change the representation to make this case simpler?
1879 */
1880 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001883 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001885 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886
Neal Norwitzcbce2802006-04-03 06:26:32 +00001887 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001888 level = PyInt_FromLong(0);
1889 else
1890 level = PyInt_FromLong(-1);
1891
1892 if (level == NULL)
1893 return 0;
1894
1895 ADDOP_O(c, LOAD_CONST, level, consts);
1896 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1898 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1899
1900 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001901 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001902 if (!r)
1903 return r;
1904 }
1905 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 identifier tmp = alias->name;
1907 const char *base = PyString_AS_STRING(alias->name);
1908 char *dot = strchr(base, '.');
1909 if (dot)
1910 tmp = PyString_FromStringAndSize(base,
1911 dot - base);
1912 r = compiler_nameop(c, tmp, Store);
1913 if (dot) {
1914 Py_DECREF(tmp);
1915 }
1916 if (!r)
1917 return r;
1918 }
1919 }
1920 return 1;
1921}
1922
1923static int
1924compiler_from_import(struct compiler *c, stmt_ty s)
1925{
1926 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927
1928 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001929 PyObject *level;
1930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 if (!names)
1932 return 0;
1933
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001934 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001935 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001936 level = PyInt_FromLong(-1);
1937 else
1938 level = PyInt_FromLong(s->v.ImportFrom.level);
1939
1940 if (!level) {
1941 Py_DECREF(names);
1942 return 0;
1943 }
1944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945 /* build up the names */
1946 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001947 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 Py_INCREF(alias->name);
1949 PyTuple_SET_ITEM(names, i, alias->name);
1950 }
1951
1952 if (s->lineno > c->c_future->ff_lineno) {
1953 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1954 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001955 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 Py_DECREF(names);
1957 return compiler_error(c,
1958 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
1961 }
1962 }
1963
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001964 ADDOP_O(c, LOAD_CONST, level, consts);
1965 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001967 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1969 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001970 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 identifier store_name;
1972
1973 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1974 assert(n == 1);
1975 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001976 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 }
1978
1979 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1980 store_name = alias->name;
1981 if (alias->asname)
1982 store_name = alias->asname;
1983
1984 if (!compiler_nameop(c, store_name, Store)) {
1985 Py_DECREF(names);
1986 return 0;
1987 }
1988 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001989 /* remove imported module */
1990 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 return 1;
1992}
1993
1994static int
1995compiler_assert(struct compiler *c, stmt_ty s)
1996{
1997 static PyObject *assertion_error = NULL;
1998 basicblock *end;
1999
2000 if (Py_OptimizeFlag)
2001 return 1;
2002 if (assertion_error == NULL) {
2003 assertion_error = PyString_FromString("AssertionError");
2004 if (assertion_error == NULL)
2005 return 0;
2006 }
2007 VISIT(c, expr, s->v.Assert.test);
2008 end = compiler_new_block(c);
2009 if (end == NULL)
2010 return 0;
2011 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2012 ADDOP(c, POP_TOP);
2013 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2014 if (s->v.Assert.msg) {
2015 VISIT(c, expr, s->v.Assert.msg);
2016 ADDOP_I(c, RAISE_VARARGS, 2);
2017 }
2018 else {
2019 ADDOP_I(c, RAISE_VARARGS, 1);
2020 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002021 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 ADDOP(c, POP_TOP);
2023 return 1;
2024}
2025
2026static int
2027compiler_visit_stmt(struct compiler *c, stmt_ty s)
2028{
2029 int i, n;
2030
Neal Norwitzf733a012006-10-29 18:30:10 +00002031 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032 c->u->u_lineno = s->lineno;
2033 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002036 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002038 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002040 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002041 if (c->u->u_ste->ste_type != FunctionBlock)
2042 return compiler_error(c, "'return' outside function");
2043 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 VISIT(c, expr, s->v.Return.value);
2045 }
2046 else
2047 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2048 ADDOP(c, RETURN_VALUE);
2049 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002050 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002051 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002053 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 n = asdl_seq_LEN(s->v.Assign.targets);
2055 VISIT(c, expr, s->v.Assign.value);
2056 for (i = 0; i < n; i++) {
2057 if (i < n - 1)
2058 ADDOP(c, DUP_TOP);
2059 VISIT(c, expr,
2060 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2061 }
2062 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002063 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002069 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002073 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 n = 0;
2075 if (s->v.Raise.type) {
2076 VISIT(c, expr, s->v.Raise.type);
2077 n++;
2078 if (s->v.Raise.inst) {
2079 VISIT(c, expr, s->v.Raise.inst);
2080 n++;
2081 if (s->v.Raise.tback) {
2082 VISIT(c, expr, s->v.Raise.tback);
2083 n++;
2084 }
2085 }
2086 }
2087 ADDOP_I(c, RAISE_VARARGS, n);
2088 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002091 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002093 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 VISIT(c, expr, s->v.Exec.body);
2101 if (s->v.Exec.globals) {
2102 VISIT(c, expr, s->v.Exec.globals);
2103 if (s->v.Exec.locals) {
2104 VISIT(c, expr, s->v.Exec.locals);
2105 } else {
2106 ADDOP(c, DUP_TOP);
2107 }
2108 } else {
2109 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2110 ADDOP(c, DUP_TOP);
2111 }
2112 ADDOP(c, EXEC_STMT);
2113 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002116 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002118 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002119 ADDOP(c, PRINT_EXPR);
2120 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002121 else if (s->v.Expr.value->kind != Str_kind &&
2122 s->v.Expr.value->kind != Num_kind) {
2123 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124 ADDOP(c, POP_TOP);
2125 }
2126 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002127 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case Break_kind:
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002130 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 return compiler_error(c, "'break' outside loop");
2132 ADDOP(c, BREAK_LOOP);
2133 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002136 case With_kind:
2137 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138 }
2139 return 1;
2140}
2141
2142static int
2143unaryop(unaryop_ty op)
2144{
2145 switch (op) {
2146 case Invert:
2147 return UNARY_INVERT;
2148 case Not:
2149 return UNARY_NOT;
2150 case UAdd:
2151 return UNARY_POSITIVE;
2152 case USub:
2153 return UNARY_NEGATIVE;
2154 }
2155 return 0;
2156}
2157
2158static int
2159binop(struct compiler *c, operator_ty op)
2160{
2161 switch (op) {
2162 case Add:
2163 return BINARY_ADD;
2164 case Sub:
2165 return BINARY_SUBTRACT;
2166 case Mult:
2167 return BINARY_MULTIPLY;
2168 case Div:
2169 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2170 return BINARY_TRUE_DIVIDE;
2171 else
2172 return BINARY_DIVIDE;
2173 case Mod:
2174 return BINARY_MODULO;
2175 case Pow:
2176 return BINARY_POWER;
2177 case LShift:
2178 return BINARY_LSHIFT;
2179 case RShift:
2180 return BINARY_RSHIFT;
2181 case BitOr:
2182 return BINARY_OR;
2183 case BitXor:
2184 return BINARY_XOR;
2185 case BitAnd:
2186 return BINARY_AND;
2187 case FloorDiv:
2188 return BINARY_FLOOR_DIVIDE;
2189 }
2190 return 0;
2191}
2192
2193static int
2194cmpop(cmpop_ty op)
2195{
2196 switch (op) {
2197 case Eq:
2198 return PyCmp_EQ;
2199 case NotEq:
2200 return PyCmp_NE;
2201 case Lt:
2202 return PyCmp_LT;
2203 case LtE:
2204 return PyCmp_LE;
2205 case Gt:
2206 return PyCmp_GT;
2207 case GtE:
2208 return PyCmp_GE;
2209 case Is:
2210 return PyCmp_IS;
2211 case IsNot:
2212 return PyCmp_IS_NOT;
2213 case In:
2214 return PyCmp_IN;
2215 case NotIn:
2216 return PyCmp_NOT_IN;
2217 }
2218 return PyCmp_BAD;
2219}
2220
2221static int
2222inplace_binop(struct compiler *c, operator_ty op)
2223{
2224 switch (op) {
2225 case Add:
2226 return INPLACE_ADD;
2227 case Sub:
2228 return INPLACE_SUBTRACT;
2229 case Mult:
2230 return INPLACE_MULTIPLY;
2231 case Div:
2232 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2233 return INPLACE_TRUE_DIVIDE;
2234 else
2235 return INPLACE_DIVIDE;
2236 case Mod:
2237 return INPLACE_MODULO;
2238 case Pow:
2239 return INPLACE_POWER;
2240 case LShift:
2241 return INPLACE_LSHIFT;
2242 case RShift:
2243 return INPLACE_RSHIFT;
2244 case BitOr:
2245 return INPLACE_OR;
2246 case BitXor:
2247 return INPLACE_XOR;
2248 case BitAnd:
2249 return INPLACE_AND;
2250 case FloorDiv:
2251 return INPLACE_FLOOR_DIVIDE;
2252 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002253 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002254 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 return 0;
2256}
2257
2258static int
2259compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2260{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002261 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2263
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002265 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 /* XXX AugStore isn't used anywhere! */
2267
2268 /* First check for assignment to __debug__. Param? */
2269 if ((ctx == Store || ctx == AugStore || ctx == Del)
2270 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2271 return compiler_error(c, "can not assign to __debug__");
2272 }
2273
Jeremy Hylton37075c52007-02-27 01:01:59 +00002274mangled = _Py_Mangle(c->u->u_private, name);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002275 if (!mangled)
2276 return 0;
2277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278 op = 0;
2279 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002280 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 switch (scope) {
2282 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002283 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284 optype = OP_DEREF;
2285 break;
2286 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002287 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 optype = OP_DEREF;
2289 break;
2290 case LOCAL:
2291 if (c->u->u_ste->ste_type == FunctionBlock)
2292 optype = OP_FAST;
2293 break;
2294 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002295 if (c->u->u_ste->ste_type == FunctionBlock &&
2296 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 optype = OP_GLOBAL;
2298 break;
2299 case GLOBAL_EXPLICIT:
2300 optype = OP_GLOBAL;
2301 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002302 default:
2303 /* scope can be 0 */
2304 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 }
2306
2307 /* XXX Leave assert here, but handle __doc__ and the like better */
2308 assert(scope || PyString_AS_STRING(name)[0] == '_');
2309
2310 switch (optype) {
2311 case OP_DEREF:
2312 switch (ctx) {
2313 case Load: op = LOAD_DEREF; break;
2314 case Store: op = STORE_DEREF; break;
2315 case AugLoad:
2316 case AugStore:
2317 break;
2318 case Del:
2319 PyErr_Format(PyExc_SyntaxError,
2320 "can not delete variable '%s' referenced "
2321 "in nested scope",
2322 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002323 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002326 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002327 PyErr_SetString(PyExc_SystemError,
2328 "param invalid for deref variable");
2329 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330 }
2331 break;
2332 case OP_FAST:
2333 switch (ctx) {
2334 case Load: op = LOAD_FAST; break;
2335 case Store: op = STORE_FAST; break;
2336 case Del: op = DELETE_FAST; break;
2337 case AugLoad:
2338 case AugStore:
2339 break;
2340 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002341 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002342 PyErr_SetString(PyExc_SystemError,
2343 "param invalid for local variable");
2344 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002346 ADDOP_O(c, op, mangled, varnames);
2347 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002348 return 1;
2349 case OP_GLOBAL:
2350 switch (ctx) {
2351 case Load: op = LOAD_GLOBAL; break;
2352 case Store: op = STORE_GLOBAL; break;
2353 case Del: op = DELETE_GLOBAL; break;
2354 case AugLoad:
2355 case AugStore:
2356 break;
2357 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002358 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002359 PyErr_SetString(PyExc_SystemError,
2360 "param invalid for global variable");
2361 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362 }
2363 break;
2364 case OP_NAME:
2365 switch (ctx) {
2366 case Load: op = LOAD_NAME; break;
2367 case Store: op = STORE_NAME; break;
2368 case Del: op = DELETE_NAME; break;
2369 case AugLoad:
2370 case AugStore:
2371 break;
2372 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002373 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002374 PyErr_SetString(PyExc_SystemError,
2375 "param invalid for name variable");
2376 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377 }
2378 break;
2379 }
2380
2381 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002382 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002383 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002384 if (arg < 0)
2385 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002386 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387}
2388
2389static int
2390compiler_boolop(struct compiler *c, expr_ty e)
2391{
2392 basicblock *end;
2393 int jumpi, i, n;
2394 asdl_seq *s;
2395
2396 assert(e->kind == BoolOp_kind);
2397 if (e->v.BoolOp.op == And)
2398 jumpi = JUMP_IF_FALSE;
2399 else
2400 jumpi = JUMP_IF_TRUE;
2401 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002402 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403 return 0;
2404 s = e->v.BoolOp.values;
2405 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002406 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002408 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409 ADDOP_JREL(c, jumpi, end);
2410 ADDOP(c, POP_TOP)
2411 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002412 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 compiler_use_next_block(c, end);
2414 return 1;
2415}
2416
2417static int
2418compiler_list(struct compiler *c, expr_ty e)
2419{
2420 int n = asdl_seq_LEN(e->v.List.elts);
2421 if (e->v.List.ctx == Store) {
2422 ADDOP_I(c, UNPACK_SEQUENCE, n);
2423 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002424 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425 if (e->v.List.ctx == Load) {
2426 ADDOP_I(c, BUILD_LIST, n);
2427 }
2428 return 1;
2429}
2430
2431static int
2432compiler_tuple(struct compiler *c, expr_ty e)
2433{
2434 int n = asdl_seq_LEN(e->v.Tuple.elts);
2435 if (e->v.Tuple.ctx == Store) {
2436 ADDOP_I(c, UNPACK_SEQUENCE, n);
2437 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002438 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 if (e->v.Tuple.ctx == Load) {
2440 ADDOP_I(c, BUILD_TUPLE, n);
2441 }
2442 return 1;
2443}
2444
2445static int
2446compiler_compare(struct compiler *c, expr_ty e)
2447{
2448 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002449 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450
2451 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2452 VISIT(c, expr, e->v.Compare.left);
2453 n = asdl_seq_LEN(e->v.Compare.ops);
2454 assert(n > 0);
2455 if (n > 1) {
2456 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002457 if (cleanup == NULL)
2458 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002459 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002460 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 }
2462 for (i = 1; i < n; i++) {
2463 ADDOP(c, DUP_TOP);
2464 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002466 cmpop((cmpop_ty)(asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002467 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2469 NEXT_BLOCK(c);
2470 ADDOP(c, POP_TOP);
2471 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002472 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002473 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002475 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002477 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 if (n > 1) {
2479 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002480 if (end == NULL)
2481 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 ADDOP_JREL(c, JUMP_FORWARD, end);
2483 compiler_use_next_block(c, cleanup);
2484 ADDOP(c, ROT_TWO);
2485 ADDOP(c, POP_TOP);
2486 compiler_use_next_block(c, end);
2487 }
2488 return 1;
2489}
2490
2491static int
2492compiler_call(struct compiler *c, expr_ty e)
2493{
2494 int n, code = 0;
2495
2496 VISIT(c, expr, e->v.Call.func);
2497 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002498 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002500 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2502 }
2503 if (e->v.Call.starargs) {
2504 VISIT(c, expr, e->v.Call.starargs);
2505 code |= 1;
2506 }
2507 if (e->v.Call.kwargs) {
2508 VISIT(c, expr, e->v.Call.kwargs);
2509 code |= 2;
2510 }
2511 switch (code) {
2512 case 0:
2513 ADDOP_I(c, CALL_FUNCTION, n);
2514 break;
2515 case 1:
2516 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2517 break;
2518 case 2:
2519 ADDOP_I(c, CALL_FUNCTION_KW, n);
2520 break;
2521 case 3:
2522 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2523 break;
2524 }
2525 return 1;
2526}
2527
2528static int
2529compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002530 asdl_seq *generators, int gen_index,
2531 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532{
2533 /* generate code for the iterator, then each of the ifs,
2534 and then write to the element */
2535
2536 comprehension_ty l;
2537 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002538 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539
2540 start = compiler_new_block(c);
2541 skip = compiler_new_block(c);
2542 if_cleanup = compiler_new_block(c);
2543 anchor = compiler_new_block(c);
2544
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002545 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2546 anchor == NULL)
2547 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548
Anthony Baxter7b782b62006-04-11 12:01:56 +00002549 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 VISIT(c, expr, l->iter);
2551 ADDOP(c, GET_ITER);
2552 compiler_use_next_block(c, start);
2553 ADDOP_JREL(c, FOR_ITER, anchor);
2554 NEXT_BLOCK(c);
2555 VISIT(c, expr, l->target);
2556
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002557 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558 n = asdl_seq_LEN(l->ifs);
2559 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002560 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 VISIT(c, expr, e);
2562 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2563 NEXT_BLOCK(c);
2564 ADDOP(c, POP_TOP);
2565 }
2566
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002567 if (++gen_index < asdl_seq_LEN(generators))
2568 if (!compiler_listcomp_generator(c, tmpname,
2569 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002572 /* only append after the last for generator */
2573 if (gen_index >= asdl_seq_LEN(generators)) {
2574 if (!compiler_nameop(c, tmpname, Load))
2575 return 0;
2576 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002577 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002578
2579 compiler_use_next_block(c, skip);
2580 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 for (i = 0; i < n; i++) {
2582 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 if (i == 0)
2584 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 ADDOP(c, POP_TOP);
2586 }
2587 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2588 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002589 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002591 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 return 0;
2593
2594 return 1;
2595}
2596
2597static int
2598compiler_listcomp(struct compiler *c, expr_ty e)
2599{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 asdl_seq *generators = e->v.ListComp.generators;
2603
2604 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002605 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 if (!tmp)
2607 return 0;
2608 ADDOP_I(c, BUILD_LIST, 0);
2609 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2612 e->v.ListComp.elt);
2613 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 return rc;
2615}
2616
2617static int
2618compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 asdl_seq *generators, int gen_index,
2620 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621{
2622 /* generate code for the iterator, then each of the ifs,
2623 and then write to the element */
2624
2625 comprehension_ty ge;
2626 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
2629 start = compiler_new_block(c);
2630 skip = compiler_new_block(c);
2631 if_cleanup = compiler_new_block(c);
2632 anchor = compiler_new_block(c);
2633 end = compiler_new_block(c);
2634
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002635 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 anchor == NULL || end == NULL)
2637 return 0;
2638
Anthony Baxter7b782b62006-04-11 12:01:56 +00002639 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 ADDOP_JREL(c, SETUP_LOOP, end);
2641 if (!compiler_push_fblock(c, LOOP, start))
2642 return 0;
2643
2644 if (gen_index == 0) {
2645 /* Receive outermost iter as an implicit argument */
2646 c->u->u_argcount = 1;
2647 ADDOP_I(c, LOAD_FAST, 0);
2648 }
2649 else {
2650 /* Sub-iter - calculate on the fly */
2651 VISIT(c, expr, ge->iter);
2652 ADDOP(c, GET_ITER);
2653 }
2654 compiler_use_next_block(c, start);
2655 ADDOP_JREL(c, FOR_ITER, anchor);
2656 NEXT_BLOCK(c);
2657 VISIT(c, expr, ge->target);
2658
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 n = asdl_seq_LEN(ge->ifs);
2661 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002662 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 VISIT(c, expr, e);
2664 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2665 NEXT_BLOCK(c);
2666 ADDOP(c, POP_TOP);
2667 }
2668
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2671 return 0;
2672
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 /* only append after the last 'for' generator */
2674 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 VISIT(c, expr, elt);
2676 ADDOP(c, YIELD_VALUE);
2677 ADDOP(c, POP_TOP);
2678
2679 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 for (i = 0; i < n; i++) {
2682 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 compiler_use_next_block(c, if_cleanup);
2685
2686 ADDOP(c, POP_TOP);
2687 }
2688 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2689 compiler_use_next_block(c, anchor);
2690 ADDOP(c, POP_BLOCK);
2691 compiler_pop_fblock(c, LOOP, start);
2692 compiler_use_next_block(c, end);
2693
2694 return 1;
2695}
2696
2697static int
2698compiler_genexp(struct compiler *c, expr_ty e)
2699{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002700 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 PyCodeObject *co;
2702 expr_ty outermost_iter = ((comprehension_ty)
2703 (asdl_seq_GET(e->v.GeneratorExp.generators,
2704 0)))->iter;
2705
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002706 if (!name) {
2707 name = PyString_FromString("<genexpr>");
2708 if (!name)
2709 return 0;
2710 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
2712 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2713 return 0;
2714 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2715 e->v.GeneratorExp.elt);
2716 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002717 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 if (co == NULL)
2719 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002722 Py_DECREF(co);
2723
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 VISIT(c, expr, outermost_iter);
2725 ADDOP(c, GET_ITER);
2726 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
2728 return 1;
2729}
2730
2731static int
2732compiler_visit_keyword(struct compiler *c, keyword_ty k)
2733{
2734 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2735 VISIT(c, expr, k->value);
2736 return 1;
2737}
2738
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002739/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 whether they are true or false.
2741
2742 Return values: 1 for true, 0 for false, -1 for non-constant.
2743 */
2744
2745static int
2746expr_constant(expr_ty e)
2747{
2748 switch (e->kind) {
2749 case Num_kind:
2750 return PyObject_IsTrue(e->v.Num.n);
2751 case Str_kind:
2752 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002753 case Name_kind:
2754 /* __debug__ is not assignable, so we can optimize
2755 * it away in if and while statements */
2756 if (strcmp(PyString_AS_STRING(e->v.Name.id),
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002757 "__debug__") == 0)
Georg Brandlddbaa662006-06-04 21:56:52 +00002758 return ! Py_OptimizeFlag;
2759 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760 default:
2761 return -1;
2762 }
2763}
2764
Guido van Rossumc2e20742006-02-27 22:32:47 +00002765/*
2766 Implements the with statement from PEP 343.
2767
2768 The semantics outlined in that PEP are as follows:
2769
2770 with EXPR as VAR:
2771 BLOCK
2772
2773 It is implemented roughly as:
2774
Guido van Rossumda5b7012006-05-02 19:47:52 +00002775 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002776 exit = context.__exit__ # not calling it
2777 value = context.__enter__()
2778 try:
2779 VAR = value # if VAR present in the syntax
2780 BLOCK
2781 finally:
2782 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002783 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002784 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002785 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002786 exit(*exc)
2787 */
2788static int
2789compiler_with(struct compiler *c, stmt_ty s)
2790{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002791 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002792 basicblock *block, *finally;
2793 identifier tmpexit, tmpvalue = NULL;
2794
2795 assert(s->kind == With_kind);
2796
Guido van Rossumc2e20742006-02-27 22:32:47 +00002797 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002798 enter_attr = PyString_InternFromString("__enter__");
2799 if (!enter_attr)
2800 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 }
2802 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002803 exit_attr = PyString_InternFromString("__exit__");
2804 if (!exit_attr)
2805 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002806 }
2807
2808 block = compiler_new_block(c);
2809 finally = compiler_new_block(c);
2810 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002811 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812
2813 /* Create a temporary variable to hold context.__exit__ */
2814 tmpexit = compiler_new_tmpname(c);
2815 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 PyArena_AddPyObject(c->c_arena, tmpexit);
2818
2819 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821 We need to do this rather than preserving it on the stack
2822 because SETUP_FINALLY remembers the stack level.
2823 We need to do the assignment *inside* the try/finally
2824 so that context.__exit__() is called when the assignment
2825 fails. But we need to call context.__enter__() *before*
2826 the try/finally so that if it fails we won't call
2827 context.__exit__().
2828 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 if (tmpvalue == NULL)
2831 return 0;
2832 PyArena_AddPyObject(c->c_arena, tmpvalue);
2833 }
2834
Guido van Rossumda5b7012006-05-02 19:47:52 +00002835 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837
2838 /* Squirrel away context.__exit__ */
2839 ADDOP(c, DUP_TOP);
2840 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2841 if (!compiler_nameop(c, tmpexit, Store))
2842 return 0;
2843
2844 /* Call context.__enter__() */
2845 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2846 ADDOP_I(c, CALL_FUNCTION, 0);
2847
2848 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002849 /* Store it in tmpvalue */
2850 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851 return 0;
2852 }
2853 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002854 /* Discard result from context.__enter__() */
2855 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856 }
2857
2858 /* Start the try block */
2859 ADDOP_JREL(c, SETUP_FINALLY, finally);
2860
2861 compiler_use_next_block(c, block);
2862 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002864 }
2865
2866 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002867 /* Bind saved result of context.__enter__() to VAR */
2868 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869 !compiler_nameop(c, tmpvalue, Del))
2870 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002872 }
2873
2874 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002875 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002876
2877 /* End of try block; start the finally block */
2878 ADDOP(c, POP_BLOCK);
2879 compiler_pop_fblock(c, FINALLY_TRY, block);
2880
2881 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2882 compiler_use_next_block(c, finally);
2883 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002884 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002885
2886 /* Finally block starts; push tmpexit and issue our magic opcode. */
2887 if (!compiler_nameop(c, tmpexit, Load) ||
2888 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002889 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002890 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002891
2892 /* Finally block ends. */
2893 ADDOP(c, END_FINALLY);
2894 compiler_pop_fblock(c, FINALLY_END, finally);
2895 return 1;
2896}
2897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898static int
2899compiler_visit_expr(struct compiler *c, expr_ty e)
2900{
2901 int i, n;
2902
Neal Norwitzf733a012006-10-29 18:30:10 +00002903 /* If expr e has a different line number than the last expr/stmt,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002904 set a new line number for the next instruction.
2905 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 if (e->lineno > c->u->u_lineno) {
2907 c->u->u_lineno = e->lineno;
2908 c->u->u_lineno_set = false;
2909 }
2910 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 VISIT(c, expr, e->v.BinOp.left);
2915 VISIT(c, expr, e->v.BinOp.right);
2916 ADDOP(c, binop(c, e->v.BinOp.op));
2917 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002918 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919 VISIT(c, expr, e->v.UnaryOp.operand);
2920 ADDOP(c, unaryop(e->v.UnaryOp.op));
2921 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002924 case IfExp_kind:
2925 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 /* XXX get rid of arg? */
2928 ADDOP_I(c, BUILD_MAP, 0);
2929 n = asdl_seq_LEN(e->v.Dict.values);
2930 /* We must arrange things just right for STORE_SUBSCR.
2931 It wants the stack to look like (value) (dict) (key) */
2932 for (i = 0; i < n; i++) {
2933 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002934 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002935 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002937 VISIT(c, expr,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00002938 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 ADDOP(c, STORE_SUBSCR);
2940 }
2941 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002942 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 return compiler_genexp(c, e);
2946 case Yield_kind:
2947 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002948 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 if (e->v.Yield.value) {
2950 VISIT(c, expr, e->v.Yield.value);
2951 }
2952 else {
2953 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2954 }
2955 ADDOP(c, YIELD_VALUE);
2956 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002961 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 VISIT(c, expr, e->v.Repr.value);
2963 ADDOP(c, UNARY_CONVERT);
2964 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002965 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2967 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002968 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2970 break;
2971 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002972 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973 if (e->v.Attribute.ctx != AugStore)
2974 VISIT(c, expr, e->v.Attribute.value);
2975 switch (e->v.Attribute.ctx) {
2976 case AugLoad:
2977 ADDOP(c, DUP_TOP);
2978 /* Fall through to load */
2979 case Load:
2980 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2981 break;
2982 case AugStore:
2983 ADDOP(c, ROT_TWO);
2984 /* Fall through to save */
2985 case Store:
2986 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2987 break;
2988 case Del:
2989 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2990 break;
2991 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002992 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002993 PyErr_SetString(PyExc_SystemError,
2994 "param invalid in attribute expression");
2995 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 }
2997 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 switch (e->v.Subscript.ctx) {
3000 case AugLoad:
3001 VISIT(c, expr, e->v.Subscript.value);
3002 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3003 break;
3004 case Load:
3005 VISIT(c, expr, e->v.Subscript.value);
3006 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3007 break;
3008 case AugStore:
3009 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3010 break;
3011 case Store:
3012 VISIT(c, expr, e->v.Subscript.value);
3013 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3014 break;
3015 case Del:
3016 VISIT(c, expr, e->v.Subscript.value);
3017 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3018 break;
3019 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003020 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003021 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003022 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003023 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 }
3025 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003026 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3028 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003029 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003031 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032 return compiler_tuple(c, e);
3033 }
3034 return 1;
3035}
3036
3037static int
3038compiler_augassign(struct compiler *c, stmt_ty s)
3039{
3040 expr_ty e = s->v.AugAssign.target;
3041 expr_ty auge;
3042
3043 assert(s->kind == AugAssign_kind);
3044
3045 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003046 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003048 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 if (auge == NULL)
3050 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 VISIT(c, expr, auge);
3052 VISIT(c, expr, s->v.AugAssign.value);
3053 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3054 auge->v.Attribute.ctx = AugStore;
3055 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 break;
3057 case Subscript_kind:
3058 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003059 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003060 if (auge == NULL)
3061 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 VISIT(c, expr, auge);
3063 VISIT(c, expr, s->v.AugAssign.value);
3064 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003066 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003067 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003069 if (!compiler_nameop(c, e->v.Name.id, Load))
3070 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 VISIT(c, expr, s->v.AugAssign.value);
3072 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3073 return compiler_nameop(c, e->v.Name.id, Store);
3074 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003075 PyErr_Format(PyExc_SystemError,
3076 "invalid node type (%d) for augmented assignment",
3077 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003078 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003079 }
3080 return 1;
3081}
3082
3083static int
3084compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3085{
3086 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003087 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3088 PyErr_SetString(PyExc_SystemError,
3089 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003091 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 f = &c->u->u_fblock[c->u->u_nfblocks++];
3093 f->fb_type = t;
3094 f->fb_block = b;
3095 return 1;
3096}
3097
3098static void
3099compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3100{
3101 struct compiler_unit *u = c->u;
3102 assert(u->u_nfblocks > 0);
3103 u->u_nfblocks--;
3104 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3105 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3106}
3107
Jeremy Hylton82271f12006-10-04 02:24:52 +00003108static int
3109compiler_in_loop(struct compiler *c) {
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003110 int i;
3111 struct compiler_unit *u = c->u;
3112 for (i = 0; i < u->u_nfblocks; ++i) {
3113 if (u->u_fblock[i].fb_type == LOOP)
3114 return 1;
3115 }
3116 return 0;
Jeremy Hylton82271f12006-10-04 02:24:52 +00003117}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118/* Raises a SyntaxError and returns 0.
3119 If something goes wrong, a different exception may be raised.
3120*/
3121
3122static int
3123compiler_error(struct compiler *c, const char *errstr)
3124{
3125 PyObject *loc;
3126 PyObject *u = NULL, *v = NULL;
3127
3128 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3129 if (!loc) {
3130 Py_INCREF(Py_None);
3131 loc = Py_None;
3132 }
3133 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3134 Py_None, loc);
3135 if (!u)
3136 goto exit;
3137 v = Py_BuildValue("(zO)", errstr, u);
3138 if (!v)
3139 goto exit;
3140 PyErr_SetObject(PyExc_SyntaxError, v);
3141 exit:
3142 Py_DECREF(loc);
3143 Py_XDECREF(u);
3144 Py_XDECREF(v);
3145 return 0;
3146}
3147
3148static int
3149compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003153
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003154 /* XXX this code is duplicated */
3155 switch (ctx) {
3156 case AugLoad: /* fall through to Load */
3157 case Load: op = BINARY_SUBSCR; break;
3158 case AugStore:/* fall through to Store */
3159 case Store: op = STORE_SUBSCR; break;
3160 case Del: op = DELETE_SUBSCR; break;
3161 case Param:
3162 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003163 "invalid %s kind %d in subscript\n",
3164 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 return 0;
3166 }
3167 if (ctx == AugLoad) {
3168 ADDOP_I(c, DUP_TOPX, 2);
3169 }
3170 else if (ctx == AugStore) {
3171 ADDOP(c, ROT_THREE);
3172 }
3173 ADDOP(c, op);
3174 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175}
3176
3177static int
3178compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3179{
3180 int n = 2;
3181 assert(s->kind == Slice_kind);
3182
3183 /* only handles the cases where BUILD_SLICE is emitted */
3184 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 }
3187 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003188 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 }
3194 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 }
3197
3198 if (s->v.Slice.step) {
3199 n++;
3200 VISIT(c, expr, s->v.Slice.step);
3201 }
3202 ADDOP_I(c, BUILD_SLICE, n);
3203 return 1;
3204}
3205
3206static int
3207compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3208{
3209 int op = 0, slice_offset = 0, stack_count = 0;
3210
3211 assert(s->v.Slice.step == NULL);
3212 if (s->v.Slice.lower) {
3213 slice_offset++;
3214 stack_count++;
3215 if (ctx != AugStore)
3216 VISIT(c, expr, s->v.Slice.lower);
3217 }
3218 if (s->v.Slice.upper) {
3219 slice_offset += 2;
3220 stack_count++;
3221 if (ctx != AugStore)
3222 VISIT(c, expr, s->v.Slice.upper);
3223 }
3224
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003225 if (ctx == AugLoad) {
3226 switch (stack_count) {
3227 case 0: ADDOP(c, DUP_TOP); break;
3228 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3229 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3230 }
3231 }
3232 else if (ctx == AugStore) {
3233 switch (stack_count) {
3234 case 0: ADDOP(c, ROT_TWO); break;
3235 case 1: ADDOP(c, ROT_THREE); break;
3236 case 2: ADDOP(c, ROT_FOUR); break;
3237 }
3238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239
3240 switch (ctx) {
3241 case AugLoad: /* fall through to Load */
3242 case Load: op = SLICE; break;
3243 case AugStore:/* fall through to Store */
3244 case Store: op = STORE_SLICE; break;
3245 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003246 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003247 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003248 PyErr_SetString(PyExc_SystemError,
3249 "param invalid in simple slice");
3250 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 }
3252
3253 ADDOP(c, op + slice_offset);
3254 return 1;
3255}
3256
3257static int
3258compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3259 expr_context_ty ctx)
3260{
3261 switch (s->kind) {
3262 case Ellipsis_kind:
3263 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3264 break;
3265 case Slice_kind:
3266 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 case Index_kind:
3268 VISIT(c, expr, s->v.Index.value);
3269 break;
3270 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003271 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003272 PyErr_SetString(PyExc_SystemError,
3273 "extended slice invalid in nested slice");
3274 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 }
3276 return 1;
3277}
3278
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279static int
3280compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3281{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003282 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003284 case Index_kind:
3285 kindname = "index";
3286 if (ctx != AugStore) {
3287 VISIT(c, expr, s->v.Index.value);
3288 }
3289 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003291 kindname = "ellipsis";
3292 if (ctx != AugStore) {
3293 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 break;
3296 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003297 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 if (!s->v.Slice.step)
3299 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003300 if (ctx != AugStore) {
3301 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 return 0;
3303 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003304 break;
3305 case ExtSlice_kind:
3306 kindname = "extended slice";
3307 if (ctx != AugStore) {
3308 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3309 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003310 slice_ty sub = (slice_ty)asdl_seq_GET(
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003311 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003312 if (!compiler_visit_nested_slice(c, sub, ctx))
3313 return 0;
3314 }
3315 ADDOP_I(c, BUILD_TUPLE, n);
3316 }
3317 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003318 default:
3319 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003320 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003321 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003323 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324}
3325
Neal Norwitzf733a012006-10-29 18:30:10 +00003326
3327/* End of the compiler section, beginning of the assembler section */
3328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329/* do depth-first search of basic block graph, starting with block.
3330 post records the block indices in post-order.
3331
3332 XXX must handle implicit jumps from one block to next
3333*/
3334
Neal Norwitzf733a012006-10-29 18:30:10 +00003335struct assembler {
3336 PyObject *a_bytecode; /* string containing bytecode */
3337 int a_offset; /* offset into bytecode */
3338 int a_nblocks; /* number of reachable blocks */
3339 basicblock **a_postorder; /* list of blocks in dfs postorder */
3340 PyObject *a_lnotab; /* string containing lnotab */
3341 int a_lnotab_off; /* offset into lnotab */
3342 int a_lineno; /* last lineno of emitted instruction */
3343 int a_lineno_off; /* bytecode offset of last lineno */
3344};
3345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346static void
3347dfs(struct compiler *c, basicblock *b, struct assembler *a)
3348{
3349 int i;
3350 struct instr *instr = NULL;
3351
3352 if (b->b_seen)
3353 return;
3354 b->b_seen = 1;
3355 if (b->b_next != NULL)
3356 dfs(c, b->b_next, a);
3357 for (i = 0; i < b->b_iused; i++) {
3358 instr = &b->b_instr[i];
3359 if (instr->i_jrel || instr->i_jabs)
3360 dfs(c, instr->i_target, a);
3361 }
3362 a->a_postorder[a->a_nblocks++] = b;
3363}
3364
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003365static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003366stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3367{
3368 int i;
3369 struct instr *instr;
3370 if (b->b_seen || b->b_startdepth >= depth)
3371 return maxdepth;
3372 b->b_seen = 1;
3373 b->b_startdepth = depth;
3374 for (i = 0; i < b->b_iused; i++) {
3375 instr = &b->b_instr[i];
3376 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3377 if (depth > maxdepth)
3378 maxdepth = depth;
3379 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3380 if (instr->i_jrel || instr->i_jabs) {
3381 maxdepth = stackdepth_walk(c, instr->i_target,
3382 depth, maxdepth);
3383 if (instr->i_opcode == JUMP_ABSOLUTE ||
3384 instr->i_opcode == JUMP_FORWARD) {
3385 goto out; /* remaining code is dead */
3386 }
3387 }
3388 }
3389 if (b->b_next)
3390 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3391out:
3392 b->b_seen = 0;
3393 return maxdepth;
3394}
3395
3396/* Find the flow path that needs the largest stack. We assume that
3397 * cycles in the flow graph have no net effect on the stack depth.
3398 */
3399static int
3400stackdepth(struct compiler *c)
3401{
3402 basicblock *b, *entryblock;
3403 entryblock = NULL;
3404 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3405 b->b_seen = 0;
3406 b->b_startdepth = INT_MIN;
3407 entryblock = b;
3408 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003409 if (!entryblock)
3410 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 return stackdepth_walk(c, entryblock, 0, 0);
3412}
3413
3414static int
3415assemble_init(struct assembler *a, int nblocks, int firstlineno)
3416{
3417 memset(a, 0, sizeof(struct assembler));
3418 a->a_lineno = firstlineno;
3419 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3420 if (!a->a_bytecode)
3421 return 0;
3422 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3423 if (!a->a_lnotab)
3424 return 0;
3425 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003427 if (!a->a_postorder) {
3428 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003429 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003430 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 return 1;
3432}
3433
3434static void
3435assemble_free(struct assembler *a)
3436{
3437 Py_XDECREF(a->a_bytecode);
3438 Py_XDECREF(a->a_lnotab);
3439 if (a->a_postorder)
3440 PyObject_Free(a->a_postorder);
3441}
3442
3443/* Return the size of a basic block in bytes. */
3444
3445static int
3446instrsize(struct instr *instr)
3447{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003448 if (!instr->i_hasarg)
3449 return 1;
3450 if (instr->i_oparg > 0xffff)
3451 return 6;
3452 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003453}
3454
3455static int
3456blocksize(basicblock *b)
3457{
3458 int i;
3459 int size = 0;
3460
3461 for (i = 0; i < b->b_iused; i++)
3462 size += instrsize(&b->b_instr[i]);
3463 return size;
3464}
3465
3466/* All about a_lnotab.
3467
3468c_lnotab is an array of unsigned bytes disguised as a Python string.
3469It is used to map bytecode offsets to source code line #s (when needed
3470for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003471
Tim Peters2a7f3842001-06-09 09:26:21 +00003472The array is conceptually a list of
3473 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003474pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003475
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476 byte code offset source code line number
3477 0 1
3478 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003479 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003480 350 307
3481 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003482
3483The first trick is that these numbers aren't stored, only the increments
3484from one row to the next (this doesn't really work, but it's a start):
3485
3486 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3487
3488The second trick is that an unsigned byte can't hold negative values, or
3489values larger than 255, so (a) there's a deep assumption that byte code
3490offsets and their corresponding line #s both increase monotonically, and (b)
3491if at least one column jumps by more than 255 from one row to the next, more
3492than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003494part. A user of c_lnotab desiring to find the source line number
3495corresponding to a bytecode address A should do something like this
3496
3497 lineno = addr = 0
3498 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 addr += addr_incr
3500 if addr > A:
3501 return lineno
3502 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003503
3504In order for this to work, when the addr field increments by more than 255,
3505the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003506increment is < 256. So, in the example above, assemble_lnotab (it used
3507to be called com_set_lineno) should not (as was actually done until 2.2)
3508expand 300, 300 to 255, 255, 45, 45,
Jeremy Hylton819de6c2007-02-27 16:13:23 +00003509 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003510*/
3511
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003512static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003514{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515 int d_bytecode, d_lineno;
3516 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003517 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518
3519 d_bytecode = a->a_offset - a->a_lineno_off;
3520 d_lineno = i->i_lineno - a->a_lineno;
3521
3522 assert(d_bytecode >= 0);
3523 assert(d_lineno >= 0);
3524
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003525 /* XXX(nnorwitz): is there a better way to handle this?
3526 for loops are special, we want to be able to trace them
3527 each time around, so we need to set an extra line number. */
Nick Coghlan3af0e782007-08-25 04:32:07 +00003528 /* XXX(ncoghlan): while loops need this too */
3529 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003530 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003533 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 nbytes = a->a_lnotab_off + 2 * ncodes;
3535 len = PyString_GET_SIZE(a->a_lnotab);
3536 if (nbytes >= len) {
3537 if (len * 2 < nbytes)
3538 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003539 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 len *= 2;
3541 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3542 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003543 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003544 lnotab = (unsigned char *)
3545 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003546 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 *lnotab++ = 255;
3548 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003549 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 d_bytecode -= ncodes * 255;
3551 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 assert(d_bytecode <= 255);
3554 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003555 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 nbytes = a->a_lnotab_off + 2 * ncodes;
3557 len = PyString_GET_SIZE(a->a_lnotab);
3558 if (nbytes >= len) {
3559 if (len * 2 < nbytes)
3560 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003561 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 len *= 2;
3563 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3564 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003565 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003566 lnotab = (unsigned char *)
3567 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003569 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003571 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003573 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003574 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 d_lineno -= ncodes * 255;
3576 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003577 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579 len = PyString_GET_SIZE(a->a_lnotab);
3580 if (a->a_lnotab_off + 2 >= len) {
3581 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003582 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003583 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003584 lnotab = (unsigned char *)
3585 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587 a->a_lnotab_off += 2;
3588 if (d_bytecode) {
3589 *lnotab++ = d_bytecode;
3590 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003591 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003592 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 *lnotab++ = 0;
3594 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003595 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 a->a_lineno = i->i_lineno;
3597 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003598 return 1;
3599}
3600
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601/* assemble_emit()
3602 Extend the bytecode with a new instruction.
3603 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003604*/
3605
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003606static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003608{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003609 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003610 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 char *code;
3612
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003613 size = instrsize(i);
3614 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003616 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003619 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 if (a->a_offset + size >= len) {
3621 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003622 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3625 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003626 if (size == 6) {
3627 assert(i->i_hasarg);
3628 *code++ = (char)EXTENDED_ARG;
3629 *code++ = ext & 0xff;
3630 *code++ = ext >> 8;
3631 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003632 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003634 if (i->i_hasarg) {
3635 assert(size == 3 || size == 6);
3636 *code++ = arg & 0xff;
3637 *code++ = arg >> 8;
3638 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003640}
3641
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003644{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003646 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003647 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649 /* Compute the size of each block and fixup jump args.
3650 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003651start:
3652 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003654 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 bsize = blocksize(b);
3656 b->b_offset = totsize;
3657 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003658 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003659 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3661 bsize = b->b_offset;
3662 for (i = 0; i < b->b_iused; i++) {
3663 struct instr *instr = &b->b_instr[i];
3664 /* Relative jumps are computed relative to
3665 the instruction pointer after fetching
3666 the jump instruction.
3667 */
3668 bsize += instrsize(instr);
3669 if (instr->i_jabs)
3670 instr->i_oparg = instr->i_target->b_offset;
3671 else if (instr->i_jrel) {
3672 int delta = instr->i_target->b_offset - bsize;
3673 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003674 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003675 else
3676 continue;
3677 if (instr->i_oparg > 0xffff)
3678 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003679 }
3680 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003681
3682 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003683 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003684 with a better solution.
3685
3686 In the meantime, should the goto be dropped in favor
3687 of a loop?
3688
3689 The issue is that in the first loop blocksize() is called
3690 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003691 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003692 i_oparg is calculated in the second loop above.
3693
3694 So we loop until we stop seeing new EXTENDED_ARGs.
3695 The only EXTENDED_ARGs that could be popping up are
3696 ones in jump instructions. So this should converge
3697 fairly quickly.
3698 */
3699 if (last_extended_arg_count != extended_arg_count) {
3700 last_extended_arg_count = extended_arg_count;
3701 goto start;
3702 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003703}
3704
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003705static PyObject *
3706dict_keys_inorder(PyObject *dict, int offset)
3707{
3708 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003709 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003710
3711 tuple = PyTuple_New(size);
3712 if (tuple == NULL)
3713 return NULL;
3714 while (PyDict_Next(dict, &pos, &k, &v)) {
3715 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003716 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003717 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003718 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003719 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003720 PyTuple_SET_ITEM(tuple, i - offset, k);
3721 }
3722 return tuple;
3723}
3724
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003725static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003727{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728 PySTEntryObject *ste = c->u->u_ste;
3729 int flags = 0, n;
3730 if (ste->ste_type != ModuleBlock)
3731 flags |= CO_NEWLOCALS;
3732 if (ste->ste_type == FunctionBlock) {
3733 if (!ste->ste_unoptimized)
3734 flags |= CO_OPTIMIZED;
3735 if (ste->ste_nested)
3736 flags |= CO_NESTED;
3737 if (ste->ste_generator)
3738 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003739 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 if (ste->ste_varargs)
3741 flags |= CO_VARARGS;
3742 if (ste->ste_varkeywords)
3743 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003744 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003746
3747 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003748 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003749
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 n = PyDict_Size(c->u->u_freevars);
3751 if (n < 0)
3752 return -1;
3753 if (n == 0) {
3754 n = PyDict_Size(c->u->u_cellvars);
3755 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003756 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 if (n == 0) {
3758 flags |= CO_NOFREE;
3759 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003760 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003761
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003762 return flags;
3763}
3764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765static PyCodeObject *
3766makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003767{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 PyObject *tmp;
3769 PyCodeObject *co = NULL;
3770 PyObject *consts = NULL;
3771 PyObject *names = NULL;
3772 PyObject *varnames = NULL;
3773 PyObject *filename = NULL;
3774 PyObject *name = NULL;
3775 PyObject *freevars = NULL;
3776 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003777 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 tmp = dict_keys_inorder(c->u->u_consts, 0);
3781 if (!tmp)
3782 goto error;
3783 consts = PySequence_List(tmp); /* optimize_code requires a list */
3784 Py_DECREF(tmp);
3785
3786 names = dict_keys_inorder(c->u->u_names, 0);
3787 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3788 if (!consts || !names || !varnames)
3789 goto error;
3790
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003791 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3792 if (!cellvars)
3793 goto error;
3794 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3795 if (!freevars)
3796 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 filename = PyString_FromString(c->c_filename);
3798 if (!filename)
3799 goto error;
3800
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003801 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802 flags = compute_code_flags(c);
3803 if (flags < 0)
3804 goto error;
3805
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003806 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 if (!bytecode)
3808 goto error;
3809
3810 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3811 if (!tmp)
3812 goto error;
3813 Py_DECREF(consts);
3814 consts = tmp;
3815
3816 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3817 bytecode, consts, names, varnames,
3818 freevars, cellvars,
3819 filename, c->u->u_name,
3820 c->u->u_firstlineno,
3821 a->a_lnotab);
3822 error:
3823 Py_XDECREF(consts);
3824 Py_XDECREF(names);
3825 Py_XDECREF(varnames);
3826 Py_XDECREF(filename);
3827 Py_XDECREF(name);
3828 Py_XDECREF(freevars);
3829 Py_XDECREF(cellvars);
3830 Py_XDECREF(bytecode);
3831 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003832}
3833
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003834
3835/* For debugging purposes only */
3836#if 0
3837static void
3838dump_instr(const struct instr *i)
3839{
3840 const char *jrel = i->i_jrel ? "jrel " : "";
3841 const char *jabs = i->i_jabs ? "jabs " : "";
3842 char arg[128];
3843
3844 *arg = '\0';
3845 if (i->i_hasarg)
3846 sprintf(arg, "arg: %d ", i->i_oparg);
3847
3848 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3849 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3850}
3851
3852static void
3853dump_basicblock(const basicblock *b)
3854{
3855 const char *seen = b->b_seen ? "seen " : "";
3856 const char *b_return = b->b_return ? "return " : "";
3857 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3858 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3859 if (b->b_instr) {
3860 int i;
3861 for (i = 0; i < b->b_iused; i++) {
3862 fprintf(stderr, " [%02d] ", i);
3863 dump_instr(b->b_instr + i);
3864 }
3865 }
3866}
3867#endif
3868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869static PyCodeObject *
3870assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003871{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 basicblock *b, *entryblock;
3873 struct assembler a;
3874 int i, j, nblocks;
3875 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 /* Make sure every block that falls off the end returns None.
3878 XXX NEXT_BLOCK() isn't quite right, because if the last
3879 block ends with a jump or return b_next shouldn't set.
3880 */
3881 if (!c->u->u_curblock->b_return) {
3882 NEXT_BLOCK(c);
3883 if (addNone)
3884 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3885 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 nblocks = 0;
3889 entryblock = NULL;
3890 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3891 nblocks++;
3892 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003893 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003894
Neal Norwitzed657552006-07-10 00:04:44 +00003895 /* Set firstlineno if it wasn't explicitly set. */
3896 if (!c->u->u_firstlineno) {
3897 if (entryblock && entryblock->b_instr)
3898 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3899 else
3900 c->u->u_firstlineno = 1;
3901 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3903 goto error;
3904 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003907 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003908
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 /* Emit code in reverse postorder from dfs. */
3910 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003911 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912 for (j = 0; j < b->b_iused; j++)
3913 if (!assemble_emit(&a, &b->b_instr[j]))
3914 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003915 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003916
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3918 goto error;
3919 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3920 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 co = makecode(c, &a);
3923 error:
3924 assemble_free(&a);
3925 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003926}