blob: ed0bdcf92a57df2d450d8f037bb98fcba4add4b5 [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.
Thomas Wouters89f507f2006-12-13 04:49:30 +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
Thomas Wouters89f507f2006-12-13 04:49:30 +000011 * this file.
12 * 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
Thomas Wouters89f507f2006-12-13 04:49:30 +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_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000110 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 /* Pointer to the most recently allocated block. By following b_list
112 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116
117 int u_nfblocks;
118 struct fblockinfo u_fblock[CO_MAXBLOCKS];
119
120 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000121 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000122 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123 has been generated with current lineno */
124};
125
126/* This struct captures the global state of a compilation.
127
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128The u pointer points to the current compilation unit, while units
129for enclosing blocks are stored in c_stack. The u and c_stack are
130managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131*/
132
133struct compiler {
134 const char *c_filename;
135 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000136 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137 PyCompilerFlags *c_flags;
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142 struct compiler_unit *u; /* compiler state for current block */
143 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146};
147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148static int compiler_enter_scope(struct compiler *, identifier, void *, int);
149static void compiler_free(struct compiler *);
150static basicblock *compiler_new_block(struct compiler *);
151static int compiler_next_instr(struct compiler *, basicblock *);
152static int compiler_addop(struct compiler *, int);
153static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
154static int compiler_addop_i(struct compiler *, int, int);
155static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156static basicblock *compiler_use_new_block(struct compiler *);
157static int compiler_error(struct compiler *, const char *);
158static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
159
160static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
161static int compiler_visit_stmt(struct compiler *, stmt_ty);
162static int compiler_visit_keyword(struct compiler *, keyword_ty);
163static int compiler_visit_expr(struct compiler *, expr_ty);
164static int compiler_augassign(struct compiler *, stmt_ty);
165static int compiler_visit_slice(struct compiler *, slice_ty,
166 expr_context_ty);
167
168static int compiler_push_fblock(struct compiler *, enum fblocktype,
169 basicblock *);
170static void compiler_pop_fblock(struct compiler *, enum fblocktype,
171 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172/* Returns true if there is a loop on the fblock stack. */
173static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174
175static int inplace_binop(struct compiler *, operator_ty);
176static int expr_constant(expr_ty e);
177
Guido van Rossumc2e20742006-02-27 22:32:47 +0000178static int compiler_with(struct compiler *, stmt_ty);
179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static PyCodeObject *assemble(struct compiler *, int addNone);
181static PyObject *__doc__;
182
183PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000185{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186 /* Name mangling: __private becomes _classname__private.
187 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000188 const char *p, *name = PyString_AsString(ident);
189 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191 if (privateobj == NULL || !PyString_Check(privateobj) ||
192 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000193 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000195 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197 nlen = strlen(name);
198 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000199 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000201 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Strip leading underscores from class name */
203 while (*p == '_')
204 p++;
205 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
211 if (!ident)
212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 buffer = PyString_AS_STRING(ident);
215 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 strncpy(buffer+1, p, plen);
217 strcpy(buffer+1+plen, name);
218 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000219}
220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221static int
222compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000223{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 c->c_stack = PyList_New(0);
227 if (!c->c_stack)
228 return 0;
229
230 return 1;
231}
232
233PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000234PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236{
237 struct compiler c;
238 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000239 PyCompilerFlags local_flags;
240 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000242 if (!__doc__) {
243 __doc__ = PyString_InternFromString("__doc__");
244 if (!__doc__)
245 return NULL;
246 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247
248 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000249 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 c.c_future = PyFuture_FromAST(mod, filename);
253 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000254 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000256 local_flags.cf_flags = 0;
257 flags = &local_flags;
258 }
259 merged = c.c_future->ff_features | flags->cf_flags;
260 c.c_future->ff_features = merged;
261 flags->cf_flags = merged;
262 c.c_flags = flags;
263 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
265 c.c_st = PySymtable_Build(mod, filename, c.c_future);
266 if (c.c_st == NULL) {
267 if (!PyErr_Occurred())
268 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000269 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 }
271
272 /* XXX initialize to NULL for now, need to handle */
273 c.c_encoding = NULL;
274
275 co = compiler_mod(&c, mod);
276
Thomas Wouters1175c432006-02-27 22:49:54 +0000277 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000279 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280 return co;
281}
282
283PyCodeObject *
284PyNode_Compile(struct _node *n, const char *filename)
285{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000286 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000287 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000288 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 if (!arena)
290 return NULL;
291 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000292 if (mod)
293 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000294 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000295 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296}
297
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000298static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000300{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301 if (c->c_st)
302 PySymtable_Free(c->c_st);
303 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000306}
307
Guido van Rossum79f25d91997-04-29 20:08:16 +0000308static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000310{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312 PyObject *v, *k;
313 PyObject *dict = PyDict_New();
314 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316 n = PyList_Size(list);
317 for (i = 0; i < n; i++) {
318 v = PyInt_FromLong(i);
319 if (!v) {
320 Py_DECREF(dict);
321 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000322 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000323 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
326 Py_XDECREF(k);
327 Py_DECREF(v);
328 Py_DECREF(dict);
329 return NULL;
330 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000331 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 return dict;
335}
336
337/* Return new dict containing names from src that match scope(s).
338
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339src is a symbol table dictionary. If the scope of a name matches
340either scope_type or flag is set, insert it into the new dict. The
341values are integers, starting at offset and increasing by one for
342each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343*/
344
345static PyObject *
346dictbytype(PyObject *src, int scope_type, int flag, int offset)
347{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000348 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 PyObject *k, *v, *dest = PyDict_New();
350
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000351 assert(offset >= 0);
352 if (dest == NULL)
353 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
355 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000356 /* XXX this should probably be a macro in symtable.h */
357 assert(PyInt_Check(v));
358 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
361 PyObject *tuple, *item = PyInt_FromLong(i);
362 if (item == NULL) {
363 Py_DECREF(dest);
364 return NULL;
365 }
366 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
369 Py_DECREF(item);
370 Py_DECREF(dest);
371 Py_XDECREF(tuple);
372 return NULL;
373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377 }
378 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000379}
380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381static void
382compiler_unit_check(struct compiler_unit *u)
383{
384 basicblock *block;
385 for (block = u->u_blocks; block != NULL; block = block->b_list) {
386 assert(block != (void *)0xcbcbcbcb);
387 assert(block != (void *)0xfbfbfbfb);
388 assert(block != (void *)0xdbdbdbdb);
389 if (block->b_instr != NULL) {
390 assert(block->b_ialloc > 0);
391 assert(block->b_iused > 0);
392 assert(block->b_ialloc >= block->b_iused);
393 }
394 else {
395 assert (block->b_iused == 0);
396 assert (block->b_ialloc == 0);
397 }
398 }
399}
400
401static void
402compiler_unit_free(struct compiler_unit *u)
403{
404 basicblock *b, *next;
405
406 compiler_unit_check(u);
407 b = u->u_blocks;
408 while (b != NULL) {
409 if (b->b_instr)
410 PyObject_Free((void *)b->b_instr);
411 next = b->b_list;
412 PyObject_Free((void *)b);
413 b = next;
414 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000415 Py_CLEAR(u->u_ste);
416 Py_CLEAR(u->u_name);
417 Py_CLEAR(u->u_consts);
418 Py_CLEAR(u->u_names);
419 Py_CLEAR(u->u_varnames);
420 Py_CLEAR(u->u_freevars);
421 Py_CLEAR(u->u_cellvars);
422 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423 PyObject_Free(u);
424}
425
426static int
427compiler_enter_scope(struct compiler *c, identifier name, void *key,
428 int lineno)
429{
430 struct compiler_unit *u;
431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
433 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000434 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435 PyErr_NoMemory();
436 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000437 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000438 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000440 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441 u->u_ste = PySymtable_Lookup(c->c_st, key);
442 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443 compiler_unit_free(u);
444 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445 }
446 Py_INCREF(name);
447 u->u_name = name;
448 u->u_varnames = list2dict(u->u_ste->ste_varnames);
449 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000450 if (!u->u_varnames || !u->u_cellvars) {
451 compiler_unit_free(u);
452 return 0;
453 }
454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457 if (!u->u_freevars) {
458 compiler_unit_free(u);
459 return 0;
460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461
462 u->u_blocks = NULL;
463 u->u_tmpname = 0;
464 u->u_nfblocks = 0;
465 u->u_firstlineno = lineno;
466 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000467 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468 u->u_consts = PyDict_New();
469 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000470 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471 return 0;
472 }
473 u->u_names = PyDict_New();
474 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000475 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476 return 0;
477 }
478
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000479 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480
481 /* Push the old compiler_unit on the stack. */
482 if (c->u) {
483 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
485 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000486 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487 return 0;
488 }
489 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000490 u->u_private = c->u->u_private;
491 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492 }
493 c->u = u;
494
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000496 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498
499 return 1;
500}
501
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000502static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503compiler_exit_scope(struct compiler *c)
504{
505 int n;
506 PyObject *wrapper;
507
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 compiler_unit_free(c->u);
510 /* Restore c->u to the parent unit. */
511 n = PyList_GET_SIZE(c->c_stack) - 1;
512 if (n >= 0) {
513 wrapper = PyList_GET_ITEM(c->c_stack, n);
514 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000515 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000516 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000518 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 compiler_unit_check(c->u);
520 }
521 else
522 c->u = NULL;
523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524}
525
Guido van Rossumc2e20742006-02-27 22:32:47 +0000526/* Allocate a new "anonymous" local variable.
527 Used by list comprehensions and with statements.
528*/
529
530static PyObject *
531compiler_new_tmpname(struct compiler *c)
532{
533 char tmpname[256];
534 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
535 return PyString_FromString(tmpname);
536}
537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538/* Allocate a new block and return a pointer to it.
539 Returns NULL on error.
540*/
541
542static basicblock *
543compiler_new_block(struct compiler *c)
544{
545 basicblock *b;
546 struct compiler_unit *u;
547
548 u = c->u;
549 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000550 if (b == NULL) {
551 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000555 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556 b->b_list = u->u_blocks;
557 u->u_blocks = b;
558 return b;
559}
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561static basicblock *
562compiler_use_new_block(struct compiler *c)
563{
564 basicblock *block = compiler_new_block(c);
565 if (block == NULL)
566 return NULL;
567 c->u->u_curblock = block;
568 return block;
569}
570
571static basicblock *
572compiler_next_block(struct compiler *c)
573{
574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock->b_next = block;
578 c->u->u_curblock = block;
579 return block;
580}
581
582static basicblock *
583compiler_use_next_block(struct compiler *c, basicblock *block)
584{
585 assert(block != NULL);
586 c->u->u_curblock->b_next = block;
587 c->u->u_curblock = block;
588 return block;
589}
590
591/* Returns the offset of the next instruction in the current block's
592 b_instr array. Resizes the b_instr as necessary.
593 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
596static int
597compiler_next_instr(struct compiler *c, basicblock *b)
598{
599 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000600 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601 b->b_instr = (struct instr *)PyObject_Malloc(
602 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603 if (b->b_instr == NULL) {
604 PyErr_NoMemory();
605 return -1;
606 }
607 b->b_ialloc = DEFAULT_BLOCK_SIZE;
608 memset((char *)b->b_instr, 0,
609 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613 size_t oldsize, newsize;
614 oldsize = b->b_ialloc * sizeof(struct instr);
615 newsize = oldsize << 1;
616 if (newsize == 0) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000621 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000622 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623 if (tmp == NULL) {
624 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 }
627 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
629 }
630 return b->b_iused++;
631}
632
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633/* Set the i_lineno member of the instruction at offse off if the
634 line number for the current expression/statement (?) has not
635 already been set. If it has been set, the call has no effect.
636
637 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000639
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640static void
641compiler_set_lineno(struct compiler *c, int off)
642{
643 basicblock *b;
644 if (c->u->u_lineno_set)
645 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000646 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000648 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
651static int
652opcode_stack_effect(int opcode, int oparg)
653{
654 switch (opcode) {
655 case POP_TOP:
656 return -1;
657 case ROT_TWO:
658 case ROT_THREE:
659 return 0;
660 case DUP_TOP:
661 return 1;
662 case ROT_FOUR:
663 return 0;
664
665 case UNARY_POSITIVE:
666 case UNARY_NEGATIVE:
667 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 case UNARY_INVERT:
669 return 0;
670
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000671 case LIST_APPEND:
672 return -2;
673
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674 case BINARY_POWER:
675 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676 case BINARY_MODULO:
677 case BINARY_ADD:
678 case BINARY_SUBTRACT:
679 case BINARY_SUBSCR:
680 case BINARY_FLOOR_DIVIDE:
681 case BINARY_TRUE_DIVIDE:
682 return -1;
683 case INPLACE_FLOOR_DIVIDE:
684 case INPLACE_TRUE_DIVIDE:
685 return -1;
686
687 case SLICE+0:
688 return 1;
689 case SLICE+1:
690 return 0;
691 case SLICE+2:
692 return 0;
693 case SLICE+3:
694 return -1;
695
696 case STORE_SLICE+0:
697 return -2;
698 case STORE_SLICE+1:
699 return -3;
700 case STORE_SLICE+2:
701 return -3;
702 case STORE_SLICE+3:
703 return -4;
704
705 case DELETE_SLICE+0:
706 return -1;
707 case DELETE_SLICE+1:
708 return -2;
709 case DELETE_SLICE+2:
710 return -2;
711 case DELETE_SLICE+3:
712 return -3;
713
714 case INPLACE_ADD:
715 case INPLACE_SUBTRACT:
716 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717 case INPLACE_MODULO:
718 return -1;
719 case STORE_SUBSCR:
720 return -3;
721 case DELETE_SUBSCR:
722 return -2;
723
724 case BINARY_LSHIFT:
725 case BINARY_RSHIFT:
726 case BINARY_AND:
727 case BINARY_XOR:
728 case BINARY_OR:
729 return -1;
730 case INPLACE_POWER:
731 return -1;
732 case GET_ITER:
733 return 0;
734
735 case PRINT_EXPR:
736 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737 case INPLACE_LSHIFT:
738 case INPLACE_RSHIFT:
739 case INPLACE_AND:
740 case INPLACE_XOR:
741 case INPLACE_OR:
742 return -1;
743 case BREAK_LOOP:
744 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000745 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000746 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747 case LOAD_LOCALS:
748 return 1;
749 case RETURN_VALUE:
750 return -1;
751 case IMPORT_STAR:
752 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753 case YIELD_VALUE:
754 return 0;
755
756 case POP_BLOCK:
757 return 0;
758 case END_FINALLY:
759 return -1; /* or -2 or -3 if exception occurred */
760 case BUILD_CLASS:
761 return -2;
762
763 case STORE_NAME:
764 return -1;
765 case DELETE_NAME:
766 return 0;
767 case UNPACK_SEQUENCE:
768 return oparg-1;
769 case FOR_ITER:
770 return 1;
771
772 case STORE_ATTR:
773 return -2;
774 case DELETE_ATTR:
775 return -1;
776 case STORE_GLOBAL:
777 return -1;
778 case DELETE_GLOBAL:
779 return 0;
780 case DUP_TOPX:
781 return oparg;
782 case LOAD_CONST:
783 return 1;
784 case LOAD_NAME:
785 return 1;
786 case BUILD_TUPLE:
787 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000788 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789 return 1-oparg;
790 case BUILD_MAP:
791 return 1;
Thomas Wouters00e41de2007-02-23 19:56:57 +0000792 case MAKE_BYTES:
793 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 case LOAD_ATTR:
795 return 0;
796 case COMPARE_OP:
797 return -1;
798 case IMPORT_NAME:
799 return 0;
800 case IMPORT_FROM:
801 return 1;
802
803 case JUMP_FORWARD:
804 case JUMP_IF_FALSE:
805 case JUMP_IF_TRUE:
806 case JUMP_ABSOLUTE:
807 return 0;
808
809 case LOAD_GLOBAL:
810 return 1;
811
812 case CONTINUE_LOOP:
813 return 0;
814 case SETUP_LOOP:
815 return 0;
816 case SETUP_EXCEPT:
817 case SETUP_FINALLY:
818 return 3; /* actually pushed by an exception */
819
820 case LOAD_FAST:
821 return 1;
822 case STORE_FAST:
823 return -1;
824 case DELETE_FAST:
825 return 0;
826
827 case RAISE_VARARGS:
828 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000829#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 case CALL_FUNCTION:
831 return -NARGS(oparg);
832 case CALL_FUNCTION_VAR:
833 case CALL_FUNCTION_KW:
834 return -NARGS(oparg)-1;
835 case CALL_FUNCTION_VAR_KW:
836 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000838 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000839#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840 case BUILD_SLICE:
841 if (oparg == 3)
842 return -2;
843 else
844 return -1;
845
846 case MAKE_CLOSURE:
847 return -oparg;
848 case LOAD_CLOSURE:
849 return 1;
850 case LOAD_DEREF:
851 return 1;
852 case STORE_DEREF:
853 return -1;
854 default:
855 fprintf(stderr, "opcode = %d\n", opcode);
856 Py_FatalError("opcode_stack_effect()");
857
858 }
859 return 0; /* not reachable */
860}
861
862/* Add an opcode with no argument.
863 Returns 0 on failure, 1 on success.
864*/
865
866static int
867compiler_addop(struct compiler *c, int opcode)
868{
869 basicblock *b;
870 struct instr *i;
871 int off;
872 off = compiler_next_instr(c, c->u->u_curblock);
873 if (off < 0)
874 return 0;
875 b = c->u->u_curblock;
876 i = &b->b_instr[off];
877 i->i_opcode = opcode;
878 i->i_hasarg = 0;
879 if (opcode == RETURN_VALUE)
880 b->b_return = 1;
881 compiler_set_lineno(c, off);
882 return 1;
883}
884
885static int
886compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
887{
888 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000889 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000891 /* necessary to make sure types aren't coerced (e.g., int and long) */
892 t = PyTuple_Pack(2, o, o->ob_type);
893 if (t == NULL)
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
896 v = PyDict_GetItem(dict, t);
897 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000898 if (PyErr_Occurred())
899 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900 arg = PyDict_Size(dict);
901 v = PyInt_FromLong(arg);
902 if (!v) {
903 Py_DECREF(t);
904 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000905 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906 if (PyDict_SetItem(dict, t, v) < 0) {
907 Py_DECREF(t);
908 Py_DECREF(v);
909 return -1;
910 }
911 Py_DECREF(v);
912 }
913 else
914 arg = PyInt_AsLong(v);
915 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000916 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917}
918
919static int
920compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
921 PyObject *o)
922{
923 int arg = compiler_add_o(c, dict, o);
924 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000925 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926 return compiler_addop_i(c, opcode, arg);
927}
928
929static int
930compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000931 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932{
933 int arg;
934 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
935 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937 arg = compiler_add_o(c, dict, mangled);
938 Py_DECREF(mangled);
939 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000940 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941 return compiler_addop_i(c, opcode, arg);
942}
943
944/* Add an opcode with an integer argument.
945 Returns 0 on failure, 1 on success.
946*/
947
948static int
949compiler_addop_i(struct compiler *c, int opcode, int oparg)
950{
951 struct instr *i;
952 int off;
953 off = compiler_next_instr(c, c->u->u_curblock);
954 if (off < 0)
955 return 0;
956 i = &c->u->u_curblock->b_instr[off];
957 i->i_opcode = opcode;
958 i->i_oparg = oparg;
959 i->i_hasarg = 1;
960 compiler_set_lineno(c, off);
961 return 1;
962}
963
964static int
965compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
966{
967 struct instr *i;
968 int off;
969
970 assert(b != NULL);
971 off = compiler_next_instr(c, c->u->u_curblock);
972 if (off < 0)
973 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 i = &c->u->u_curblock->b_instr[off];
975 i->i_opcode = opcode;
976 i->i_target = b;
977 i->i_hasarg = 1;
978 if (absolute)
979 i->i_jabs = 1;
980 else
981 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000982 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 return 1;
984}
985
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
987 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 it as the current block. NEXT_BLOCK() also creates an implicit jump
989 from the current block to the new block.
990*/
991
Thomas Wouters89f507f2006-12-13 04:49:30 +0000992/* The returns inside these macros make it impossible to decref objects
993 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994*/
995
996
997#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 if (compiler_use_new_block((C)) == NULL) \
999 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000}
1001
1002#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 if (compiler_next_block((C)) == NULL) \
1004 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005}
1006
1007#define ADDOP(C, OP) { \
1008 if (!compiler_addop((C), (OP))) \
1009 return 0; \
1010}
1011
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001012#define ADDOP_IN_SCOPE(C, OP) { \
1013 if (!compiler_addop((C), (OP))) { \
1014 compiler_exit_scope(c); \
1015 return 0; \
1016 } \
1017}
1018
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019#define ADDOP_O(C, OP, O, TYPE) { \
1020 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1021 return 0; \
1022}
1023
1024#define ADDOP_NAME(C, OP, O, TYPE) { \
1025 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1026 return 0; \
1027}
1028
1029#define ADDOP_I(C, OP, O) { \
1030 if (!compiler_addop_i((C), (OP), (O))) \
1031 return 0; \
1032}
1033
1034#define ADDOP_JABS(C, OP, O) { \
1035 if (!compiler_addop_j((C), (OP), (O), 1)) \
1036 return 0; \
1037}
1038
1039#define ADDOP_JREL(C, OP, O) { \
1040 if (!compiler_addop_j((C), (OP), (O), 0)) \
1041 return 0; \
1042}
1043
1044/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1045 the ASDL name to synthesize the name of the C type and the visit function.
1046*/
1047
1048#define VISIT(C, TYPE, V) {\
1049 if (!compiler_visit_ ## TYPE((C), (V))) \
1050 return 0; \
1051}
1052
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001053#define VISIT_IN_SCOPE(C, TYPE, V) {\
1054 if (!compiler_visit_ ## TYPE((C), (V))) { \
1055 compiler_exit_scope(c); \
1056 return 0; \
1057 } \
1058}
1059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060#define VISIT_SLICE(C, V, CTX) {\
1061 if (!compiler_visit_slice((C), (V), (CTX))) \
1062 return 0; \
1063}
1064
1065#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001066 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001068 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070 if (!compiler_visit_ ## TYPE((C), elt)) \
1071 return 0; \
1072 } \
1073}
1074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001076 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001077 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001078 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001080 if (!compiler_visit_ ## TYPE((C), elt)) { \
1081 compiler_exit_scope(c); \
1082 return 0; \
1083 } \
1084 } \
1085}
1086
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087static int
1088compiler_isdocstring(stmt_ty s)
1089{
1090 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092 return s->v.Expr.value->kind == Str_kind;
1093}
1094
1095/* Compile a sequence of statements, checking for a docstring. */
1096
1097static int
1098compiler_body(struct compiler *c, asdl_seq *stmts)
1099{
1100 int i = 0;
1101 stmt_ty st;
1102
1103 if (!asdl_seq_LEN(stmts))
1104 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001105 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106 if (compiler_isdocstring(st)) {
1107 i = 1;
1108 VISIT(c, expr, st->v.Expr.value);
1109 if (!compiler_nameop(c, __doc__, Store))
1110 return 0;
1111 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001113 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114 return 1;
1115}
1116
1117static PyCodeObject *
1118compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001119{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001120 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001121 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122 static PyObject *module;
1123 if (!module) {
1124 module = PyString_FromString("<module>");
1125 if (!module)
1126 return NULL;
1127 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1129 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001130 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 switch (mod->kind) {
1132 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001133 if (!compiler_body(c, mod->v.Module.body)) {
1134 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 break;
1138 case Interactive_kind:
1139 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001140 VISIT_SEQ_IN_SCOPE(c, stmt,
1141 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142 break;
1143 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001145 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 break;
1147 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001148 PyErr_SetString(PyExc_SystemError,
1149 "suite should not be possible");
1150 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001152 PyErr_Format(PyExc_SystemError,
1153 "module kind %d should not be possible",
1154 mod->kind);
1155 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 co = assemble(c, addNone);
1158 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001159 return co;
1160}
1161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162/* The test for LOCAL must come before the test for FREE in order to
1163 handle classes where name is both local and free. The local var is
1164 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001165*/
1166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167static int
1168get_ref_type(struct compiler *c, PyObject *name)
1169{
1170 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001171 if (scope == 0) {
1172 char buf[350];
1173 PyOS_snprintf(buf, sizeof(buf),
1174 "unknown scope for %.100s in %.100s(%s) in %s\n"
1175 "symbols: %s\nlocals: %s\nglobals: %s\n",
1176 PyString_AS_STRING(name),
1177 PyString_AS_STRING(c->u->u_name),
1178 PyObject_REPR(c->u->u_ste->ste_id),
1179 c->c_filename,
1180 PyObject_REPR(c->u->u_ste->ste_symbols),
1181 PyObject_REPR(c->u->u_varnames),
1182 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 Py_FatalError(buf);
1185 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001186
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001187 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188}
1189
1190static int
1191compiler_lookup_arg(PyObject *dict, PyObject *name)
1192{
1193 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001196 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001198 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001200 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 return PyInt_AS_LONG(v);
1202}
1203
1204static int
1205compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1206{
1207 int i, free = PyCode_GetNumFree(co);
1208 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1210 ADDOP_I(c, MAKE_FUNCTION, args);
1211 return 1;
1212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 for (i = 0; i < free; ++i) {
1214 /* Bypass com_addop_varname because it will generate
1215 LOAD_DEREF but LOAD_CLOSURE is needed.
1216 */
1217 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1218 int arg, reftype;
1219
1220 /* Special case: If a class contains a method with a
1221 free variable that has the same name as a method,
1222 the name will be considered free *and* local in the
1223 class. It should be handled by the closure, as
1224 well as by the normal name loookup logic.
1225 */
1226 reftype = get_ref_type(c, name);
1227 if (reftype == CELL)
1228 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1229 else /* (reftype == FREE) */
1230 arg = compiler_lookup_arg(c->u->u_freevars, name);
1231 if (arg == -1) {
1232 printf("lookup %s in %s %d %d\n"
1233 "freevars of %s: %s\n",
1234 PyObject_REPR(name),
1235 PyString_AS_STRING(c->u->u_name),
1236 reftype, arg,
1237 PyString_AS_STRING(co->co_name),
1238 PyObject_REPR(co->co_freevars));
1239 Py_FatalError("compiler_make_closure()");
1240 }
1241 ADDOP_I(c, LOAD_CLOSURE, arg);
1242 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 ADDOP_I(c, MAKE_CLOSURE, args);
1246 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247}
1248
1249static int
1250compiler_decorators(struct compiler *c, asdl_seq* decos)
1251{
1252 int i;
1253
1254 if (!decos)
1255 return 1;
1256
1257 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 }
1260 return 1;
1261}
1262
1263static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001264compiler_unpack_nested(struct compiler *c, asdl_seq *args) {
1265 int i, len;
1266 len = asdl_seq_LEN(args);
1267 ADDOP_I(c, UNPACK_SEQUENCE, len);
1268 for (i = 0; i < len; i++) {
1269 arg_ty elt = (arg_ty)asdl_seq_GET(args, i);
1270 switch (elt->kind) {
1271 case SimpleArg_kind:
1272 if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store))
1273 return 0;
1274 break;
1275 case NestedArgs_kind:
1276 if (!compiler_unpack_nested(c, elt->v.NestedArgs.args))
1277 return 0;
1278 break;
1279 default:
1280 return 0;
1281 }
1282 }
1283 return 1;
1284}
1285
1286static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287compiler_arguments(struct compiler *c, arguments_ty args)
1288{
1289 int i;
1290 int n = asdl_seq_LEN(args->args);
Neal Norwitzc1505362006-12-28 06:47:50 +00001291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 for (i = 0; i < n; i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001293 arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i);
1294 if (arg->kind == NestedArgs_kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 PyObject *id = PyString_FromFormat(".%d", i);
1296 if (id == NULL) {
1297 return 0;
1298 }
1299 if (!compiler_nameop(c, id, Load)) {
1300 Py_DECREF(id);
1301 return 0;
1302 }
1303 Py_DECREF(id);
Neal Norwitzc1505362006-12-28 06:47:50 +00001304 if (!compiler_unpack_nested(c, arg->v.NestedArgs.args))
1305 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 }
1307 }
1308 return 1;
1309}
1310
1311static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001312compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1313 asdl_seq *kw_defaults)
1314{
1315 int i, default_count = 0;
1316 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001317 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001318 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1319 if (default_) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001320 ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001321 if (!compiler_visit_expr(c, default_)) {
1322 return -1;
1323 }
1324 default_count++;
1325 }
1326 }
1327 return default_count;
1328}
1329
1330static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001331compiler_visit_argannotation(struct compiler *c, identifier id,
1332 expr_ty annotation, PyObject *names)
1333{
1334 if (annotation) {
1335 VISIT(c, expr, annotation);
1336 if (PyList_Append(names, id))
1337 return -1;
1338 }
1339 return 0;
1340}
1341
1342static int
1343compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1344 PyObject *names)
1345{
1346 int i, error;
1347 for (i = 0; i < asdl_seq_LEN(args); i++) {
1348 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1349 if (arg->kind == NestedArgs_kind)
1350 error = compiler_visit_argannotations(
1351 c,
1352 arg->v.NestedArgs.args,
1353 names);
1354 else
1355 error = compiler_visit_argannotation(
1356 c,
1357 arg->v.SimpleArg.arg,
1358 arg->v.SimpleArg.annotation,
1359 names);
1360 if (error)
1361 return error;
1362 }
1363 return 0;
1364}
1365
1366static int
1367compiler_visit_annotations(struct compiler *c, arguments_ty args,
1368 expr_ty returns)
1369{
1370 /* push arg annotations and a list of the argument names. return the #
1371 of items pushed. this is out-of-order wrt the source code. */
1372 static identifier return_str;
1373 PyObject *names;
1374 int len;
1375 names = PyList_New(0);
1376 if (!names)
1377 return -1;
1378
1379 if (compiler_visit_argannotations(c, args->args, names))
1380 goto error;
1381 if (args->varargannotation &&
1382 compiler_visit_argannotation(c, args->vararg,
1383 args->varargannotation, names))
1384 goto error;
1385 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1386 goto error;
1387 if (args->kwargannotation &&
1388 compiler_visit_argannotation(c, args->kwarg,
1389 args->kwargannotation, names))
1390 goto error;
1391
1392 if (!return_str) {
1393 return_str = PyString_InternFromString("return");
1394 if (!return_str)
1395 goto error;
1396 }
1397 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1398 goto error;
1399 }
1400
1401 len = PyList_GET_SIZE(names);
1402 if (len) {
1403 /* convert names to a tuple and place on stack */
1404 PyObject *elt;
1405 int i;
1406 PyObject *s = PyTuple_New(len);
1407 if (!s)
1408 goto error;
1409 for (i = 0; i < len; i++) {
1410 elt = PyList_GET_ITEM(names, i);
1411 Py_INCREF(elt);
1412 PyTuple_SET_ITEM(s, i, elt);
1413 }
1414 ADDOP_O(c, LOAD_CONST, s, consts);
1415 Py_DECREF(s);
1416 len++; /* include the just-pushed tuple */
1417 }
1418 Py_DECREF(names);
1419 return len;
1420
1421error:
1422 Py_DECREF(names);
1423 return -1;
1424}
1425
1426static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427compiler_function(struct compiler *c, stmt_ty s)
1428{
1429 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001430 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001432 expr_ty returns = s->v.FunctionDef.returns;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001435 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001436 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437
1438 assert(s->kind == FunctionDef_kind);
1439
1440 if (!compiler_decorators(c, decos))
1441 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001442 if (args->kwonlyargs) {
1443 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1444 args->kw_defaults);
1445 if (res < 0)
1446 return 0;
1447 kw_default_count = res;
1448 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449 if (args->defaults)
1450 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001451 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1454 s->lineno))
1455 return 0;
1456
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001457 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001458 docstring = compiler_isdocstring(st);
1459 if (docstring)
1460 first_const = st->v.Expr.value->v.Str.s;
1461 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001462 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001463 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001466 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467 compiler_arguments(c, args);
1468
1469 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001470 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001472 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001474 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1475 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 }
1477 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001478 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479 if (co == NULL)
1480 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481
Guido van Rossum4f72a782006-10-27 23:31:49 +00001482 arglength = asdl_seq_LEN(args->defaults);
1483 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001484 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001485 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001486 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487
Neal Norwitzc1505362006-12-28 06:47:50 +00001488 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1490 ADDOP_I(c, CALL_FUNCTION, 1);
1491 }
1492
1493 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1494}
1495
1496static int
1497compiler_class(struct compiler *c, stmt_ty s)
1498{
1499 int n;
1500 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001501 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502 /* push class name on stack, needed by BUILD_CLASS */
1503 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1504 /* push the tuple of base classes on the stack */
1505 n = asdl_seq_LEN(s->v.ClassDef.bases);
1506 if (n > 0)
1507 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1508 ADDOP_I(c, BUILD_TUPLE, n);
1509 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1510 s->lineno))
1511 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001512 c->u->u_private = s->v.ClassDef.name;
1513 Py_INCREF(c->u->u_private);
1514 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515 if (!str || !compiler_nameop(c, str, Load)) {
1516 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001517 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001519 }
1520
1521 Py_DECREF(str);
1522 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523 if (!str || !compiler_nameop(c, str, Store)) {
1524 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001525 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001527 }
1528 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001530 if (!compiler_body(c, s->v.ClassDef.body)) {
1531 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001533 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001535 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1536 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001538 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539 if (co == NULL)
1540 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001541
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001542 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001543 Py_DECREF(co);
1544
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545 ADDOP_I(c, CALL_FUNCTION, 0);
1546 ADDOP(c, BUILD_CLASS);
1547 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1548 return 0;
1549 return 1;
1550}
1551
1552static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001553compiler_ifexp(struct compiler *c, expr_ty e)
1554{
1555 basicblock *end, *next;
1556
1557 assert(e->kind == IfExp_kind);
1558 end = compiler_new_block(c);
1559 if (end == NULL)
1560 return 0;
1561 next = compiler_new_block(c);
1562 if (next == NULL)
1563 return 0;
1564 VISIT(c, expr, e->v.IfExp.test);
1565 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1566 ADDOP(c, POP_TOP);
1567 VISIT(c, expr, e->v.IfExp.body);
1568 ADDOP_JREL(c, JUMP_FORWARD, end);
1569 compiler_use_next_block(c, next);
1570 ADDOP(c, POP_TOP);
1571 VISIT(c, expr, e->v.IfExp.orelse);
1572 compiler_use_next_block(c, end);
1573 return 1;
1574}
1575
1576static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577compiler_lambda(struct compiler *c, expr_ty e)
1578{
1579 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001580 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001581 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001582 arguments_ty args = e->v.Lambda.args;
1583 assert(e->kind == Lambda_kind);
1584
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001585 if (!name) {
1586 name = PyString_InternFromString("<lambda>");
1587 if (!name)
1588 return 0;
1589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590
Guido van Rossum4f72a782006-10-27 23:31:49 +00001591 if (args->kwonlyargs) {
1592 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1593 args->kw_defaults);
1594 if (res < 0) return 0;
1595 kw_default_count = res;
1596 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001597 if (args->defaults)
1598 VISIT_SEQ(c, expr, args->defaults);
1599 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1600 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001601
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001602 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603 compiler_arguments(c, args);
1604
1605 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001606 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001607 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1608 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001609 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001610 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 if (co == NULL)
1612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613
Guido van Rossum4f72a782006-10-27 23:31:49 +00001614 arglength = asdl_seq_LEN(args->defaults);
1615 arglength |= kw_default_count << 8;
1616 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001617 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618
1619 return 1;
1620}
1621
1622static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623compiler_if(struct compiler *c, stmt_ty s)
1624{
1625 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001626 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627 assert(s->kind == If_kind);
1628 end = compiler_new_block(c);
1629 if (end == NULL)
1630 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001631 next = compiler_new_block(c);
1632 if (next == NULL)
1633 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001634
1635 constant = expr_constant(s->v.If.test);
1636 /* constant = 0: "if 0"
1637 * constant = 1: "if 1", "if 2", ...
1638 * constant = -1: rest */
1639 if (constant == 0) {
1640 if (s->v.If.orelse)
1641 VISIT_SEQ(c, stmt, s->v.If.orelse);
1642 } else if (constant == 1) {
1643 VISIT_SEQ(c, stmt, s->v.If.body);
1644 } else {
1645 VISIT(c, expr, s->v.If.test);
1646 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1647 ADDOP(c, POP_TOP);
1648 VISIT_SEQ(c, stmt, s->v.If.body);
1649 ADDOP_JREL(c, JUMP_FORWARD, end);
1650 compiler_use_next_block(c, next);
1651 ADDOP(c, POP_TOP);
1652 if (s->v.If.orelse)
1653 VISIT_SEQ(c, stmt, s->v.If.orelse);
1654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 compiler_use_next_block(c, end);
1656 return 1;
1657}
1658
1659static int
1660compiler_for(struct compiler *c, stmt_ty s)
1661{
1662 basicblock *start, *cleanup, *end;
1663
1664 start = compiler_new_block(c);
1665 cleanup = compiler_new_block(c);
1666 end = compiler_new_block(c);
1667 if (start == NULL || end == NULL || cleanup == NULL)
1668 return 0;
1669 ADDOP_JREL(c, SETUP_LOOP, end);
1670 if (!compiler_push_fblock(c, LOOP, start))
1671 return 0;
1672 VISIT(c, expr, s->v.For.iter);
1673 ADDOP(c, GET_ITER);
1674 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675 /* XXX(nnorwitz): is there a better way to handle this?
1676 for loops are special, we want to be able to trace them
1677 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001678 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679 ADDOP_JREL(c, FOR_ITER, cleanup);
1680 VISIT(c, expr, s->v.For.target);
1681 VISIT_SEQ(c, stmt, s->v.For.body);
1682 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1683 compiler_use_next_block(c, cleanup);
1684 ADDOP(c, POP_BLOCK);
1685 compiler_pop_fblock(c, LOOP, start);
1686 VISIT_SEQ(c, stmt, s->v.For.orelse);
1687 compiler_use_next_block(c, end);
1688 return 1;
1689}
1690
1691static int
1692compiler_while(struct compiler *c, stmt_ty s)
1693{
1694 basicblock *loop, *orelse, *end, *anchor = NULL;
1695 int constant = expr_constant(s->v.While.test);
1696
1697 if (constant == 0)
1698 return 1;
1699 loop = compiler_new_block(c);
1700 end = compiler_new_block(c);
1701 if (constant == -1) {
1702 anchor = compiler_new_block(c);
1703 if (anchor == NULL)
1704 return 0;
1705 }
1706 if (loop == NULL || end == NULL)
1707 return 0;
1708 if (s->v.While.orelse) {
1709 orelse = compiler_new_block(c);
1710 if (orelse == NULL)
1711 return 0;
1712 }
1713 else
1714 orelse = NULL;
1715
1716 ADDOP_JREL(c, SETUP_LOOP, end);
1717 compiler_use_next_block(c, loop);
1718 if (!compiler_push_fblock(c, LOOP, loop))
1719 return 0;
1720 if (constant == -1) {
1721 VISIT(c, expr, s->v.While.test);
1722 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1723 ADDOP(c, POP_TOP);
1724 }
1725 VISIT_SEQ(c, stmt, s->v.While.body);
1726 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1727
1728 /* XXX should the two POP instructions be in a separate block
1729 if there is no else clause ?
1730 */
1731
1732 if (constant == -1) {
1733 compiler_use_next_block(c, anchor);
1734 ADDOP(c, POP_TOP);
1735 ADDOP(c, POP_BLOCK);
1736 }
1737 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739 VISIT_SEQ(c, stmt, s->v.While.orelse);
1740 compiler_use_next_block(c, end);
1741
1742 return 1;
1743}
1744
1745static int
1746compiler_continue(struct compiler *c)
1747{
1748 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001749 static const char IN_FINALLY_ERROR_MSG[] =
1750 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751 int i;
1752
1753 if (!c->u->u_nfblocks)
1754 return compiler_error(c, LOOP_ERROR_MSG);
1755 i = c->u->u_nfblocks - 1;
1756 switch (c->u->u_fblock[i].fb_type) {
1757 case LOOP:
1758 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1759 break;
1760 case EXCEPT:
1761 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001762 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1763 /* Prevent continue anywhere under a finally
1764 even if hidden in a sub-try or except. */
1765 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1766 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1767 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768 if (i == -1)
1769 return compiler_error(c, LOOP_ERROR_MSG);
1770 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1771 break;
1772 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001773 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 }
1775
1776 return 1;
1777}
1778
1779/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1780
1781 SETUP_FINALLY L
1782 <code for body>
1783 POP_BLOCK
1784 LOAD_CONST <None>
1785 L: <code for finalbody>
1786 END_FINALLY
1787
1788 The special instructions use the block stack. Each block
1789 stack entry contains the instruction that created it (here
1790 SETUP_FINALLY), the level of the value stack at the time the
1791 block stack entry was created, and a label (here L).
1792
1793 SETUP_FINALLY:
1794 Pushes the current value stack level and the label
1795 onto the block stack.
1796 POP_BLOCK:
1797 Pops en entry from the block stack, and pops the value
1798 stack until its level is the same as indicated on the
1799 block stack. (The label is ignored.)
1800 END_FINALLY:
1801 Pops a variable number of entries from the *value* stack
1802 and re-raises the exception they specify. The number of
1803 entries popped depends on the (pseudo) exception type.
1804
1805 The block stack is unwound when an exception is raised:
1806 when a SETUP_FINALLY entry is found, the exception is pushed
1807 onto the value stack (and the exception condition is cleared),
1808 and the interpreter jumps to the label gotten from the block
1809 stack.
1810*/
1811
1812static int
1813compiler_try_finally(struct compiler *c, stmt_ty s)
1814{
1815 basicblock *body, *end;
1816 body = compiler_new_block(c);
1817 end = compiler_new_block(c);
1818 if (body == NULL || end == NULL)
1819 return 0;
1820
1821 ADDOP_JREL(c, SETUP_FINALLY, end);
1822 compiler_use_next_block(c, body);
1823 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1824 return 0;
1825 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1826 ADDOP(c, POP_BLOCK);
1827 compiler_pop_fblock(c, FINALLY_TRY, body);
1828
1829 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1830 compiler_use_next_block(c, end);
1831 if (!compiler_push_fblock(c, FINALLY_END, end))
1832 return 0;
1833 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1834 ADDOP(c, END_FINALLY);
1835 compiler_pop_fblock(c, FINALLY_END, end);
1836
1837 return 1;
1838}
1839
1840/*
1841 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1842 (The contents of the value stack is shown in [], with the top
1843 at the right; 'tb' is trace-back info, 'val' the exception's
1844 associated value, and 'exc' the exception.)
1845
1846 Value stack Label Instruction Argument
1847 [] SETUP_EXCEPT L1
1848 [] <code for S>
1849 [] POP_BLOCK
1850 [] JUMP_FORWARD L0
1851
1852 [tb, val, exc] L1: DUP )
1853 [tb, val, exc, exc] <evaluate E1> )
1854 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1855 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1856 [tb, val, exc, 1] POP )
1857 [tb, val, exc] POP
1858 [tb, val] <assign to V1> (or POP if no V1)
1859 [tb] POP
1860 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001861 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862
1863 [tb, val, exc, 0] L2: POP
1864 [tb, val, exc] DUP
1865 .............................etc.......................
1866
1867 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001868 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869
1870 [] L0: <next statement>
1871
1872 Of course, parts are not generated if Vi or Ei is not present.
1873*/
1874static int
1875compiler_try_except(struct compiler *c, stmt_ty s)
1876{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001877 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 int i, n;
1879
1880 body = compiler_new_block(c);
1881 except = compiler_new_block(c);
1882 orelse = compiler_new_block(c);
1883 end = compiler_new_block(c);
1884 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1885 return 0;
1886 ADDOP_JREL(c, SETUP_EXCEPT, except);
1887 compiler_use_next_block(c, body);
1888 if (!compiler_push_fblock(c, EXCEPT, body))
1889 return 0;
1890 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1891 ADDOP(c, POP_BLOCK);
1892 compiler_pop_fblock(c, EXCEPT, body);
1893 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1894 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1895 compiler_use_next_block(c, except);
1896 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001897 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898 s->v.TryExcept.handlers, i);
1899 if (!handler->type && i < n-1)
1900 return compiler_error(c, "default 'except:' must be last");
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001901 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001902 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903 except = compiler_new_block(c);
1904 if (except == NULL)
1905 return 0;
1906 if (handler->type) {
1907 ADDOP(c, DUP_TOP);
1908 VISIT(c, expr, handler->type);
1909 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1910 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1911 ADDOP(c, POP_TOP);
1912 }
1913 ADDOP(c, POP_TOP);
1914 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001915 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001916
1917 cleanup_end = compiler_new_block(c);
1918 cleanup_body = compiler_new_block(c);
1919 if(!(cleanup_end || cleanup_body))
1920 return 0;
1921
Guido van Rossum16be03e2007-01-10 18:51:35 +00001922 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001923 ADDOP(c, POP_TOP);
1924
1925 /*
1926 try:
1927 # body
1928 except type as name:
1929 try:
1930 # body
1931 finally:
1932 name = None
1933 del name
1934 */
1935
1936 /* second try: */
1937 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1938 compiler_use_next_block(c, cleanup_body);
1939 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1940 return 0;
1941
1942 /* second # body */
1943 VISIT_SEQ(c, stmt, handler->body);
1944 ADDOP(c, POP_BLOCK);
1945 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
1946
1947 /* finally: */
1948 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1949 compiler_use_next_block(c, cleanup_end);
1950 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
1951 return 0;
1952
1953 /* name = None */
1954 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00001955 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001956
Guido van Rossum16be03e2007-01-10 18:51:35 +00001957 /* del name */
1958 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00001959
1960 ADDOP(c, END_FINALLY);
1961 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 }
1963 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00001964 ADDOP(c, POP_TOP);
1965 ADDOP(c, POP_TOP);
1966 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 ADDOP_JREL(c, JUMP_FORWARD, end);
1969 compiler_use_next_block(c, except);
1970 if (handler->type)
1971 ADDOP(c, POP_TOP);
1972 }
1973 ADDOP(c, END_FINALLY);
1974 compiler_use_next_block(c, orelse);
1975 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1976 compiler_use_next_block(c, end);
1977 return 1;
1978}
1979
1980static int
1981compiler_import_as(struct compiler *c, identifier name, identifier asname)
1982{
1983 /* The IMPORT_NAME opcode was already generated. This function
1984 merely needs to bind the result to a name.
1985
1986 If there is a dot in name, we need to split it and emit a
1987 LOAD_ATTR for each name.
1988 */
1989 const char *src = PyString_AS_STRING(name);
1990 const char *dot = strchr(src, '.');
1991 if (dot) {
1992 /* Consume the base module name to get the first attribute */
1993 src = dot + 1;
1994 while (dot) {
1995 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001996 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001998 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002000 if (!attr)
2001 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002003 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 src = dot + 1;
2005 }
2006 }
2007 return compiler_nameop(c, asname, Store);
2008}
2009
2010static int
2011compiler_import(struct compiler *c, stmt_ty s)
2012{
2013 /* The Import node stores a module name like a.b.c as a single
2014 string. This is convenient for all cases except
2015 import a.b.c as d
2016 where we need to parse that string to extract the individual
2017 module names.
2018 XXX Perhaps change the representation to make this case simpler?
2019 */
2020 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002021
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002023 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002025 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026
Guido van Rossum45aecf42006-03-15 04:58:47 +00002027 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002028 if (level == NULL)
2029 return 0;
2030
2031 ADDOP_O(c, LOAD_CONST, level, consts);
2032 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2034 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2035
2036 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002037 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002038 if (!r)
2039 return r;
2040 }
2041 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 identifier tmp = alias->name;
2043 const char *base = PyString_AS_STRING(alias->name);
2044 char *dot = strchr(base, '.');
2045 if (dot)
2046 tmp = PyString_FromStringAndSize(base,
2047 dot - base);
2048 r = compiler_nameop(c, tmp, Store);
2049 if (dot) {
2050 Py_DECREF(tmp);
2051 }
2052 if (!r)
2053 return r;
2054 }
2055 }
2056 return 1;
2057}
2058
2059static int
2060compiler_from_import(struct compiler *c, stmt_ty s)
2061{
2062 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063
2064 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002065 PyObject *level;
2066
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 if (!names)
2068 return 0;
2069
Guido van Rossum45aecf42006-03-15 04:58:47 +00002070 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002071 if (!level) {
2072 Py_DECREF(names);
2073 return 0;
2074 }
2075
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 /* build up the names */
2077 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002078 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 Py_INCREF(alias->name);
2080 PyTuple_SET_ITEM(names, i, alias->name);
2081 }
2082
2083 if (s->lineno > c->c_future->ff_lineno) {
2084 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2085 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002086 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 Py_DECREF(names);
2088 return compiler_error(c,
2089 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002090 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091
2092 }
2093 }
2094
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002095 ADDOP_O(c, LOAD_CONST, level, consts);
2096 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002098 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2100 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002101 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 identifier store_name;
2103
2104 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2105 assert(n == 1);
2106 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002107 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 }
2109
2110 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2111 store_name = alias->name;
2112 if (alias->asname)
2113 store_name = alias->asname;
2114
2115 if (!compiler_nameop(c, store_name, Store)) {
2116 Py_DECREF(names);
2117 return 0;
2118 }
2119 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002120 /* remove imported module */
2121 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122 return 1;
2123}
2124
2125static int
2126compiler_assert(struct compiler *c, stmt_ty s)
2127{
2128 static PyObject *assertion_error = NULL;
2129 basicblock *end;
2130
2131 if (Py_OptimizeFlag)
2132 return 1;
2133 if (assertion_error == NULL) {
2134 assertion_error = PyString_FromString("AssertionError");
2135 if (assertion_error == NULL)
2136 return 0;
2137 }
2138 VISIT(c, expr, s->v.Assert.test);
2139 end = compiler_new_block(c);
2140 if (end == NULL)
2141 return 0;
2142 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2143 ADDOP(c, POP_TOP);
2144 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2145 if (s->v.Assert.msg) {
2146 VISIT(c, expr, s->v.Assert.msg);
2147 ADDOP_I(c, RAISE_VARARGS, 2);
2148 }
2149 else {
2150 ADDOP_I(c, RAISE_VARARGS, 1);
2151 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002152 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 ADDOP(c, POP_TOP);
2154 return 1;
2155}
2156
2157static int
2158compiler_visit_stmt(struct compiler *c, stmt_ty s)
2159{
2160 int i, n;
2161
Thomas Wouters89f507f2006-12-13 04:49:30 +00002162 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002164 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002165
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002167 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002169 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002171 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002172 if (c->u->u_ste->ste_type != FunctionBlock)
2173 return compiler_error(c, "'return' outside function");
2174 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175 VISIT(c, expr, s->v.Return.value);
2176 }
2177 else
2178 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2179 ADDOP(c, RETURN_VALUE);
2180 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002181 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002182 VISIT_SEQ(c, expr, s->v.Delete.targets)
2183 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002184 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 n = asdl_seq_LEN(s->v.Assign.targets);
2186 VISIT(c, expr, s->v.Assign.value);
2187 for (i = 0; i < n; i++) {
2188 if (i < n - 1)
2189 ADDOP(c, DUP_TOP);
2190 VISIT(c, expr,
2191 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2192 }
2193 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002196 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002198 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002200 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002202 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203 n = 0;
2204 if (s->v.Raise.type) {
2205 VISIT(c, expr, s->v.Raise.type);
2206 n++;
2207 if (s->v.Raise.inst) {
2208 VISIT(c, expr, s->v.Raise.inst);
2209 n++;
2210 if (s->v.Raise.tback) {
2211 VISIT(c, expr, s->v.Raise.tback);
2212 n++;
2213 }
2214 }
2215 }
2216 ADDOP_I(c, RAISE_VARARGS, n);
2217 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002218 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002220 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002222 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002224 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002226 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002228 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002230 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002232 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233 ADDOP(c, PRINT_EXPR);
2234 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002235 else if (s->v.Expr.value->kind != Str_kind &&
2236 s->v.Expr.value->kind != Num_kind) {
2237 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 ADDOP(c, POP_TOP);
2239 }
2240 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002243 case Break_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002244 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 return compiler_error(c, "'break' outside loop");
2246 ADDOP(c, BREAK_LOOP);
2247 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002248 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002250 case With_kind:
2251 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252 }
2253 return 1;
2254}
2255
2256static int
2257unaryop(unaryop_ty op)
2258{
2259 switch (op) {
2260 case Invert:
2261 return UNARY_INVERT;
2262 case Not:
2263 return UNARY_NOT;
2264 case UAdd:
2265 return UNARY_POSITIVE;
2266 case USub:
2267 return UNARY_NEGATIVE;
2268 }
2269 return 0;
2270}
2271
2272static int
2273binop(struct compiler *c, operator_ty op)
2274{
2275 switch (op) {
2276 case Add:
2277 return BINARY_ADD;
2278 case Sub:
2279 return BINARY_SUBTRACT;
2280 case Mult:
2281 return BINARY_MULTIPLY;
2282 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002283 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284 case Mod:
2285 return BINARY_MODULO;
2286 case Pow:
2287 return BINARY_POWER;
2288 case LShift:
2289 return BINARY_LSHIFT;
2290 case RShift:
2291 return BINARY_RSHIFT;
2292 case BitOr:
2293 return BINARY_OR;
2294 case BitXor:
2295 return BINARY_XOR;
2296 case BitAnd:
2297 return BINARY_AND;
2298 case FloorDiv:
2299 return BINARY_FLOOR_DIVIDE;
2300 }
2301 return 0;
2302}
2303
2304static int
2305cmpop(cmpop_ty op)
2306{
2307 switch (op) {
2308 case Eq:
2309 return PyCmp_EQ;
2310 case NotEq:
2311 return PyCmp_NE;
2312 case Lt:
2313 return PyCmp_LT;
2314 case LtE:
2315 return PyCmp_LE;
2316 case Gt:
2317 return PyCmp_GT;
2318 case GtE:
2319 return PyCmp_GE;
2320 case Is:
2321 return PyCmp_IS;
2322 case IsNot:
2323 return PyCmp_IS_NOT;
2324 case In:
2325 return PyCmp_IN;
2326 case NotIn:
2327 return PyCmp_NOT_IN;
2328 }
2329 return PyCmp_BAD;
2330}
2331
2332static int
2333inplace_binop(struct compiler *c, operator_ty op)
2334{
2335 switch (op) {
2336 case Add:
2337 return INPLACE_ADD;
2338 case Sub:
2339 return INPLACE_SUBTRACT;
2340 case Mult:
2341 return INPLACE_MULTIPLY;
2342 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002343 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344 case Mod:
2345 return INPLACE_MODULO;
2346 case Pow:
2347 return INPLACE_POWER;
2348 case LShift:
2349 return INPLACE_LSHIFT;
2350 case RShift:
2351 return INPLACE_RSHIFT;
2352 case BitOr:
2353 return INPLACE_OR;
2354 case BitXor:
2355 return INPLACE_XOR;
2356 case BitAnd:
2357 return INPLACE_AND;
2358 case FloorDiv:
2359 return INPLACE_FLOOR_DIVIDE;
2360 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002361 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002362 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363 return 0;
2364}
2365
2366static int
2367compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2368{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002369 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2371
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002372 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002373 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374 /* XXX AugStore isn't used anywhere! */
2375
2376 /* First check for assignment to __debug__. Param? */
2377 if ((ctx == Store || ctx == AugStore || ctx == Del)
2378 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2379 return compiler_error(c, "can not assign to __debug__");
2380 }
2381
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002382 mangled = _Py_Mangle(c->u->u_private, name);
2383 if (!mangled)
2384 return 0;
2385
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386 op = 0;
2387 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002388 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002389 switch (scope) {
2390 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002391 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392 optype = OP_DEREF;
2393 break;
2394 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002395 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396 optype = OP_DEREF;
2397 break;
2398 case LOCAL:
2399 if (c->u->u_ste->ste_type == FunctionBlock)
2400 optype = OP_FAST;
2401 break;
2402 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002403 if (c->u->u_ste->ste_type == FunctionBlock &&
2404 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405 optype = OP_GLOBAL;
2406 break;
2407 case GLOBAL_EXPLICIT:
2408 optype = OP_GLOBAL;
2409 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002410 default:
2411 /* scope can be 0 */
2412 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 }
2414
2415 /* XXX Leave assert here, but handle __doc__ and the like better */
2416 assert(scope || PyString_AS_STRING(name)[0] == '_');
2417
2418 switch (optype) {
2419 case OP_DEREF:
2420 switch (ctx) {
2421 case Load: op = LOAD_DEREF; break;
2422 case Store: op = STORE_DEREF; break;
2423 case AugLoad:
2424 case AugStore:
2425 break;
2426 case Del:
2427 PyErr_Format(PyExc_SyntaxError,
2428 "can not delete variable '%s' referenced "
2429 "in nested scope",
2430 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002431 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002434 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002435 PyErr_SetString(PyExc_SystemError,
2436 "param invalid for deref variable");
2437 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 }
2439 break;
2440 case OP_FAST:
2441 switch (ctx) {
2442 case Load: op = LOAD_FAST; break;
2443 case Store: op = STORE_FAST; break;
2444 case Del: op = DELETE_FAST; break;
2445 case AugLoad:
2446 case AugStore:
2447 break;
2448 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002449 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002450 PyErr_SetString(PyExc_SystemError,
2451 "param invalid for local variable");
2452 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002454 ADDOP_O(c, op, mangled, varnames);
2455 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 return 1;
2457 case OP_GLOBAL:
2458 switch (ctx) {
2459 case Load: op = LOAD_GLOBAL; break;
2460 case Store: op = STORE_GLOBAL; break;
2461 case Del: op = DELETE_GLOBAL; break;
2462 case AugLoad:
2463 case AugStore:
2464 break;
2465 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002466 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002467 PyErr_SetString(PyExc_SystemError,
2468 "param invalid for global variable");
2469 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 }
2471 break;
2472 case OP_NAME:
2473 switch (ctx) {
2474 case Load: op = LOAD_NAME; break;
2475 case Store: op = STORE_NAME; break;
2476 case Del: op = DELETE_NAME; break;
2477 case AugLoad:
2478 case AugStore:
2479 break;
2480 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002481 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002482 PyErr_SetString(PyExc_SystemError,
2483 "param invalid for name variable");
2484 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 }
2486 break;
2487 }
2488
2489 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002490 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002491 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002492 if (arg < 0)
2493 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002494 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495}
2496
2497static int
2498compiler_boolop(struct compiler *c, expr_ty e)
2499{
2500 basicblock *end;
2501 int jumpi, i, n;
2502 asdl_seq *s;
2503
2504 assert(e->kind == BoolOp_kind);
2505 if (e->v.BoolOp.op == And)
2506 jumpi = JUMP_IF_FALSE;
2507 else
2508 jumpi = JUMP_IF_TRUE;
2509 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002510 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 return 0;
2512 s = e->v.BoolOp.values;
2513 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002514 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002516 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517 ADDOP_JREL(c, jumpi, end);
2518 ADDOP(c, POP_TOP)
2519 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002520 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 compiler_use_next_block(c, end);
2522 return 1;
2523}
2524
2525static int
2526compiler_list(struct compiler *c, expr_ty e)
2527{
2528 int n = asdl_seq_LEN(e->v.List.elts);
2529 if (e->v.List.ctx == Store) {
2530 ADDOP_I(c, UNPACK_SEQUENCE, n);
2531 }
2532 VISIT_SEQ(c, expr, e->v.List.elts);
2533 if (e->v.List.ctx == Load) {
2534 ADDOP_I(c, BUILD_LIST, n);
2535 }
2536 return 1;
2537}
2538
2539static int
2540compiler_tuple(struct compiler *c, expr_ty e)
2541{
2542 int n = asdl_seq_LEN(e->v.Tuple.elts);
2543 if (e->v.Tuple.ctx == Store) {
2544 ADDOP_I(c, UNPACK_SEQUENCE, n);
2545 }
2546 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2547 if (e->v.Tuple.ctx == Load) {
2548 ADDOP_I(c, BUILD_TUPLE, n);
2549 }
2550 return 1;
2551}
2552
2553static int
2554compiler_compare(struct compiler *c, expr_ty e)
2555{
2556 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002557 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558
2559 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2560 VISIT(c, expr, e->v.Compare.left);
2561 n = asdl_seq_LEN(e->v.Compare.ops);
2562 assert(n > 0);
2563 if (n > 1) {
2564 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002565 if (cleanup == NULL)
2566 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002567 VISIT(c, expr,
2568 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 }
2570 for (i = 1; i < n; i++) {
2571 ADDOP(c, DUP_TOP);
2572 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002574 cmpop((cmpop_ty)(asdl_seq_GET(
2575 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2577 NEXT_BLOCK(c);
2578 ADDOP(c, POP_TOP);
2579 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580 VISIT(c, expr,
2581 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002583 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002585 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 if (n > 1) {
2587 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002588 if (end == NULL)
2589 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 ADDOP_JREL(c, JUMP_FORWARD, end);
2591 compiler_use_next_block(c, cleanup);
2592 ADDOP(c, ROT_TWO);
2593 ADDOP(c, POP_TOP);
2594 compiler_use_next_block(c, end);
2595 }
2596 return 1;
2597}
2598
2599static int
2600compiler_call(struct compiler *c, expr_ty e)
2601{
2602 int n, code = 0;
2603
2604 VISIT(c, expr, e->v.Call.func);
2605 n = asdl_seq_LEN(e->v.Call.args);
2606 VISIT_SEQ(c, expr, e->v.Call.args);
2607 if (e->v.Call.keywords) {
2608 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2609 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2610 }
2611 if (e->v.Call.starargs) {
2612 VISIT(c, expr, e->v.Call.starargs);
2613 code |= 1;
2614 }
2615 if (e->v.Call.kwargs) {
2616 VISIT(c, expr, e->v.Call.kwargs);
2617 code |= 2;
2618 }
2619 switch (code) {
2620 case 0:
2621 ADDOP_I(c, CALL_FUNCTION, n);
2622 break;
2623 case 1:
2624 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2625 break;
2626 case 2:
2627 ADDOP_I(c, CALL_FUNCTION_KW, n);
2628 break;
2629 case 3:
2630 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2631 break;
2632 }
2633 return 1;
2634}
2635
2636static int
2637compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002638 asdl_seq *generators, int gen_index,
2639 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640{
2641 /* generate code for the iterator, then each of the ifs,
2642 and then write to the element */
2643
2644 comprehension_ty l;
2645 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002646 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
2648 start = compiler_new_block(c);
2649 skip = compiler_new_block(c);
2650 if_cleanup = compiler_new_block(c);
2651 anchor = compiler_new_block(c);
2652
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2654 anchor == NULL)
2655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002657 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 VISIT(c, expr, l->iter);
2659 ADDOP(c, GET_ITER);
2660 compiler_use_next_block(c, start);
2661 ADDOP_JREL(c, FOR_ITER, anchor);
2662 NEXT_BLOCK(c);
2663 VISIT(c, expr, l->target);
2664
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 n = asdl_seq_LEN(l->ifs);
2667 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002668 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669 VISIT(c, expr, e);
2670 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2671 NEXT_BLOCK(c);
2672 ADDOP(c, POP_TOP);
2673 }
2674
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 if (++gen_index < asdl_seq_LEN(generators))
2676 if (!compiler_listcomp_generator(c, tmpname,
2677 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 /* only append after the last for generator */
2681 if (gen_index >= asdl_seq_LEN(generators)) {
2682 if (!compiler_nameop(c, tmpname, Load))
2683 return 0;
2684 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002685 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002686
2687 compiler_use_next_block(c, skip);
2688 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 for (i = 0; i < n; i++) {
2690 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 if (i == 0)
2692 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 ADDOP(c, POP_TOP);
2694 }
2695 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2696 compiler_use_next_block(c, anchor);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002697 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 return 0;
2701
2702 return 1;
2703}
2704
2705static int
2706compiler_listcomp(struct compiler *c, expr_ty e)
2707{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002709 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 asdl_seq *generators = e->v.ListComp.generators;
2711
2712 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002713 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 if (!tmp)
2715 return 0;
2716 ADDOP_I(c, BUILD_LIST, 0);
2717 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2720 e->v.ListComp.elt);
2721 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 return rc;
2723}
2724
2725static int
2726compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002727 asdl_seq *generators, int gen_index,
2728 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729{
2730 /* generate code for the iterator, then each of the ifs,
2731 and then write to the element */
2732
2733 comprehension_ty ge;
2734 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002735 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
2737 start = compiler_new_block(c);
2738 skip = compiler_new_block(c);
2739 if_cleanup = compiler_new_block(c);
2740 anchor = compiler_new_block(c);
2741 end = compiler_new_block(c);
2742
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002743 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744 anchor == NULL || end == NULL)
2745 return 0;
2746
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002747 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748 ADDOP_JREL(c, SETUP_LOOP, end);
2749 if (!compiler_push_fblock(c, LOOP, start))
2750 return 0;
2751
2752 if (gen_index == 0) {
2753 /* Receive outermost iter as an implicit argument */
2754 c->u->u_argcount = 1;
2755 ADDOP_I(c, LOAD_FAST, 0);
2756 }
2757 else {
2758 /* Sub-iter - calculate on the fly */
2759 VISIT(c, expr, ge->iter);
2760 ADDOP(c, GET_ITER);
2761 }
2762 compiler_use_next_block(c, start);
2763 ADDOP_JREL(c, FOR_ITER, anchor);
2764 NEXT_BLOCK(c);
2765 VISIT(c, expr, ge->target);
2766
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002767 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768 n = asdl_seq_LEN(ge->ifs);
2769 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002770 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002771 VISIT(c, expr, e);
2772 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2773 NEXT_BLOCK(c);
2774 ADDOP(c, POP_TOP);
2775 }
2776
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002777 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2779 return 0;
2780
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781 /* only append after the last 'for' generator */
2782 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783 VISIT(c, expr, elt);
2784 ADDOP(c, YIELD_VALUE);
2785 ADDOP(c, POP_TOP);
2786
2787 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002788 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789 for (i = 0; i < n; i++) {
2790 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002791 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 compiler_use_next_block(c, if_cleanup);
2793
2794 ADDOP(c, POP_TOP);
2795 }
2796 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2797 compiler_use_next_block(c, anchor);
2798 ADDOP(c, POP_BLOCK);
2799 compiler_pop_fblock(c, LOOP, start);
2800 compiler_use_next_block(c, end);
2801
2802 return 1;
2803}
2804
2805static int
2806compiler_genexp(struct compiler *c, expr_ty e)
2807{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002808 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002809 PyCodeObject *co;
2810 expr_ty outermost_iter = ((comprehension_ty)
2811 (asdl_seq_GET(e->v.GeneratorExp.generators,
2812 0)))->iter;
2813
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002814 if (!name) {
2815 name = PyString_FromString("<genexpr>");
2816 if (!name)
2817 return 0;
2818 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819
2820 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2821 return 0;
2822 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2823 e->v.GeneratorExp.elt);
2824 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002825 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826 if (co == NULL)
2827 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002828
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002830 Py_DECREF(co);
2831
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832 VISIT(c, expr, outermost_iter);
2833 ADDOP(c, GET_ITER);
2834 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835
2836 return 1;
2837}
2838
2839static int
2840compiler_visit_keyword(struct compiler *c, keyword_ty k)
2841{
2842 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2843 VISIT(c, expr, k->value);
2844 return 1;
2845}
2846
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002847/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848 whether they are true or false.
2849
2850 Return values: 1 for true, 0 for false, -1 for non-constant.
2851 */
2852
2853static int
2854expr_constant(expr_ty e)
2855{
2856 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002857 case Ellipsis_kind:
2858 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859 case Num_kind:
2860 return PyObject_IsTrue(e->v.Num.n);
2861 case Str_kind:
2862 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002863 case Name_kind:
2864 /* __debug__ is not assignable, so we can optimize
2865 * it away in if and while statements */
2866 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2867 "__debug__") == 0)
2868 return ! Py_OptimizeFlag;
2869 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870 default:
2871 return -1;
2872 }
2873}
2874
Guido van Rossumc2e20742006-02-27 22:32:47 +00002875/*
2876 Implements the with statement from PEP 343.
2877
2878 The semantics outlined in that PEP are as follows:
2879
2880 with EXPR as VAR:
2881 BLOCK
2882
2883 It is implemented roughly as:
2884
Thomas Wouters477c8d52006-05-27 19:21:47 +00002885 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002886 exit = context.__exit__ # not calling it
2887 value = context.__enter__()
2888 try:
2889 VAR = value # if VAR present in the syntax
2890 BLOCK
2891 finally:
2892 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002894 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002895 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002896 exit(*exc)
2897 */
2898static int
2899compiler_with(struct compiler *c, stmt_ty s)
2900{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002901 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002902 basicblock *block, *finally;
2903 identifier tmpexit, tmpvalue = NULL;
2904
2905 assert(s->kind == With_kind);
2906
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002908 enter_attr = PyString_InternFromString("__enter__");
2909 if (!enter_attr)
2910 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002911 }
2912 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 exit_attr = PyString_InternFromString("__exit__");
2914 if (!exit_attr)
2915 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916 }
2917
2918 block = compiler_new_block(c);
2919 finally = compiler_new_block(c);
2920 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002921 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002922
2923 /* Create a temporary variable to hold context.__exit__ */
2924 tmpexit = compiler_new_tmpname(c);
2925 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002927 PyArena_AddPyObject(c->c_arena, tmpexit);
2928
2929 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002931 We need to do this rather than preserving it on the stack
2932 because SETUP_FINALLY remembers the stack level.
2933 We need to do the assignment *inside* the try/finally
2934 so that context.__exit__() is called when the assignment
2935 fails. But we need to call context.__enter__() *before*
2936 the try/finally so that if it fails we won't call
2937 context.__exit__().
2938 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002939 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002940 if (tmpvalue == NULL)
2941 return 0;
2942 PyArena_AddPyObject(c->c_arena, tmpvalue);
2943 }
2944
Thomas Wouters477c8d52006-05-27 19:21:47 +00002945 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002946 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002947
2948 /* Squirrel away context.__exit__ */
2949 ADDOP(c, DUP_TOP);
2950 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2951 if (!compiler_nameop(c, tmpexit, Store))
2952 return 0;
2953
2954 /* Call context.__enter__() */
2955 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2956 ADDOP_I(c, CALL_FUNCTION, 0);
2957
2958 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 /* Store it in tmpvalue */
2960 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002961 return 0;
2962 }
2963 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002964 /* Discard result from context.__enter__() */
2965 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002966 }
2967
2968 /* Start the try block */
2969 ADDOP_JREL(c, SETUP_FINALLY, finally);
2970
2971 compiler_use_next_block(c, block);
2972 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002973 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002974 }
2975
2976 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 /* Bind saved result of context.__enter__() to VAR */
2978 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002979 !compiler_nameop(c, tmpvalue, Del))
2980 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002982 }
2983
2984 /* BLOCK code */
2985 VISIT_SEQ(c, stmt, s->v.With.body);
2986
2987 /* End of try block; start the finally block */
2988 ADDOP(c, POP_BLOCK);
2989 compiler_pop_fblock(c, FINALLY_TRY, block);
2990
2991 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2992 compiler_use_next_block(c, finally);
2993 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002994 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002995
2996 /* Finally block starts; push tmpexit and issue our magic opcode. */
2997 if (!compiler_nameop(c, tmpexit, Load) ||
2998 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002999 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003000 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003001
3002 /* Finally block ends. */
3003 ADDOP(c, END_FINALLY);
3004 compiler_pop_fblock(c, FINALLY_END, finally);
3005 return 1;
3006}
3007
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008static int
3009compiler_visit_expr(struct compiler *c, expr_ty e)
3010{
3011 int i, n;
3012
Thomas Wouters89f507f2006-12-13 04:49:30 +00003013 /* If expr e has a different line number than the last expr/stmt,
3014 set a new line number for the next instruction.
3015 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 if (e->lineno > c->u->u_lineno) {
3017 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003018 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 }
3020 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003021 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003023 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 VISIT(c, expr, e->v.BinOp.left);
3025 VISIT(c, expr, e->v.BinOp.right);
3026 ADDOP(c, binop(c, e->v.BinOp.op));
3027 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003028 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 VISIT(c, expr, e->v.UnaryOp.operand);
3030 ADDOP(c, unaryop(e->v.UnaryOp.op));
3031 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003034 case IfExp_kind:
3035 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003036 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 /* XXX get rid of arg? */
3038 ADDOP_I(c, BUILD_MAP, 0);
3039 n = asdl_seq_LEN(e->v.Dict.values);
3040 /* We must arrange things just right for STORE_SUBSCR.
3041 It wants the stack to look like (value) (dict) (key) */
3042 for (i = 0; i < n; i++) {
3043 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003044 VISIT(c, expr,
3045 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003047 VISIT(c, expr,
3048 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049 ADDOP(c, STORE_SUBSCR);
3050 }
3051 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003052 case Set_kind:
3053 n = asdl_seq_LEN(e->v.Set.elts);
3054 VISIT_SEQ(c, expr, e->v.Set.elts);
3055 ADDOP_I(c, BUILD_SET, n);
3056 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003059 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060 return compiler_genexp(c, e);
3061 case Yield_kind:
3062 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003063 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064 if (e->v.Yield.value) {
3065 VISIT(c, expr, e->v.Yield.value);
3066 }
3067 else {
3068 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3069 }
3070 ADDOP(c, YIELD_VALUE);
3071 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003076 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3078 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003079 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3081 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003082 case Bytes_kind:
3083 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3084 ADDOP(c, MAKE_BYTES);
3085 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003086 case Ellipsis_kind:
3087 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3088 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003090 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 if (e->v.Attribute.ctx != AugStore)
3092 VISIT(c, expr, e->v.Attribute.value);
3093 switch (e->v.Attribute.ctx) {
3094 case AugLoad:
3095 ADDOP(c, DUP_TOP);
3096 /* Fall through to load */
3097 case Load:
3098 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3099 break;
3100 case AugStore:
3101 ADDOP(c, ROT_TWO);
3102 /* Fall through to save */
3103 case Store:
3104 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3105 break;
3106 case Del:
3107 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3108 break;
3109 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003110 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003111 PyErr_SetString(PyExc_SystemError,
3112 "param invalid in attribute expression");
3113 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114 }
3115 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117 switch (e->v.Subscript.ctx) {
3118 case AugLoad:
3119 VISIT(c, expr, e->v.Subscript.value);
3120 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3121 break;
3122 case Load:
3123 VISIT(c, expr, e->v.Subscript.value);
3124 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3125 break;
3126 case AugStore:
3127 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3128 break;
3129 case Store:
3130 VISIT(c, expr, e->v.Subscript.value);
3131 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3132 break;
3133 case Del:
3134 VISIT(c, expr, e->v.Subscript.value);
3135 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3136 break;
3137 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003138 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003139 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003141 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 }
3143 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003144 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3146 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003149 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150 return compiler_tuple(c, e);
3151 }
3152 return 1;
3153}
3154
3155static int
3156compiler_augassign(struct compiler *c, stmt_ty s)
3157{
3158 expr_ty e = s->v.AugAssign.target;
3159 expr_ty auge;
3160
3161 assert(s->kind == AugAssign_kind);
3162
3163 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003164 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003166 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 if (auge == NULL)
3168 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 VISIT(c, expr, auge);
3170 VISIT(c, expr, s->v.AugAssign.value);
3171 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3172 auge->v.Attribute.ctx = AugStore;
3173 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174 break;
3175 case Subscript_kind:
3176 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003177 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003178 if (auge == NULL)
3179 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 VISIT(c, expr, auge);
3181 VISIT(c, expr, s->v.AugAssign.value);
3182 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003187 if (!compiler_nameop(c, e->v.Name.id, Load))
3188 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189 VISIT(c, expr, s->v.AugAssign.value);
3190 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3191 return compiler_nameop(c, e->v.Name.id, Store);
3192 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003193 PyErr_Format(PyExc_SystemError,
3194 "invalid node type (%d) for augmented assignment",
3195 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197 }
3198 return 1;
3199}
3200
3201static int
3202compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3203{
3204 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003205 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3206 PyErr_SetString(PyExc_SystemError,
3207 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 f = &c->u->u_fblock[c->u->u_nfblocks++];
3211 f->fb_type = t;
3212 f->fb_block = b;
3213 return 1;
3214}
3215
3216static void
3217compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3218{
3219 struct compiler_unit *u = c->u;
3220 assert(u->u_nfblocks > 0);
3221 u->u_nfblocks--;
3222 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3223 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3224}
3225
Thomas Wouters89f507f2006-12-13 04:49:30 +00003226static int
3227compiler_in_loop(struct compiler *c) {
3228 int i;
3229 struct compiler_unit *u = c->u;
3230 for (i = 0; i < u->u_nfblocks; ++i) {
3231 if (u->u_fblock[i].fb_type == LOOP)
3232 return 1;
3233 }
3234 return 0;
3235}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236/* Raises a SyntaxError and returns 0.
3237 If something goes wrong, a different exception may be raised.
3238*/
3239
3240static int
3241compiler_error(struct compiler *c, const char *errstr)
3242{
3243 PyObject *loc;
3244 PyObject *u = NULL, *v = NULL;
3245
3246 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3247 if (!loc) {
3248 Py_INCREF(Py_None);
3249 loc = Py_None;
3250 }
3251 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3252 Py_None, loc);
3253 if (!u)
3254 goto exit;
3255 v = Py_BuildValue("(zO)", errstr, u);
3256 if (!v)
3257 goto exit;
3258 PyErr_SetObject(PyExc_SyntaxError, v);
3259 exit:
3260 Py_DECREF(loc);
3261 Py_XDECREF(u);
3262 Py_XDECREF(v);
3263 return 0;
3264}
3265
3266static int
3267compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003268 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003270 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003272 /* XXX this code is duplicated */
3273 switch (ctx) {
3274 case AugLoad: /* fall through to Load */
3275 case Load: op = BINARY_SUBSCR; break;
3276 case AugStore:/* fall through to Store */
3277 case Store: op = STORE_SUBSCR; break;
3278 case Del: op = DELETE_SUBSCR; break;
3279 case Param:
3280 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003281 "invalid %s kind %d in subscript\n",
3282 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 return 0;
3284 }
3285 if (ctx == AugLoad) {
3286 ADDOP_I(c, DUP_TOPX, 2);
3287 }
3288 else if (ctx == AugStore) {
3289 ADDOP(c, ROT_THREE);
3290 }
3291 ADDOP(c, op);
3292 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293}
3294
3295static int
3296compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3297{
3298 int n = 2;
3299 assert(s->kind == Slice_kind);
3300
3301 /* only handles the cases where BUILD_SLICE is emitted */
3302 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003303 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 }
3305 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003306 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003310 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 }
3312 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314 }
3315
3316 if (s->v.Slice.step) {
3317 n++;
3318 VISIT(c, expr, s->v.Slice.step);
3319 }
3320 ADDOP_I(c, BUILD_SLICE, n);
3321 return 1;
3322}
3323
3324static int
3325compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3326{
3327 int op = 0, slice_offset = 0, stack_count = 0;
3328
3329 assert(s->v.Slice.step == NULL);
3330 if (s->v.Slice.lower) {
3331 slice_offset++;
3332 stack_count++;
3333 if (ctx != AugStore)
3334 VISIT(c, expr, s->v.Slice.lower);
3335 }
3336 if (s->v.Slice.upper) {
3337 slice_offset += 2;
3338 stack_count++;
3339 if (ctx != AugStore)
3340 VISIT(c, expr, s->v.Slice.upper);
3341 }
3342
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003343 if (ctx == AugLoad) {
3344 switch (stack_count) {
3345 case 0: ADDOP(c, DUP_TOP); break;
3346 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3347 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3348 }
3349 }
3350 else if (ctx == AugStore) {
3351 switch (stack_count) {
3352 case 0: ADDOP(c, ROT_TWO); break;
3353 case 1: ADDOP(c, ROT_THREE); break;
3354 case 2: ADDOP(c, ROT_FOUR); break;
3355 }
3356 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357
3358 switch (ctx) {
3359 case AugLoad: /* fall through to Load */
3360 case Load: op = SLICE; break;
3361 case AugStore:/* fall through to Store */
3362 case Store: op = STORE_SLICE; break;
3363 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003364 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003365 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003366 PyErr_SetString(PyExc_SystemError,
3367 "param invalid in simple slice");
3368 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003369 }
3370
3371 ADDOP(c, op + slice_offset);
3372 return 1;
3373}
3374
3375static int
3376compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3377 expr_context_ty ctx)
3378{
3379 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380 case Slice_kind:
3381 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 case Index_kind:
3383 VISIT(c, expr, s->v.Index.value);
3384 break;
3385 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003386 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003387 PyErr_SetString(PyExc_SystemError,
3388 "extended slice invalid in nested slice");
3389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003390 }
3391 return 1;
3392}
3393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394static int
3395compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3396{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003397 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003399 case Index_kind:
3400 kindname = "index";
3401 if (ctx != AugStore) {
3402 VISIT(c, expr, s->v.Index.value);
3403 }
3404 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003406 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407 if (!s->v.Slice.step)
3408 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003409 if (ctx != AugStore) {
3410 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 return 0;
3412 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003413 break;
3414 case ExtSlice_kind:
3415 kindname = "extended slice";
3416 if (ctx != AugStore) {
3417 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3418 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003419 slice_ty sub = (slice_ty)asdl_seq_GET(
3420 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003421 if (!compiler_visit_nested_slice(c, sub, ctx))
3422 return 0;
3423 }
3424 ADDOP_I(c, BUILD_TUPLE, n);
3425 }
3426 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003427 default:
3428 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003429 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003430 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003432 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433}
3434
Thomas Wouters89f507f2006-12-13 04:49:30 +00003435/* End of the compiler section, beginning of the assembler section */
3436
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437/* do depth-first search of basic block graph, starting with block.
3438 post records the block indices in post-order.
3439
3440 XXX must handle implicit jumps from one block to next
3441*/
3442
Thomas Wouters89f507f2006-12-13 04:49:30 +00003443struct assembler {
3444 PyObject *a_bytecode; /* string containing bytecode */
3445 int a_offset; /* offset into bytecode */
3446 int a_nblocks; /* number of reachable blocks */
3447 basicblock **a_postorder; /* list of blocks in dfs postorder */
3448 PyObject *a_lnotab; /* string containing lnotab */
3449 int a_lnotab_off; /* offset into lnotab */
3450 int a_lineno; /* last lineno of emitted instruction */
3451 int a_lineno_off; /* bytecode offset of last lineno */
3452};
3453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003454static void
3455dfs(struct compiler *c, basicblock *b, struct assembler *a)
3456{
3457 int i;
3458 struct instr *instr = NULL;
3459
3460 if (b->b_seen)
3461 return;
3462 b->b_seen = 1;
3463 if (b->b_next != NULL)
3464 dfs(c, b->b_next, a);
3465 for (i = 0; i < b->b_iused; i++) {
3466 instr = &b->b_instr[i];
3467 if (instr->i_jrel || instr->i_jabs)
3468 dfs(c, instr->i_target, a);
3469 }
3470 a->a_postorder[a->a_nblocks++] = b;
3471}
3472
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003473static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3475{
3476 int i;
3477 struct instr *instr;
3478 if (b->b_seen || b->b_startdepth >= depth)
3479 return maxdepth;
3480 b->b_seen = 1;
3481 b->b_startdepth = depth;
3482 for (i = 0; i < b->b_iused; i++) {
3483 instr = &b->b_instr[i];
3484 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3485 if (depth > maxdepth)
3486 maxdepth = depth;
3487 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3488 if (instr->i_jrel || instr->i_jabs) {
3489 maxdepth = stackdepth_walk(c, instr->i_target,
3490 depth, maxdepth);
3491 if (instr->i_opcode == JUMP_ABSOLUTE ||
3492 instr->i_opcode == JUMP_FORWARD) {
3493 goto out; /* remaining code is dead */
3494 }
3495 }
3496 }
3497 if (b->b_next)
3498 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3499out:
3500 b->b_seen = 0;
3501 return maxdepth;
3502}
3503
3504/* Find the flow path that needs the largest stack. We assume that
3505 * cycles in the flow graph have no net effect on the stack depth.
3506 */
3507static int
3508stackdepth(struct compiler *c)
3509{
3510 basicblock *b, *entryblock;
3511 entryblock = NULL;
3512 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3513 b->b_seen = 0;
3514 b->b_startdepth = INT_MIN;
3515 entryblock = b;
3516 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003517 if (!entryblock)
3518 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519 return stackdepth_walk(c, entryblock, 0, 0);
3520}
3521
3522static int
3523assemble_init(struct assembler *a, int nblocks, int firstlineno)
3524{
3525 memset(a, 0, sizeof(struct assembler));
3526 a->a_lineno = firstlineno;
3527 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3528 if (!a->a_bytecode)
3529 return 0;
3530 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3531 if (!a->a_lnotab)
3532 return 0;
3533 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003534 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003535 if (!a->a_postorder) {
3536 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 return 1;
3540}
3541
3542static void
3543assemble_free(struct assembler *a)
3544{
3545 Py_XDECREF(a->a_bytecode);
3546 Py_XDECREF(a->a_lnotab);
3547 if (a->a_postorder)
3548 PyObject_Free(a->a_postorder);
3549}
3550
3551/* Return the size of a basic block in bytes. */
3552
3553static int
3554instrsize(struct instr *instr)
3555{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003556 if (!instr->i_hasarg)
3557 return 1;
3558 if (instr->i_oparg > 0xffff)
3559 return 6;
3560 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561}
3562
3563static int
3564blocksize(basicblock *b)
3565{
3566 int i;
3567 int size = 0;
3568
3569 for (i = 0; i < b->b_iused; i++)
3570 size += instrsize(&b->b_instr[i]);
3571 return size;
3572}
3573
3574/* All about a_lnotab.
3575
3576c_lnotab is an array of unsigned bytes disguised as a Python string.
3577It is used to map bytecode offsets to source code line #s (when needed
3578for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003579
Tim Peters2a7f3842001-06-09 09:26:21 +00003580The array is conceptually a list of
3581 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003582pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003583
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003584 byte code offset source code line number
3585 0 1
3586 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003587 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 350 307
3589 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003590
3591The first trick is that these numbers aren't stored, only the increments
3592from one row to the next (this doesn't really work, but it's a start):
3593
3594 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3595
3596The second trick is that an unsigned byte can't hold negative values, or
3597values larger than 255, so (a) there's a deep assumption that byte code
3598offsets and their corresponding line #s both increase monotonically, and (b)
3599if at least one column jumps by more than 255 from one row to the next, more
3600than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003601from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003602part. A user of c_lnotab desiring to find the source line number
3603corresponding to a bytecode address A should do something like this
3604
3605 lineno = addr = 0
3606 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003607 addr += addr_incr
3608 if addr > A:
3609 return lineno
3610 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003611
3612In order for this to work, when the addr field increments by more than 255,
3613the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003614increment is < 256. So, in the example above, assemble_lnotab (it used
3615to be called com_set_lineno) should not (as was actually done until 2.2)
3616expand 300, 300 to 255, 255, 45, 45,
3617 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003618*/
3619
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003620static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003622{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 int d_bytecode, d_lineno;
3624 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003625 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626
3627 d_bytecode = a->a_offset - a->a_lineno_off;
3628 d_lineno = i->i_lineno - a->a_lineno;
3629
3630 assert(d_bytecode >= 0);
3631 assert(d_lineno >= 0);
3632
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003633 /* XXX(nnorwitz): is there a better way to handle this?
3634 for loops are special, we want to be able to trace them
3635 each time around, so we need to set an extra line number. */
3636 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003637 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003638
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003640 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 nbytes = a->a_lnotab_off + 2 * ncodes;
3642 len = PyString_GET_SIZE(a->a_lnotab);
3643 if (nbytes >= len) {
3644 if (len * 2 < nbytes)
3645 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003646 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 len *= 2;
3648 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3649 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003650 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003651 lnotab = (unsigned char *)
3652 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003653 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 *lnotab++ = 255;
3655 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003656 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 d_bytecode -= ncodes * 255;
3658 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 assert(d_bytecode <= 255);
3661 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003662 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663 nbytes = a->a_lnotab_off + 2 * ncodes;
3664 len = PyString_GET_SIZE(a->a_lnotab);
3665 if (nbytes >= len) {
3666 if (len * 2 < nbytes)
3667 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003668 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003669 len *= 2;
3670 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3671 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003672 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003673 lnotab = (unsigned char *)
3674 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003676 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003678 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003680 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 d_lineno -= ncodes * 255;
3683 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003684 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003685
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686 len = PyString_GET_SIZE(a->a_lnotab);
3687 if (a->a_lnotab_off + 2 >= len) {
3688 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003689 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003690 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003691 lnotab = (unsigned char *)
3692 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 a->a_lnotab_off += 2;
3695 if (d_bytecode) {
3696 *lnotab++ = d_bytecode;
3697 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003698 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003699 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 *lnotab++ = 0;
3701 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703 a->a_lineno = i->i_lineno;
3704 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003705 return 1;
3706}
3707
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708/* assemble_emit()
3709 Extend the bytecode with a new instruction.
3710 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003711*/
3712
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003713static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003715{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003716 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003717 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 char *code;
3719
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003720 size = instrsize(i);
3721 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003723 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003724 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003726 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 if (a->a_offset + size >= len) {
3728 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003729 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003730 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3732 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003733 if (size == 6) {
3734 assert(i->i_hasarg);
3735 *code++ = (char)EXTENDED_ARG;
3736 *code++ = ext & 0xff;
3737 *code++ = ext >> 8;
3738 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003739 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003741 if (i->i_hasarg) {
3742 assert(size == 3 || size == 6);
3743 *code++ = arg & 0xff;
3744 *code++ = arg >> 8;
3745 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003747}
3748
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003749static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003751{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003752 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003753 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003754 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003755
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003756 /* Compute the size of each block and fixup jump args.
3757 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003758start:
3759 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003761 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 bsize = blocksize(b);
3763 b->b_offset = totsize;
3764 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003765 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003766 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3768 bsize = b->b_offset;
3769 for (i = 0; i < b->b_iused; i++) {
3770 struct instr *instr = &b->b_instr[i];
3771 /* Relative jumps are computed relative to
3772 the instruction pointer after fetching
3773 the jump instruction.
3774 */
3775 bsize += instrsize(instr);
3776 if (instr->i_jabs)
3777 instr->i_oparg = instr->i_target->b_offset;
3778 else if (instr->i_jrel) {
3779 int delta = instr->i_target->b_offset - bsize;
3780 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003781 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003782 else
3783 continue;
3784 if (instr->i_oparg > 0xffff)
3785 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003786 }
3787 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003788
3789 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003790 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003791 with a better solution.
3792
3793 In the meantime, should the goto be dropped in favor
3794 of a loop?
3795
3796 The issue is that in the first loop blocksize() is called
3797 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003798 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003799 i_oparg is calculated in the second loop above.
3800
3801 So we loop until we stop seeing new EXTENDED_ARGs.
3802 The only EXTENDED_ARGs that could be popping up are
3803 ones in jump instructions. So this should converge
3804 fairly quickly.
3805 */
3806 if (last_extended_arg_count != extended_arg_count) {
3807 last_extended_arg_count = extended_arg_count;
3808 goto start;
3809 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003810}
3811
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003812static PyObject *
3813dict_keys_inorder(PyObject *dict, int offset)
3814{
3815 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003816 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003817
3818 tuple = PyTuple_New(size);
3819 if (tuple == NULL)
3820 return NULL;
3821 while (PyDict_Next(dict, &pos, &k, &v)) {
3822 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003823 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003824 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003825 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003826 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003827 PyTuple_SET_ITEM(tuple, i - offset, k);
3828 }
3829 return tuple;
3830}
3831
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003832static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003834{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 PySTEntryObject *ste = c->u->u_ste;
3836 int flags = 0, n;
3837 if (ste->ste_type != ModuleBlock)
3838 flags |= CO_NEWLOCALS;
3839 if (ste->ste_type == FunctionBlock) {
3840 if (!ste->ste_unoptimized)
3841 flags |= CO_OPTIMIZED;
3842 if (ste->ste_nested)
3843 flags |= CO_NESTED;
3844 if (ste->ste_generator)
3845 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 if (ste->ste_varargs)
3848 flags |= CO_VARARGS;
3849 if (ste->ste_varkeywords)
3850 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003851 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003853
3854 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003855 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 n = PyDict_Size(c->u->u_freevars);
3858 if (n < 0)
3859 return -1;
3860 if (n == 0) {
3861 n = PyDict_Size(c->u->u_cellvars);
3862 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003863 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864 if (n == 0) {
3865 flags |= CO_NOFREE;
3866 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003867 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003868
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003869 return flags;
3870}
3871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872static PyCodeObject *
3873makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003874{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875 PyObject *tmp;
3876 PyCodeObject *co = NULL;
3877 PyObject *consts = NULL;
3878 PyObject *names = NULL;
3879 PyObject *varnames = NULL;
3880 PyObject *filename = NULL;
3881 PyObject *name = NULL;
3882 PyObject *freevars = NULL;
3883 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003884 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 tmp = dict_keys_inorder(c->u->u_consts, 0);
3888 if (!tmp)
3889 goto error;
3890 consts = PySequence_List(tmp); /* optimize_code requires a list */
3891 Py_DECREF(tmp);
3892
3893 names = dict_keys_inorder(c->u->u_names, 0);
3894 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3895 if (!consts || !names || !varnames)
3896 goto error;
3897
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003898 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3899 if (!cellvars)
3900 goto error;
3901 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3902 if (!freevars)
3903 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 filename = PyString_FromString(c->c_filename);
3905 if (!filename)
3906 goto error;
3907
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003908 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 flags = compute_code_flags(c);
3910 if (flags < 0)
3911 goto error;
3912
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003913 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 if (!bytecode)
3915 goto error;
3916
3917 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3918 if (!tmp)
3919 goto error;
3920 Py_DECREF(consts);
3921 consts = tmp;
3922
Guido van Rossum4f72a782006-10-27 23:31:49 +00003923 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3924 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003925 bytecode, consts, names, varnames,
3926 freevars, cellvars,
3927 filename, c->u->u_name,
3928 c->u->u_firstlineno,
3929 a->a_lnotab);
3930 error:
3931 Py_XDECREF(consts);
3932 Py_XDECREF(names);
3933 Py_XDECREF(varnames);
3934 Py_XDECREF(filename);
3935 Py_XDECREF(name);
3936 Py_XDECREF(freevars);
3937 Py_XDECREF(cellvars);
3938 Py_XDECREF(bytecode);
3939 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003940}
3941
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003942
3943/* For debugging purposes only */
3944#if 0
3945static void
3946dump_instr(const struct instr *i)
3947{
3948 const char *jrel = i->i_jrel ? "jrel " : "";
3949 const char *jabs = i->i_jabs ? "jabs " : "";
3950 char arg[128];
3951
3952 *arg = '\0';
3953 if (i->i_hasarg)
3954 sprintf(arg, "arg: %d ", i->i_oparg);
3955
3956 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3957 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3958}
3959
3960static void
3961dump_basicblock(const basicblock *b)
3962{
3963 const char *seen = b->b_seen ? "seen " : "";
3964 const char *b_return = b->b_return ? "return " : "";
3965 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3966 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3967 if (b->b_instr) {
3968 int i;
3969 for (i = 0; i < b->b_iused; i++) {
3970 fprintf(stderr, " [%02d] ", i);
3971 dump_instr(b->b_instr + i);
3972 }
3973 }
3974}
3975#endif
3976
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003977static PyCodeObject *
3978assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003979{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 basicblock *b, *entryblock;
3981 struct assembler a;
3982 int i, j, nblocks;
3983 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003984
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985 /* Make sure every block that falls off the end returns None.
3986 XXX NEXT_BLOCK() isn't quite right, because if the last
3987 block ends with a jump or return b_next shouldn't set.
3988 */
3989 if (!c->u->u_curblock->b_return) {
3990 NEXT_BLOCK(c);
3991 if (addNone)
3992 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3993 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003994 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003995
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003996 nblocks = 0;
3997 entryblock = NULL;
3998 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3999 nblocks++;
4000 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004001 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004002
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004003 /* Set firstlineno if it wasn't explicitly set. */
4004 if (!c->u->u_firstlineno) {
4005 if (entryblock && entryblock->b_instr)
4006 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4007 else
4008 c->u->u_firstlineno = 1;
4009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4011 goto error;
4012 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004013
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004014 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004015 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004017 /* Emit code in reverse postorder from dfs. */
4018 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004019 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 for (j = 0; j < b->b_iused; j++)
4021 if (!assemble_emit(&a, &b->b_instr[j]))
4022 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004023 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4026 goto error;
4027 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4028 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 co = makecode(c, &a);
4031 error:
4032 assemble_free(&a);
4033 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004034}