blob: 927569a9287be098a5f87de751b7e1dc2162e96a [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 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000122 bool u_lineno_set; /* boolean to indicate whether instr
123 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;
467 u->u_lineno_set = false;
468 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;
646 c->u->u_lineno_set = true;
647 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;
792 case LOAD_ATTR:
793 return 0;
794 case COMPARE_OP:
795 return -1;
796 case IMPORT_NAME:
797 return 0;
798 case IMPORT_FROM:
799 return 1;
800
801 case JUMP_FORWARD:
802 case JUMP_IF_FALSE:
803 case JUMP_IF_TRUE:
804 case JUMP_ABSOLUTE:
805 return 0;
806
807 case LOAD_GLOBAL:
808 return 1;
809
810 case CONTINUE_LOOP:
811 return 0;
812 case SETUP_LOOP:
813 return 0;
814 case SETUP_EXCEPT:
815 case SETUP_FINALLY:
816 return 3; /* actually pushed by an exception */
817
818 case LOAD_FAST:
819 return 1;
820 case STORE_FAST:
821 return -1;
822 case DELETE_FAST:
823 return 0;
824
825 case RAISE_VARARGS:
826 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000827#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000828 case CALL_FUNCTION:
829 return -NARGS(oparg);
830 case CALL_FUNCTION_VAR:
831 case CALL_FUNCTION_KW:
832 return -NARGS(oparg)-1;
833 case CALL_FUNCTION_VAR_KW:
834 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000836 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000837#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838 case BUILD_SLICE:
839 if (oparg == 3)
840 return -2;
841 else
842 return -1;
843
844 case MAKE_CLOSURE:
845 return -oparg;
846 case LOAD_CLOSURE:
847 return 1;
848 case LOAD_DEREF:
849 return 1;
850 case STORE_DEREF:
851 return -1;
852 default:
853 fprintf(stderr, "opcode = %d\n", opcode);
854 Py_FatalError("opcode_stack_effect()");
855
856 }
857 return 0; /* not reachable */
858}
859
860/* Add an opcode with no argument.
861 Returns 0 on failure, 1 on success.
862*/
863
864static int
865compiler_addop(struct compiler *c, int opcode)
866{
867 basicblock *b;
868 struct instr *i;
869 int off;
870 off = compiler_next_instr(c, c->u->u_curblock);
871 if (off < 0)
872 return 0;
873 b = c->u->u_curblock;
874 i = &b->b_instr[off];
875 i->i_opcode = opcode;
876 i->i_hasarg = 0;
877 if (opcode == RETURN_VALUE)
878 b->b_return = 1;
879 compiler_set_lineno(c, off);
880 return 1;
881}
882
883static int
884compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
885{
886 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000887 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000889 /* necessary to make sure types aren't coerced (e.g., int and long) */
890 t = PyTuple_Pack(2, o, o->ob_type);
891 if (t == NULL)
892 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000893
894 v = PyDict_GetItem(dict, t);
895 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000896 if (PyErr_Occurred())
897 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000898 arg = PyDict_Size(dict);
899 v = PyInt_FromLong(arg);
900 if (!v) {
901 Py_DECREF(t);
902 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904 if (PyDict_SetItem(dict, t, v) < 0) {
905 Py_DECREF(t);
906 Py_DECREF(v);
907 return -1;
908 }
909 Py_DECREF(v);
910 }
911 else
912 arg = PyInt_AsLong(v);
913 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000914 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000915}
916
917static int
918compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
919 PyObject *o)
920{
921 int arg = compiler_add_o(c, dict, o);
922 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924 return compiler_addop_i(c, opcode, arg);
925}
926
927static int
928compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000929 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000930{
931 int arg;
932 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
933 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935 arg = compiler_add_o(c, dict, mangled);
936 Py_DECREF(mangled);
937 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000939 return compiler_addop_i(c, opcode, arg);
940}
941
942/* Add an opcode with an integer argument.
943 Returns 0 on failure, 1 on success.
944*/
945
946static int
947compiler_addop_i(struct compiler *c, int opcode, int oparg)
948{
949 struct instr *i;
950 int off;
951 off = compiler_next_instr(c, c->u->u_curblock);
952 if (off < 0)
953 return 0;
954 i = &c->u->u_curblock->b_instr[off];
955 i->i_opcode = opcode;
956 i->i_oparg = oparg;
957 i->i_hasarg = 1;
958 compiler_set_lineno(c, off);
959 return 1;
960}
961
962static int
963compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
964{
965 struct instr *i;
966 int off;
967
968 assert(b != NULL);
969 off = compiler_next_instr(c, c->u->u_curblock);
970 if (off < 0)
971 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000972 i = &c->u->u_curblock->b_instr[off];
973 i->i_opcode = opcode;
974 i->i_target = b;
975 i->i_hasarg = 1;
976 if (absolute)
977 i->i_jabs = 1;
978 else
979 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000980 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981 return 1;
982}
983
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000984/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
985 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986 it as the current block. NEXT_BLOCK() also creates an implicit jump
987 from the current block to the new block.
988*/
989
Thomas Wouters89f507f2006-12-13 04:49:30 +0000990/* The returns inside these macros make it impossible to decref objects
991 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000992*/
993
994
995#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000996 if (compiler_use_new_block((C)) == NULL) \
997 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998}
999
1000#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001001 if (compiler_next_block((C)) == NULL) \
1002 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003}
1004
1005#define ADDOP(C, OP) { \
1006 if (!compiler_addop((C), (OP))) \
1007 return 0; \
1008}
1009
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001010#define ADDOP_IN_SCOPE(C, OP) { \
1011 if (!compiler_addop((C), (OP))) { \
1012 compiler_exit_scope(c); \
1013 return 0; \
1014 } \
1015}
1016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017#define ADDOP_O(C, OP, O, TYPE) { \
1018 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1019 return 0; \
1020}
1021
1022#define ADDOP_NAME(C, OP, O, TYPE) { \
1023 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1024 return 0; \
1025}
1026
1027#define ADDOP_I(C, OP, O) { \
1028 if (!compiler_addop_i((C), (OP), (O))) \
1029 return 0; \
1030}
1031
1032#define ADDOP_JABS(C, OP, O) { \
1033 if (!compiler_addop_j((C), (OP), (O), 1)) \
1034 return 0; \
1035}
1036
1037#define ADDOP_JREL(C, OP, O) { \
1038 if (!compiler_addop_j((C), (OP), (O), 0)) \
1039 return 0; \
1040}
1041
1042/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1043 the ASDL name to synthesize the name of the C type and the visit function.
1044*/
1045
1046#define VISIT(C, TYPE, V) {\
1047 if (!compiler_visit_ ## TYPE((C), (V))) \
1048 return 0; \
1049}
1050
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001051#define VISIT_IN_SCOPE(C, TYPE, V) {\
1052 if (!compiler_visit_ ## TYPE((C), (V))) { \
1053 compiler_exit_scope(c); \
1054 return 0; \
1055 } \
1056}
1057
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058#define VISIT_SLICE(C, V, CTX) {\
1059 if (!compiler_visit_slice((C), (V), (CTX))) \
1060 return 0; \
1061}
1062
1063#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001064 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001065 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001066 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068 if (!compiler_visit_ ## TYPE((C), elt)) \
1069 return 0; \
1070 } \
1071}
1072
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001073#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001074 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001076 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001077 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001078 if (!compiler_visit_ ## TYPE((C), elt)) { \
1079 compiler_exit_scope(c); \
1080 return 0; \
1081 } \
1082 } \
1083}
1084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001085static int
1086compiler_isdocstring(stmt_ty s)
1087{
1088 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001089 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001090 return s->v.Expr.value->kind == Str_kind;
1091}
1092
1093/* Compile a sequence of statements, checking for a docstring. */
1094
1095static int
1096compiler_body(struct compiler *c, asdl_seq *stmts)
1097{
1098 int i = 0;
1099 stmt_ty st;
1100
1101 if (!asdl_seq_LEN(stmts))
1102 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001103 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104 if (compiler_isdocstring(st)) {
1105 i = 1;
1106 VISIT(c, expr, st->v.Expr.value);
1107 if (!compiler_nameop(c, __doc__, Store))
1108 return 0;
1109 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001110 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001111 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112 return 1;
1113}
1114
1115static PyCodeObject *
1116compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001117{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001118 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001119 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 static PyObject *module;
1121 if (!module) {
1122 module = PyString_FromString("<module>");
1123 if (!module)
1124 return NULL;
1125 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001126 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1127 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001128 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 switch (mod->kind) {
1130 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001131 if (!compiler_body(c, mod->v.Module.body)) {
1132 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001134 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 break;
1136 case Interactive_kind:
1137 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138 VISIT_SEQ_IN_SCOPE(c, stmt,
1139 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 break;
1141 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001142 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001143 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 break;
1145 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001146 PyErr_SetString(PyExc_SystemError,
1147 "suite should not be possible");
1148 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001149 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001150 PyErr_Format(PyExc_SystemError,
1151 "module kind %d should not be possible",
1152 mod->kind);
1153 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001154 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 co = assemble(c, addNone);
1156 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001157 return co;
1158}
1159
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160/* The test for LOCAL must come before the test for FREE in order to
1161 handle classes where name is both local and free. The local var is
1162 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001163*/
1164
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165static int
1166get_ref_type(struct compiler *c, PyObject *name)
1167{
1168 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001169 if (scope == 0) {
1170 char buf[350];
1171 PyOS_snprintf(buf, sizeof(buf),
1172 "unknown scope for %.100s in %.100s(%s) in %s\n"
1173 "symbols: %s\nlocals: %s\nglobals: %s\n",
1174 PyString_AS_STRING(name),
1175 PyString_AS_STRING(c->u->u_name),
1176 PyObject_REPR(c->u->u_ste->ste_id),
1177 c->c_filename,
1178 PyObject_REPR(c->u->u_ste->ste_symbols),
1179 PyObject_REPR(c->u->u_varnames),
1180 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001182 Py_FatalError(buf);
1183 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001184
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001185 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
1188static int
1189compiler_lookup_arg(PyObject *dict, PyObject *name)
1190{
1191 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001192 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001194 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001196 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001198 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return PyInt_AS_LONG(v);
1200}
1201
1202static int
1203compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1204{
1205 int i, free = PyCode_GetNumFree(co);
1206 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001207 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1208 ADDOP_I(c, MAKE_FUNCTION, args);
1209 return 1;
1210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 for (i = 0; i < free; ++i) {
1212 /* Bypass com_addop_varname because it will generate
1213 LOAD_DEREF but LOAD_CLOSURE is needed.
1214 */
1215 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1216 int arg, reftype;
1217
1218 /* Special case: If a class contains a method with a
1219 free variable that has the same name as a method,
1220 the name will be considered free *and* local in the
1221 class. It should be handled by the closure, as
1222 well as by the normal name loookup logic.
1223 */
1224 reftype = get_ref_type(c, name);
1225 if (reftype == CELL)
1226 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1227 else /* (reftype == FREE) */
1228 arg = compiler_lookup_arg(c->u->u_freevars, name);
1229 if (arg == -1) {
1230 printf("lookup %s in %s %d %d\n"
1231 "freevars of %s: %s\n",
1232 PyObject_REPR(name),
1233 PyString_AS_STRING(c->u->u_name),
1234 reftype, arg,
1235 PyString_AS_STRING(co->co_name),
1236 PyObject_REPR(co->co_freevars));
1237 Py_FatalError("compiler_make_closure()");
1238 }
1239 ADDOP_I(c, LOAD_CLOSURE, arg);
1240 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001241 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 ADDOP_I(c, MAKE_CLOSURE, args);
1244 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245}
1246
1247static int
1248compiler_decorators(struct compiler *c, asdl_seq* decos)
1249{
1250 int i;
1251
1252 if (!decos)
1253 return 1;
1254
1255 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001256 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 }
1258 return 1;
1259}
1260
1261static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001262compiler_unpack_nested(struct compiler *c, asdl_seq *args) {
1263 int i, len;
1264 len = asdl_seq_LEN(args);
1265 ADDOP_I(c, UNPACK_SEQUENCE, len);
1266 for (i = 0; i < len; i++) {
1267 arg_ty elt = (arg_ty)asdl_seq_GET(args, i);
1268 switch (elt->kind) {
1269 case SimpleArg_kind:
1270 if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store))
1271 return 0;
1272 break;
1273 case NestedArgs_kind:
1274 if (!compiler_unpack_nested(c, elt->v.NestedArgs.args))
1275 return 0;
1276 break;
1277 default:
1278 return 0;
1279 }
1280 }
1281 return 1;
1282}
1283
1284static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285compiler_arguments(struct compiler *c, arguments_ty args)
1286{
1287 int i;
1288 int n = asdl_seq_LEN(args->args);
Neal Norwitzc1505362006-12-28 06:47:50 +00001289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290 for (i = 0; i < n; i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001291 arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i);
1292 if (arg->kind == NestedArgs_kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293 PyObject *id = PyString_FromFormat(".%d", i);
1294 if (id == NULL) {
1295 return 0;
1296 }
1297 if (!compiler_nameop(c, id, Load)) {
1298 Py_DECREF(id);
1299 return 0;
1300 }
1301 Py_DECREF(id);
Neal Norwitzc1505362006-12-28 06:47:50 +00001302 if (!compiler_unpack_nested(c, arg->v.NestedArgs.args))
1303 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001304 }
1305 }
1306 return 1;
1307}
1308
1309static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001310compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1311 asdl_seq *kw_defaults)
1312{
1313 int i, default_count = 0;
1314 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001315 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001316 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1317 if (default_) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001318 ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001319 if (!compiler_visit_expr(c, default_)) {
1320 return -1;
1321 }
1322 default_count++;
1323 }
1324 }
1325 return default_count;
1326}
1327
1328static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001329compiler_visit_argannotation(struct compiler *c, identifier id,
1330 expr_ty annotation, PyObject *names)
1331{
1332 if (annotation) {
1333 VISIT(c, expr, annotation);
1334 if (PyList_Append(names, id))
1335 return -1;
1336 }
1337 return 0;
1338}
1339
1340static int
1341compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1342 PyObject *names)
1343{
1344 int i, error;
1345 for (i = 0; i < asdl_seq_LEN(args); i++) {
1346 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1347 if (arg->kind == NestedArgs_kind)
1348 error = compiler_visit_argannotations(
1349 c,
1350 arg->v.NestedArgs.args,
1351 names);
1352 else
1353 error = compiler_visit_argannotation(
1354 c,
1355 arg->v.SimpleArg.arg,
1356 arg->v.SimpleArg.annotation,
1357 names);
1358 if (error)
1359 return error;
1360 }
1361 return 0;
1362}
1363
1364static int
1365compiler_visit_annotations(struct compiler *c, arguments_ty args,
1366 expr_ty returns)
1367{
1368 /* push arg annotations and a list of the argument names. return the #
1369 of items pushed. this is out-of-order wrt the source code. */
1370 static identifier return_str;
1371 PyObject *names;
1372 int len;
1373 names = PyList_New(0);
1374 if (!names)
1375 return -1;
1376
1377 if (compiler_visit_argannotations(c, args->args, names))
1378 goto error;
1379 if (args->varargannotation &&
1380 compiler_visit_argannotation(c, args->vararg,
1381 args->varargannotation, names))
1382 goto error;
1383 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1384 goto error;
1385 if (args->kwargannotation &&
1386 compiler_visit_argannotation(c, args->kwarg,
1387 args->kwargannotation, names))
1388 goto error;
1389
1390 if (!return_str) {
1391 return_str = PyString_InternFromString("return");
1392 if (!return_str)
1393 goto error;
1394 }
1395 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1396 goto error;
1397 }
1398
1399 len = PyList_GET_SIZE(names);
1400 if (len) {
1401 /* convert names to a tuple and place on stack */
1402 PyObject *elt;
1403 int i;
1404 PyObject *s = PyTuple_New(len);
1405 if (!s)
1406 goto error;
1407 for (i = 0; i < len; i++) {
1408 elt = PyList_GET_ITEM(names, i);
1409 Py_INCREF(elt);
1410 PyTuple_SET_ITEM(s, i, elt);
1411 }
1412 ADDOP_O(c, LOAD_CONST, s, consts);
1413 Py_DECREF(s);
1414 len++; /* include the just-pushed tuple */
1415 }
1416 Py_DECREF(names);
1417 return len;
1418
1419error:
1420 Py_DECREF(names);
1421 return -1;
1422}
1423
1424static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425compiler_function(struct compiler *c, stmt_ty s)
1426{
1427 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001428 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001430 expr_ty returns = s->v.FunctionDef.returns;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001432 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001433 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001434 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435
1436 assert(s->kind == FunctionDef_kind);
1437
1438 if (!compiler_decorators(c, decos))
1439 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001440 if (args->kwonlyargs) {
1441 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1442 args->kw_defaults);
1443 if (res < 0)
1444 return 0;
1445 kw_default_count = res;
1446 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 if (args->defaults)
1448 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001449 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1452 s->lineno))
1453 return 0;
1454
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001455 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001456 docstring = compiler_isdocstring(st);
1457 if (docstring)
1458 first_const = st->v.Expr.value->v.Str.s;
1459 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001460 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001461 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001462 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001464 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465 compiler_arguments(c, args);
1466
1467 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001468 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001470 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001472 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1473 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474 }
1475 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001476 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001477 if (co == NULL)
1478 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479
Guido van Rossum4f72a782006-10-27 23:31:49 +00001480 arglength = asdl_seq_LEN(args->defaults);
1481 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001482 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001483 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001484 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485
Neal Norwitzc1505362006-12-28 06:47:50 +00001486 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001487 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1488 ADDOP_I(c, CALL_FUNCTION, 1);
1489 }
1490
1491 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1492}
1493
1494static int
1495compiler_class(struct compiler *c, stmt_ty s)
1496{
1497 int n;
1498 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001499 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500 /* push class name on stack, needed by BUILD_CLASS */
1501 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1502 /* push the tuple of base classes on the stack */
1503 n = asdl_seq_LEN(s->v.ClassDef.bases);
1504 if (n > 0)
1505 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1506 ADDOP_I(c, BUILD_TUPLE, n);
1507 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1508 s->lineno))
1509 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001510 c->u->u_private = s->v.ClassDef.name;
1511 Py_INCREF(c->u->u_private);
1512 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513 if (!str || !compiler_nameop(c, str, Load)) {
1514 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001515 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001517 }
1518
1519 Py_DECREF(str);
1520 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521 if (!str || !compiler_nameop(c, str, Store)) {
1522 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001523 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001525 }
1526 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001528 if (!compiler_body(c, s->v.ClassDef.body)) {
1529 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001533 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1534 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001536 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537 if (co == NULL)
1538 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001540 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001541 Py_DECREF(co);
1542
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001543 ADDOP_I(c, CALL_FUNCTION, 0);
1544 ADDOP(c, BUILD_CLASS);
1545 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1546 return 0;
1547 return 1;
1548}
1549
1550static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001551compiler_ifexp(struct compiler *c, expr_ty e)
1552{
1553 basicblock *end, *next;
1554
1555 assert(e->kind == IfExp_kind);
1556 end = compiler_new_block(c);
1557 if (end == NULL)
1558 return 0;
1559 next = compiler_new_block(c);
1560 if (next == NULL)
1561 return 0;
1562 VISIT(c, expr, e->v.IfExp.test);
1563 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1564 ADDOP(c, POP_TOP);
1565 VISIT(c, expr, e->v.IfExp.body);
1566 ADDOP_JREL(c, JUMP_FORWARD, end);
1567 compiler_use_next_block(c, next);
1568 ADDOP(c, POP_TOP);
1569 VISIT(c, expr, e->v.IfExp.orelse);
1570 compiler_use_next_block(c, end);
1571 return 1;
1572}
1573
1574static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575compiler_lambda(struct compiler *c, expr_ty e)
1576{
1577 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001578 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001579 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580 arguments_ty args = e->v.Lambda.args;
1581 assert(e->kind == Lambda_kind);
1582
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001583 if (!name) {
1584 name = PyString_InternFromString("<lambda>");
1585 if (!name)
1586 return 0;
1587 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588
Guido van Rossum4f72a782006-10-27 23:31:49 +00001589 if (args->kwonlyargs) {
1590 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1591 args->kw_defaults);
1592 if (res < 0) return 0;
1593 kw_default_count = res;
1594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595 if (args->defaults)
1596 VISIT_SEQ(c, expr, args->defaults);
1597 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1598 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001599
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001600 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601 compiler_arguments(c, args);
1602
1603 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001604 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001605 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1606 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001607 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001608 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001609 if (co == NULL)
1610 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611
Guido van Rossum4f72a782006-10-27 23:31:49 +00001612 arglength = asdl_seq_LEN(args->defaults);
1613 arglength |= kw_default_count << 8;
1614 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001615 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616
1617 return 1;
1618}
1619
1620static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621compiler_if(struct compiler *c, stmt_ty s)
1622{
1623 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001624 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001625 assert(s->kind == If_kind);
1626 end = compiler_new_block(c);
1627 if (end == NULL)
1628 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001629 next = compiler_new_block(c);
1630 if (next == NULL)
1631 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001632
1633 constant = expr_constant(s->v.If.test);
1634 /* constant = 0: "if 0"
1635 * constant = 1: "if 1", "if 2", ...
1636 * constant = -1: rest */
1637 if (constant == 0) {
1638 if (s->v.If.orelse)
1639 VISIT_SEQ(c, stmt, s->v.If.orelse);
1640 } else if (constant == 1) {
1641 VISIT_SEQ(c, stmt, s->v.If.body);
1642 } else {
1643 VISIT(c, expr, s->v.If.test);
1644 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1645 ADDOP(c, POP_TOP);
1646 VISIT_SEQ(c, stmt, s->v.If.body);
1647 ADDOP_JREL(c, JUMP_FORWARD, end);
1648 compiler_use_next_block(c, next);
1649 ADDOP(c, POP_TOP);
1650 if (s->v.If.orelse)
1651 VISIT_SEQ(c, stmt, s->v.If.orelse);
1652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653 compiler_use_next_block(c, end);
1654 return 1;
1655}
1656
1657static int
1658compiler_for(struct compiler *c, stmt_ty s)
1659{
1660 basicblock *start, *cleanup, *end;
1661
1662 start = compiler_new_block(c);
1663 cleanup = compiler_new_block(c);
1664 end = compiler_new_block(c);
1665 if (start == NULL || end == NULL || cleanup == NULL)
1666 return 0;
1667 ADDOP_JREL(c, SETUP_LOOP, end);
1668 if (!compiler_push_fblock(c, LOOP, start))
1669 return 0;
1670 VISIT(c, expr, s->v.For.iter);
1671 ADDOP(c, GET_ITER);
1672 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001673 /* XXX(nnorwitz): is there a better way to handle this?
1674 for loops are special, we want to be able to trace them
1675 each time around, so we need to set an extra line number. */
1676 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 ADDOP_JREL(c, FOR_ITER, cleanup);
1678 VISIT(c, expr, s->v.For.target);
1679 VISIT_SEQ(c, stmt, s->v.For.body);
1680 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1681 compiler_use_next_block(c, cleanup);
1682 ADDOP(c, POP_BLOCK);
1683 compiler_pop_fblock(c, LOOP, start);
1684 VISIT_SEQ(c, stmt, s->v.For.orelse);
1685 compiler_use_next_block(c, end);
1686 return 1;
1687}
1688
1689static int
1690compiler_while(struct compiler *c, stmt_ty s)
1691{
1692 basicblock *loop, *orelse, *end, *anchor = NULL;
1693 int constant = expr_constant(s->v.While.test);
1694
1695 if (constant == 0)
1696 return 1;
1697 loop = compiler_new_block(c);
1698 end = compiler_new_block(c);
1699 if (constant == -1) {
1700 anchor = compiler_new_block(c);
1701 if (anchor == NULL)
1702 return 0;
1703 }
1704 if (loop == NULL || end == NULL)
1705 return 0;
1706 if (s->v.While.orelse) {
1707 orelse = compiler_new_block(c);
1708 if (orelse == NULL)
1709 return 0;
1710 }
1711 else
1712 orelse = NULL;
1713
1714 ADDOP_JREL(c, SETUP_LOOP, end);
1715 compiler_use_next_block(c, loop);
1716 if (!compiler_push_fblock(c, LOOP, loop))
1717 return 0;
1718 if (constant == -1) {
1719 VISIT(c, expr, s->v.While.test);
1720 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1721 ADDOP(c, POP_TOP);
1722 }
1723 VISIT_SEQ(c, stmt, s->v.While.body);
1724 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1725
1726 /* XXX should the two POP instructions be in a separate block
1727 if there is no else clause ?
1728 */
1729
1730 if (constant == -1) {
1731 compiler_use_next_block(c, anchor);
1732 ADDOP(c, POP_TOP);
1733 ADDOP(c, POP_BLOCK);
1734 }
1735 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001736 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 VISIT_SEQ(c, stmt, s->v.While.orelse);
1738 compiler_use_next_block(c, end);
1739
1740 return 1;
1741}
1742
1743static int
1744compiler_continue(struct compiler *c)
1745{
1746 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001747 static const char IN_FINALLY_ERROR_MSG[] =
1748 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001749 int i;
1750
1751 if (!c->u->u_nfblocks)
1752 return compiler_error(c, LOOP_ERROR_MSG);
1753 i = c->u->u_nfblocks - 1;
1754 switch (c->u->u_fblock[i].fb_type) {
1755 case LOOP:
1756 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1757 break;
1758 case EXCEPT:
1759 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001760 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1761 /* Prevent continue anywhere under a finally
1762 even if hidden in a sub-try or except. */
1763 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1764 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 if (i == -1)
1767 return compiler_error(c, LOOP_ERROR_MSG);
1768 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1769 break;
1770 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001771 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 }
1773
1774 return 1;
1775}
1776
1777/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1778
1779 SETUP_FINALLY L
1780 <code for body>
1781 POP_BLOCK
1782 LOAD_CONST <None>
1783 L: <code for finalbody>
1784 END_FINALLY
1785
1786 The special instructions use the block stack. Each block
1787 stack entry contains the instruction that created it (here
1788 SETUP_FINALLY), the level of the value stack at the time the
1789 block stack entry was created, and a label (here L).
1790
1791 SETUP_FINALLY:
1792 Pushes the current value stack level and the label
1793 onto the block stack.
1794 POP_BLOCK:
1795 Pops en entry from the block stack, and pops the value
1796 stack until its level is the same as indicated on the
1797 block stack. (The label is ignored.)
1798 END_FINALLY:
1799 Pops a variable number of entries from the *value* stack
1800 and re-raises the exception they specify. The number of
1801 entries popped depends on the (pseudo) exception type.
1802
1803 The block stack is unwound when an exception is raised:
1804 when a SETUP_FINALLY entry is found, the exception is pushed
1805 onto the value stack (and the exception condition is cleared),
1806 and the interpreter jumps to the label gotten from the block
1807 stack.
1808*/
1809
1810static int
1811compiler_try_finally(struct compiler *c, stmt_ty s)
1812{
1813 basicblock *body, *end;
1814 body = compiler_new_block(c);
1815 end = compiler_new_block(c);
1816 if (body == NULL || end == NULL)
1817 return 0;
1818
1819 ADDOP_JREL(c, SETUP_FINALLY, end);
1820 compiler_use_next_block(c, body);
1821 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1822 return 0;
1823 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1824 ADDOP(c, POP_BLOCK);
1825 compiler_pop_fblock(c, FINALLY_TRY, body);
1826
1827 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1828 compiler_use_next_block(c, end);
1829 if (!compiler_push_fblock(c, FINALLY_END, end))
1830 return 0;
1831 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1832 ADDOP(c, END_FINALLY);
1833 compiler_pop_fblock(c, FINALLY_END, end);
1834
1835 return 1;
1836}
1837
1838/*
1839 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1840 (The contents of the value stack is shown in [], with the top
1841 at the right; 'tb' is trace-back info, 'val' the exception's
1842 associated value, and 'exc' the exception.)
1843
1844 Value stack Label Instruction Argument
1845 [] SETUP_EXCEPT L1
1846 [] <code for S>
1847 [] POP_BLOCK
1848 [] JUMP_FORWARD L0
1849
1850 [tb, val, exc] L1: DUP )
1851 [tb, val, exc, exc] <evaluate E1> )
1852 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1853 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1854 [tb, val, exc, 1] POP )
1855 [tb, val, exc] POP
1856 [tb, val] <assign to V1> (or POP if no V1)
1857 [tb] POP
1858 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001859 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860
1861 [tb, val, exc, 0] L2: POP
1862 [tb, val, exc] DUP
1863 .............................etc.......................
1864
1865 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001866 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867
1868 [] L0: <next statement>
1869
1870 Of course, parts are not generated if Vi or Ei is not present.
1871*/
1872static int
1873compiler_try_except(struct compiler *c, stmt_ty s)
1874{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001875 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 int i, n;
1877
1878 body = compiler_new_block(c);
1879 except = compiler_new_block(c);
1880 orelse = compiler_new_block(c);
1881 end = compiler_new_block(c);
1882 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1883 return 0;
1884 ADDOP_JREL(c, SETUP_EXCEPT, except);
1885 compiler_use_next_block(c, body);
1886 if (!compiler_push_fblock(c, EXCEPT, body))
1887 return 0;
1888 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1889 ADDOP(c, POP_BLOCK);
1890 compiler_pop_fblock(c, EXCEPT, body);
1891 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1892 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1893 compiler_use_next_block(c, except);
1894 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001895 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896 s->v.TryExcept.handlers, i);
1897 if (!handler->type && i < n-1)
1898 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001899 c->u->u_lineno_set = false;
1900 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901 except = compiler_new_block(c);
1902 if (except == NULL)
1903 return 0;
1904 if (handler->type) {
1905 ADDOP(c, DUP_TOP);
1906 VISIT(c, expr, handler->type);
1907 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1908 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1909 ADDOP(c, POP_TOP);
1910 }
1911 ADDOP(c, POP_TOP);
1912 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001913 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001914
1915 cleanup_end = compiler_new_block(c);
1916 cleanup_body = compiler_new_block(c);
1917 if(!(cleanup_end || cleanup_body))
1918 return 0;
1919
Guido van Rossum16be03e2007-01-10 18:51:35 +00001920 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001921 ADDOP(c, POP_TOP);
1922
1923 /*
1924 try:
1925 # body
1926 except type as name:
1927 try:
1928 # body
1929 finally:
1930 name = None
1931 del name
1932 */
1933
1934 /* second try: */
1935 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1936 compiler_use_next_block(c, cleanup_body);
1937 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1938 return 0;
1939
1940 /* second # body */
1941 VISIT_SEQ(c, stmt, handler->body);
1942 ADDOP(c, POP_BLOCK);
1943 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
1944
1945 /* finally: */
1946 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1947 compiler_use_next_block(c, cleanup_end);
1948 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
1949 return 0;
1950
1951 /* name = None */
1952 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00001953 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001954
Guido van Rossum16be03e2007-01-10 18:51:35 +00001955 /* del name */
1956 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00001957
1958 ADDOP(c, END_FINALLY);
1959 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 }
1961 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00001962 ADDOP(c, POP_TOP);
1963 ADDOP(c, POP_TOP);
1964 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 ADDOP_JREL(c, JUMP_FORWARD, end);
1967 compiler_use_next_block(c, except);
1968 if (handler->type)
1969 ADDOP(c, POP_TOP);
1970 }
1971 ADDOP(c, END_FINALLY);
1972 compiler_use_next_block(c, orelse);
1973 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1974 compiler_use_next_block(c, end);
1975 return 1;
1976}
1977
1978static int
1979compiler_import_as(struct compiler *c, identifier name, identifier asname)
1980{
1981 /* The IMPORT_NAME opcode was already generated. This function
1982 merely needs to bind the result to a name.
1983
1984 If there is a dot in name, we need to split it and emit a
1985 LOAD_ATTR for each name.
1986 */
1987 const char *src = PyString_AS_STRING(name);
1988 const char *dot = strchr(src, '.');
1989 if (dot) {
1990 /* Consume the base module name to get the first attribute */
1991 src = dot + 1;
1992 while (dot) {
1993 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001994 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001996 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001998 if (!attr)
1999 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002001 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 src = dot + 1;
2003 }
2004 }
2005 return compiler_nameop(c, asname, Store);
2006}
2007
2008static int
2009compiler_import(struct compiler *c, stmt_ty s)
2010{
2011 /* The Import node stores a module name like a.b.c as a single
2012 string. This is convenient for all cases except
2013 import a.b.c as d
2014 where we need to parse that string to extract the individual
2015 module names.
2016 XXX Perhaps change the representation to make this case simpler?
2017 */
2018 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002021 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002023 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024
Guido van Rossum45aecf42006-03-15 04:58:47 +00002025 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002026 if (level == NULL)
2027 return 0;
2028
2029 ADDOP_O(c, LOAD_CONST, level, consts);
2030 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2032 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2033
2034 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002035 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002036 if (!r)
2037 return r;
2038 }
2039 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 identifier tmp = alias->name;
2041 const char *base = PyString_AS_STRING(alias->name);
2042 char *dot = strchr(base, '.');
2043 if (dot)
2044 tmp = PyString_FromStringAndSize(base,
2045 dot - base);
2046 r = compiler_nameop(c, tmp, Store);
2047 if (dot) {
2048 Py_DECREF(tmp);
2049 }
2050 if (!r)
2051 return r;
2052 }
2053 }
2054 return 1;
2055}
2056
2057static int
2058compiler_from_import(struct compiler *c, stmt_ty s)
2059{
2060 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061
2062 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002063 PyObject *level;
2064
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 if (!names)
2066 return 0;
2067
Guido van Rossum45aecf42006-03-15 04:58:47 +00002068 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002069 if (!level) {
2070 Py_DECREF(names);
2071 return 0;
2072 }
2073
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074 /* build up the names */
2075 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002076 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 Py_INCREF(alias->name);
2078 PyTuple_SET_ITEM(names, i, alias->name);
2079 }
2080
2081 if (s->lineno > c->c_future->ff_lineno) {
2082 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2083 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002084 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 Py_DECREF(names);
2086 return compiler_error(c,
2087 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089
2090 }
2091 }
2092
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002093 ADDOP_O(c, LOAD_CONST, level, consts);
2094 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002096 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2098 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002099 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 identifier store_name;
2101
2102 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2103 assert(n == 1);
2104 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 }
2107
2108 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2109 store_name = alias->name;
2110 if (alias->asname)
2111 store_name = alias->asname;
2112
2113 if (!compiler_nameop(c, store_name, Store)) {
2114 Py_DECREF(names);
2115 return 0;
2116 }
2117 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002118 /* remove imported module */
2119 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120 return 1;
2121}
2122
2123static int
2124compiler_assert(struct compiler *c, stmt_ty s)
2125{
2126 static PyObject *assertion_error = NULL;
2127 basicblock *end;
2128
2129 if (Py_OptimizeFlag)
2130 return 1;
2131 if (assertion_error == NULL) {
2132 assertion_error = PyString_FromString("AssertionError");
2133 if (assertion_error == NULL)
2134 return 0;
2135 }
2136 VISIT(c, expr, s->v.Assert.test);
2137 end = compiler_new_block(c);
2138 if (end == NULL)
2139 return 0;
2140 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2141 ADDOP(c, POP_TOP);
2142 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2143 if (s->v.Assert.msg) {
2144 VISIT(c, expr, s->v.Assert.msg);
2145 ADDOP_I(c, RAISE_VARARGS, 2);
2146 }
2147 else {
2148 ADDOP_I(c, RAISE_VARARGS, 1);
2149 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002150 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 ADDOP(c, POP_TOP);
2152 return 1;
2153}
2154
2155static int
2156compiler_visit_stmt(struct compiler *c, stmt_ty s)
2157{
2158 int i, n;
2159
Thomas Wouters89f507f2006-12-13 04:49:30 +00002160 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 c->u->u_lineno = s->lineno;
2162 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002165 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002167 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002168 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002169 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002170 if (c->u->u_ste->ste_type != FunctionBlock)
2171 return compiler_error(c, "'return' outside function");
2172 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173 VISIT(c, expr, s->v.Return.value);
2174 }
2175 else
2176 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2177 ADDOP(c, RETURN_VALUE);
2178 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002179 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002180 VISIT_SEQ(c, expr, s->v.Delete.targets)
2181 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002182 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 n = asdl_seq_LEN(s->v.Assign.targets);
2184 VISIT(c, expr, s->v.Assign.value);
2185 for (i = 0; i < n; i++) {
2186 if (i < n - 1)
2187 ADDOP(c, DUP_TOP);
2188 VISIT(c, expr,
2189 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2190 }
2191 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002192 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002193 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002196 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002198 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002200 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201 n = 0;
2202 if (s->v.Raise.type) {
2203 VISIT(c, expr, s->v.Raise.type);
2204 n++;
2205 if (s->v.Raise.inst) {
2206 VISIT(c, expr, s->v.Raise.inst);
2207 n++;
2208 if (s->v.Raise.tback) {
2209 VISIT(c, expr, s->v.Raise.tback);
2210 n++;
2211 }
2212 }
2213 }
2214 ADDOP_I(c, RAISE_VARARGS, n);
2215 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002216 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002218 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002219 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002220 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002222 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002223 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002224 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002225 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002226 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002228 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002230 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002231 ADDOP(c, PRINT_EXPR);
2232 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002233 else if (s->v.Expr.value->kind != Str_kind &&
2234 s->v.Expr.value->kind != Num_kind) {
2235 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236 ADDOP(c, POP_TOP);
2237 }
2238 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002239 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Break_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002242 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243 return compiler_error(c, "'break' outside loop");
2244 ADDOP(c, BREAK_LOOP);
2245 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002246 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002248 case With_kind:
2249 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250 }
2251 return 1;
2252}
2253
2254static int
2255unaryop(unaryop_ty op)
2256{
2257 switch (op) {
2258 case Invert:
2259 return UNARY_INVERT;
2260 case Not:
2261 return UNARY_NOT;
2262 case UAdd:
2263 return UNARY_POSITIVE;
2264 case USub:
2265 return UNARY_NEGATIVE;
2266 }
2267 return 0;
2268}
2269
2270static int
2271binop(struct compiler *c, operator_ty op)
2272{
2273 switch (op) {
2274 case Add:
2275 return BINARY_ADD;
2276 case Sub:
2277 return BINARY_SUBTRACT;
2278 case Mult:
2279 return BINARY_MULTIPLY;
2280 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002281 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 case Mod:
2283 return BINARY_MODULO;
2284 case Pow:
2285 return BINARY_POWER;
2286 case LShift:
2287 return BINARY_LSHIFT;
2288 case RShift:
2289 return BINARY_RSHIFT;
2290 case BitOr:
2291 return BINARY_OR;
2292 case BitXor:
2293 return BINARY_XOR;
2294 case BitAnd:
2295 return BINARY_AND;
2296 case FloorDiv:
2297 return BINARY_FLOOR_DIVIDE;
2298 }
2299 return 0;
2300}
2301
2302static int
2303cmpop(cmpop_ty op)
2304{
2305 switch (op) {
2306 case Eq:
2307 return PyCmp_EQ;
2308 case NotEq:
2309 return PyCmp_NE;
2310 case Lt:
2311 return PyCmp_LT;
2312 case LtE:
2313 return PyCmp_LE;
2314 case Gt:
2315 return PyCmp_GT;
2316 case GtE:
2317 return PyCmp_GE;
2318 case Is:
2319 return PyCmp_IS;
2320 case IsNot:
2321 return PyCmp_IS_NOT;
2322 case In:
2323 return PyCmp_IN;
2324 case NotIn:
2325 return PyCmp_NOT_IN;
2326 }
2327 return PyCmp_BAD;
2328}
2329
2330static int
2331inplace_binop(struct compiler *c, operator_ty op)
2332{
2333 switch (op) {
2334 case Add:
2335 return INPLACE_ADD;
2336 case Sub:
2337 return INPLACE_SUBTRACT;
2338 case Mult:
2339 return INPLACE_MULTIPLY;
2340 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002341 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342 case Mod:
2343 return INPLACE_MODULO;
2344 case Pow:
2345 return INPLACE_POWER;
2346 case LShift:
2347 return INPLACE_LSHIFT;
2348 case RShift:
2349 return INPLACE_RSHIFT;
2350 case BitOr:
2351 return INPLACE_OR;
2352 case BitXor:
2353 return INPLACE_XOR;
2354 case BitAnd:
2355 return INPLACE_AND;
2356 case FloorDiv:
2357 return INPLACE_FLOOR_DIVIDE;
2358 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002359 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002360 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361 return 0;
2362}
2363
2364static int
2365compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2366{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002367 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2369
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002370 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002371 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 /* XXX AugStore isn't used anywhere! */
2373
2374 /* First check for assignment to __debug__. Param? */
2375 if ((ctx == Store || ctx == AugStore || ctx == Del)
2376 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2377 return compiler_error(c, "can not assign to __debug__");
2378 }
2379
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002380 mangled = _Py_Mangle(c->u->u_private, name);
2381 if (!mangled)
2382 return 0;
2383
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384 op = 0;
2385 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002386 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 switch (scope) {
2388 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002389 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390 optype = OP_DEREF;
2391 break;
2392 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002393 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002394 optype = OP_DEREF;
2395 break;
2396 case LOCAL:
2397 if (c->u->u_ste->ste_type == FunctionBlock)
2398 optype = OP_FAST;
2399 break;
2400 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002401 if (c->u->u_ste->ste_type == FunctionBlock &&
2402 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403 optype = OP_GLOBAL;
2404 break;
2405 case GLOBAL_EXPLICIT:
2406 optype = OP_GLOBAL;
2407 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002408 default:
2409 /* scope can be 0 */
2410 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 }
2412
2413 /* XXX Leave assert here, but handle __doc__ and the like better */
2414 assert(scope || PyString_AS_STRING(name)[0] == '_');
2415
2416 switch (optype) {
2417 case OP_DEREF:
2418 switch (ctx) {
2419 case Load: op = LOAD_DEREF; break;
2420 case Store: op = STORE_DEREF; break;
2421 case AugLoad:
2422 case AugStore:
2423 break;
2424 case Del:
2425 PyErr_Format(PyExc_SyntaxError,
2426 "can not delete variable '%s' referenced "
2427 "in nested scope",
2428 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002429 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002430 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002432 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002433 PyErr_SetString(PyExc_SystemError,
2434 "param invalid for deref variable");
2435 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 }
2437 break;
2438 case OP_FAST:
2439 switch (ctx) {
2440 case Load: op = LOAD_FAST; break;
2441 case Store: op = STORE_FAST; break;
2442 case Del: op = DELETE_FAST; break;
2443 case AugLoad:
2444 case AugStore:
2445 break;
2446 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002447 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002448 PyErr_SetString(PyExc_SystemError,
2449 "param invalid for local variable");
2450 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002452 ADDOP_O(c, op, mangled, varnames);
2453 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 return 1;
2455 case OP_GLOBAL:
2456 switch (ctx) {
2457 case Load: op = LOAD_GLOBAL; break;
2458 case Store: op = STORE_GLOBAL; break;
2459 case Del: op = DELETE_GLOBAL; break;
2460 case AugLoad:
2461 case AugStore:
2462 break;
2463 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002464 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002465 PyErr_SetString(PyExc_SystemError,
2466 "param invalid for global variable");
2467 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 }
2469 break;
2470 case OP_NAME:
2471 switch (ctx) {
2472 case Load: op = LOAD_NAME; break;
2473 case Store: op = STORE_NAME; break;
2474 case Del: op = DELETE_NAME; break;
2475 case AugLoad:
2476 case AugStore:
2477 break;
2478 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002479 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002480 PyErr_SetString(PyExc_SystemError,
2481 "param invalid for name variable");
2482 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 }
2484 break;
2485 }
2486
2487 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002488 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002489 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002490 if (arg < 0)
2491 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002492 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493}
2494
2495static int
2496compiler_boolop(struct compiler *c, expr_ty e)
2497{
2498 basicblock *end;
2499 int jumpi, i, n;
2500 asdl_seq *s;
2501
2502 assert(e->kind == BoolOp_kind);
2503 if (e->v.BoolOp.op == And)
2504 jumpi = JUMP_IF_FALSE;
2505 else
2506 jumpi = JUMP_IF_TRUE;
2507 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002508 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 return 0;
2510 s = e->v.BoolOp.values;
2511 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002512 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002514 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002515 ADDOP_JREL(c, jumpi, end);
2516 ADDOP(c, POP_TOP)
2517 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002518 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 compiler_use_next_block(c, end);
2520 return 1;
2521}
2522
2523static int
2524compiler_list(struct compiler *c, expr_ty e)
2525{
2526 int n = asdl_seq_LEN(e->v.List.elts);
2527 if (e->v.List.ctx == Store) {
2528 ADDOP_I(c, UNPACK_SEQUENCE, n);
2529 }
2530 VISIT_SEQ(c, expr, e->v.List.elts);
2531 if (e->v.List.ctx == Load) {
2532 ADDOP_I(c, BUILD_LIST, n);
2533 }
2534 return 1;
2535}
2536
2537static int
2538compiler_tuple(struct compiler *c, expr_ty e)
2539{
2540 int n = asdl_seq_LEN(e->v.Tuple.elts);
2541 if (e->v.Tuple.ctx == Store) {
2542 ADDOP_I(c, UNPACK_SEQUENCE, n);
2543 }
2544 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2545 if (e->v.Tuple.ctx == Load) {
2546 ADDOP_I(c, BUILD_TUPLE, n);
2547 }
2548 return 1;
2549}
2550
2551static int
2552compiler_compare(struct compiler *c, expr_ty e)
2553{
2554 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556
2557 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2558 VISIT(c, expr, e->v.Compare.left);
2559 n = asdl_seq_LEN(e->v.Compare.ops);
2560 assert(n > 0);
2561 if (n > 1) {
2562 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002563 if (cleanup == NULL)
2564 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002565 VISIT(c, expr,
2566 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 }
2568 for (i = 1; i < n; i++) {
2569 ADDOP(c, DUP_TOP);
2570 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002572 cmpop((cmpop_ty)(asdl_seq_GET(
2573 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2575 NEXT_BLOCK(c);
2576 ADDOP(c, POP_TOP);
2577 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002578 VISIT(c, expr,
2579 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002581 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002583 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 if (n > 1) {
2585 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002586 if (end == NULL)
2587 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 ADDOP_JREL(c, JUMP_FORWARD, end);
2589 compiler_use_next_block(c, cleanup);
2590 ADDOP(c, ROT_TWO);
2591 ADDOP(c, POP_TOP);
2592 compiler_use_next_block(c, end);
2593 }
2594 return 1;
2595}
2596
2597static int
2598compiler_call(struct compiler *c, expr_ty e)
2599{
2600 int n, code = 0;
2601
2602 VISIT(c, expr, e->v.Call.func);
2603 n = asdl_seq_LEN(e->v.Call.args);
2604 VISIT_SEQ(c, expr, e->v.Call.args);
2605 if (e->v.Call.keywords) {
2606 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2607 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2608 }
2609 if (e->v.Call.starargs) {
2610 VISIT(c, expr, e->v.Call.starargs);
2611 code |= 1;
2612 }
2613 if (e->v.Call.kwargs) {
2614 VISIT(c, expr, e->v.Call.kwargs);
2615 code |= 2;
2616 }
2617 switch (code) {
2618 case 0:
2619 ADDOP_I(c, CALL_FUNCTION, n);
2620 break;
2621 case 1:
2622 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2623 break;
2624 case 2:
2625 ADDOP_I(c, CALL_FUNCTION_KW, n);
2626 break;
2627 case 3:
2628 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2629 break;
2630 }
2631 return 1;
2632}
2633
2634static int
2635compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 asdl_seq *generators, int gen_index,
2637 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638{
2639 /* generate code for the iterator, then each of the ifs,
2640 and then write to the element */
2641
2642 comprehension_ty l;
2643 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645
2646 start = compiler_new_block(c);
2647 skip = compiler_new_block(c);
2648 if_cleanup = compiler_new_block(c);
2649 anchor = compiler_new_block(c);
2650
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2652 anchor == NULL)
2653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002655 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 VISIT(c, expr, l->iter);
2657 ADDOP(c, GET_ITER);
2658 compiler_use_next_block(c, start);
2659 ADDOP_JREL(c, FOR_ITER, anchor);
2660 NEXT_BLOCK(c);
2661 VISIT(c, expr, l->target);
2662
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 n = asdl_seq_LEN(l->ifs);
2665 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667 VISIT(c, expr, e);
2668 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2669 NEXT_BLOCK(c);
2670 ADDOP(c, POP_TOP);
2671 }
2672
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 if (++gen_index < asdl_seq_LEN(generators))
2674 if (!compiler_listcomp_generator(c, tmpname,
2675 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 /* only append after the last for generator */
2679 if (gen_index >= asdl_seq_LEN(generators)) {
2680 if (!compiler_nameop(c, tmpname, Load))
2681 return 0;
2682 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002683 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002684
2685 compiler_use_next_block(c, skip);
2686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 for (i = 0; i < n; i++) {
2688 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 if (i == 0)
2690 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 ADDOP(c, POP_TOP);
2692 }
2693 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2694 compiler_use_next_block(c, anchor);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002695 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 return 0;
2699
2700 return 1;
2701}
2702
2703static int
2704compiler_listcomp(struct compiler *c, expr_ty e)
2705{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002707 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 asdl_seq *generators = e->v.ListComp.generators;
2709
2710 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002711 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 if (!tmp)
2713 return 0;
2714 ADDOP_I(c, BUILD_LIST, 0);
2715 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2718 e->v.ListComp.elt);
2719 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 return rc;
2721}
2722
2723static int
2724compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002725 asdl_seq *generators, int gen_index,
2726 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727{
2728 /* generate code for the iterator, then each of the ifs,
2729 and then write to the element */
2730
2731 comprehension_ty ge;
2732 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002733 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734
2735 start = compiler_new_block(c);
2736 skip = compiler_new_block(c);
2737 if_cleanup = compiler_new_block(c);
2738 anchor = compiler_new_block(c);
2739 end = compiler_new_block(c);
2740
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002741 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742 anchor == NULL || end == NULL)
2743 return 0;
2744
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002745 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746 ADDOP_JREL(c, SETUP_LOOP, end);
2747 if (!compiler_push_fblock(c, LOOP, start))
2748 return 0;
2749
2750 if (gen_index == 0) {
2751 /* Receive outermost iter as an implicit argument */
2752 c->u->u_argcount = 1;
2753 ADDOP_I(c, LOAD_FAST, 0);
2754 }
2755 else {
2756 /* Sub-iter - calculate on the fly */
2757 VISIT(c, expr, ge->iter);
2758 ADDOP(c, GET_ITER);
2759 }
2760 compiler_use_next_block(c, start);
2761 ADDOP_JREL(c, FOR_ITER, anchor);
2762 NEXT_BLOCK(c);
2763 VISIT(c, expr, ge->target);
2764
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002765 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766 n = asdl_seq_LEN(ge->ifs);
2767 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002768 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769 VISIT(c, expr, e);
2770 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2771 NEXT_BLOCK(c);
2772 ADDOP(c, POP_TOP);
2773 }
2774
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002775 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2777 return 0;
2778
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002779 /* only append after the last 'for' generator */
2780 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781 VISIT(c, expr, elt);
2782 ADDOP(c, YIELD_VALUE);
2783 ADDOP(c, POP_TOP);
2784
2785 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002786 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002787 for (i = 0; i < n; i++) {
2788 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002789 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790 compiler_use_next_block(c, if_cleanup);
2791
2792 ADDOP(c, POP_TOP);
2793 }
2794 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2795 compiler_use_next_block(c, anchor);
2796 ADDOP(c, POP_BLOCK);
2797 compiler_pop_fblock(c, LOOP, start);
2798 compiler_use_next_block(c, end);
2799
2800 return 1;
2801}
2802
2803static int
2804compiler_genexp(struct compiler *c, expr_ty e)
2805{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002806 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807 PyCodeObject *co;
2808 expr_ty outermost_iter = ((comprehension_ty)
2809 (asdl_seq_GET(e->v.GeneratorExp.generators,
2810 0)))->iter;
2811
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002812 if (!name) {
2813 name = PyString_FromString("<genexpr>");
2814 if (!name)
2815 return 0;
2816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817
2818 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2819 return 0;
2820 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2821 e->v.GeneratorExp.elt);
2822 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002823 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 if (co == NULL)
2825 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002826
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002828 Py_DECREF(co);
2829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002830 VISIT(c, expr, outermost_iter);
2831 ADDOP(c, GET_ITER);
2832 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
2834 return 1;
2835}
2836
2837static int
2838compiler_visit_keyword(struct compiler *c, keyword_ty k)
2839{
2840 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2841 VISIT(c, expr, k->value);
2842 return 1;
2843}
2844
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 whether they are true or false.
2847
2848 Return values: 1 for true, 0 for false, -1 for non-constant.
2849 */
2850
2851static int
2852expr_constant(expr_ty e)
2853{
2854 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002855 case Ellipsis_kind:
2856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857 case Num_kind:
2858 return PyObject_IsTrue(e->v.Num.n);
2859 case Str_kind:
2860 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002861 case Name_kind:
2862 /* __debug__ is not assignable, so we can optimize
2863 * it away in if and while statements */
2864 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2865 "__debug__") == 0)
2866 return ! Py_OptimizeFlag;
2867 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868 default:
2869 return -1;
2870 }
2871}
2872
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873/*
2874 Implements the with statement from PEP 343.
2875
2876 The semantics outlined in that PEP are as follows:
2877
2878 with EXPR as VAR:
2879 BLOCK
2880
2881 It is implemented roughly as:
2882
Thomas Wouters477c8d52006-05-27 19:21:47 +00002883 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002884 exit = context.__exit__ # not calling it
2885 value = context.__enter__()
2886 try:
2887 VAR = value # if VAR present in the syntax
2888 BLOCK
2889 finally:
2890 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002891 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002892 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002893 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002894 exit(*exc)
2895 */
2896static int
2897compiler_with(struct compiler *c, stmt_ty s)
2898{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002899 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 basicblock *block, *finally;
2901 identifier tmpexit, tmpvalue = NULL;
2902
2903 assert(s->kind == With_kind);
2904
Guido van Rossumc2e20742006-02-27 22:32:47 +00002905 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 enter_attr = PyString_InternFromString("__enter__");
2907 if (!enter_attr)
2908 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002909 }
2910 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 exit_attr = PyString_InternFromString("__exit__");
2912 if (!exit_attr)
2913 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002914 }
2915
2916 block = compiler_new_block(c);
2917 finally = compiler_new_block(c);
2918 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002919 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002920
2921 /* Create a temporary variable to hold context.__exit__ */
2922 tmpexit = compiler_new_tmpname(c);
2923 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002924 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002925 PyArena_AddPyObject(c->c_arena, tmpexit);
2926
2927 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929 We need to do this rather than preserving it on the stack
2930 because SETUP_FINALLY remembers the stack level.
2931 We need to do the assignment *inside* the try/finally
2932 so that context.__exit__() is called when the assignment
2933 fails. But we need to call context.__enter__() *before*
2934 the try/finally so that if it fails we won't call
2935 context.__exit__().
2936 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002938 if (tmpvalue == NULL)
2939 return 0;
2940 PyArena_AddPyObject(c->c_arena, tmpvalue);
2941 }
2942
Thomas Wouters477c8d52006-05-27 19:21:47 +00002943 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002944 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002945
2946 /* Squirrel away context.__exit__ */
2947 ADDOP(c, DUP_TOP);
2948 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2949 if (!compiler_nameop(c, tmpexit, Store))
2950 return 0;
2951
2952 /* Call context.__enter__() */
2953 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2954 ADDOP_I(c, CALL_FUNCTION, 0);
2955
2956 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 /* Store it in tmpvalue */
2958 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002959 return 0;
2960 }
2961 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002962 /* Discard result from context.__enter__() */
2963 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002964 }
2965
2966 /* Start the try block */
2967 ADDOP_JREL(c, SETUP_FINALLY, finally);
2968
2969 compiler_use_next_block(c, block);
2970 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002971 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002972 }
2973
2974 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002975 /* Bind saved result of context.__enter__() to VAR */
2976 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002977 !compiler_nameop(c, tmpvalue, Del))
2978 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002979 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002980 }
2981
2982 /* BLOCK code */
2983 VISIT_SEQ(c, stmt, s->v.With.body);
2984
2985 /* End of try block; start the finally block */
2986 ADDOP(c, POP_BLOCK);
2987 compiler_pop_fblock(c, FINALLY_TRY, block);
2988
2989 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2990 compiler_use_next_block(c, finally);
2991 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002993
2994 /* Finally block starts; push tmpexit and issue our magic opcode. */
2995 if (!compiler_nameop(c, tmpexit, Load) ||
2996 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002997 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002998 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002999
3000 /* Finally block ends. */
3001 ADDOP(c, END_FINALLY);
3002 compiler_pop_fblock(c, FINALLY_END, finally);
3003 return 1;
3004}
3005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003006static int
3007compiler_visit_expr(struct compiler *c, expr_ty e)
3008{
3009 int i, n;
3010
Thomas Wouters89f507f2006-12-13 04:49:30 +00003011 /* If expr e has a different line number than the last expr/stmt,
3012 set a new line number for the next instruction.
3013 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 if (e->lineno > c->u->u_lineno) {
3015 c->u->u_lineno = e->lineno;
3016 c->u->u_lineno_set = false;
3017 }
3018 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003019 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003021 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 VISIT(c, expr, e->v.BinOp.left);
3023 VISIT(c, expr, e->v.BinOp.right);
3024 ADDOP(c, binop(c, e->v.BinOp.op));
3025 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003026 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 VISIT(c, expr, e->v.UnaryOp.operand);
3028 ADDOP(c, unaryop(e->v.UnaryOp.op));
3029 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003030 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003032 case IfExp_kind:
3033 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003034 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 /* XXX get rid of arg? */
3036 ADDOP_I(c, BUILD_MAP, 0);
3037 n = asdl_seq_LEN(e->v.Dict.values);
3038 /* We must arrange things just right for STORE_SUBSCR.
3039 It wants the stack to look like (value) (dict) (key) */
3040 for (i = 0; i < n; i++) {
3041 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003042 VISIT(c, expr,
3043 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003045 VISIT(c, expr,
3046 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 ADDOP(c, STORE_SUBSCR);
3048 }
3049 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003050 case Set_kind:
3051 n = asdl_seq_LEN(e->v.Set.elts);
3052 VISIT_SEQ(c, expr, e->v.Set.elts);
3053 ADDOP_I(c, BUILD_SET, n);
3054 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003055 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058 return compiler_genexp(c, e);
3059 case Yield_kind:
3060 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003061 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 if (e->v.Yield.value) {
3063 VISIT(c, expr, e->v.Yield.value);
3064 }
3065 else {
3066 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3067 }
3068 ADDOP(c, YIELD_VALUE);
3069 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3076 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003077 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3079 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003080 case Ellipsis_kind:
3081 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3082 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003084 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085 if (e->v.Attribute.ctx != AugStore)
3086 VISIT(c, expr, e->v.Attribute.value);
3087 switch (e->v.Attribute.ctx) {
3088 case AugLoad:
3089 ADDOP(c, DUP_TOP);
3090 /* Fall through to load */
3091 case Load:
3092 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3093 break;
3094 case AugStore:
3095 ADDOP(c, ROT_TWO);
3096 /* Fall through to save */
3097 case Store:
3098 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3099 break;
3100 case Del:
3101 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3102 break;
3103 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003104 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003105 PyErr_SetString(PyExc_SystemError,
3106 "param invalid in attribute expression");
3107 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108 }
3109 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003110 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111 switch (e->v.Subscript.ctx) {
3112 case AugLoad:
3113 VISIT(c, expr, e->v.Subscript.value);
3114 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3115 break;
3116 case Load:
3117 VISIT(c, expr, e->v.Subscript.value);
3118 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3119 break;
3120 case AugStore:
3121 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3122 break;
3123 case Store:
3124 VISIT(c, expr, e->v.Subscript.value);
3125 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3126 break;
3127 case Del:
3128 VISIT(c, expr, e->v.Subscript.value);
3129 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3130 break;
3131 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003132 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003133 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003135 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 }
3137 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003138 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3140 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003141 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 return compiler_tuple(c, e);
3145 }
3146 return 1;
3147}
3148
3149static int
3150compiler_augassign(struct compiler *c, stmt_ty s)
3151{
3152 expr_ty e = s->v.AugAssign.target;
3153 expr_ty auge;
3154
3155 assert(s->kind == AugAssign_kind);
3156
3157 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003158 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003160 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 if (auge == NULL)
3162 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 VISIT(c, expr, auge);
3164 VISIT(c, expr, s->v.AugAssign.value);
3165 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3166 auge->v.Attribute.ctx = AugStore;
3167 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 break;
3169 case Subscript_kind:
3170 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003171 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172 if (auge == NULL)
3173 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003174 VISIT(c, expr, auge);
3175 VISIT(c, expr, s->v.AugAssign.value);
3176 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003181 if (!compiler_nameop(c, e->v.Name.id, Load))
3182 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183 VISIT(c, expr, s->v.AugAssign.value);
3184 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3185 return compiler_nameop(c, e->v.Name.id, Store);
3186 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003187 PyErr_Format(PyExc_SystemError,
3188 "invalid node type (%d) for augmented assignment",
3189 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 }
3192 return 1;
3193}
3194
3195static int
3196compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3197{
3198 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003199 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3200 PyErr_SetString(PyExc_SystemError,
3201 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 f = &c->u->u_fblock[c->u->u_nfblocks++];
3205 f->fb_type = t;
3206 f->fb_block = b;
3207 return 1;
3208}
3209
3210static void
3211compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3212{
3213 struct compiler_unit *u = c->u;
3214 assert(u->u_nfblocks > 0);
3215 u->u_nfblocks--;
3216 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3217 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3218}
3219
Thomas Wouters89f507f2006-12-13 04:49:30 +00003220static int
3221compiler_in_loop(struct compiler *c) {
3222 int i;
3223 struct compiler_unit *u = c->u;
3224 for (i = 0; i < u->u_nfblocks; ++i) {
3225 if (u->u_fblock[i].fb_type == LOOP)
3226 return 1;
3227 }
3228 return 0;
3229}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230/* Raises a SyntaxError and returns 0.
3231 If something goes wrong, a different exception may be raised.
3232*/
3233
3234static int
3235compiler_error(struct compiler *c, const char *errstr)
3236{
3237 PyObject *loc;
3238 PyObject *u = NULL, *v = NULL;
3239
3240 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3241 if (!loc) {
3242 Py_INCREF(Py_None);
3243 loc = Py_None;
3244 }
3245 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3246 Py_None, loc);
3247 if (!u)
3248 goto exit;
3249 v = Py_BuildValue("(zO)", errstr, u);
3250 if (!v)
3251 goto exit;
3252 PyErr_SetObject(PyExc_SyntaxError, v);
3253 exit:
3254 Py_DECREF(loc);
3255 Py_XDECREF(u);
3256 Py_XDECREF(v);
3257 return 0;
3258}
3259
3260static int
3261compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003262 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 /* XXX this code is duplicated */
3267 switch (ctx) {
3268 case AugLoad: /* fall through to Load */
3269 case Load: op = BINARY_SUBSCR; break;
3270 case AugStore:/* fall through to Store */
3271 case Store: op = STORE_SUBSCR; break;
3272 case Del: op = DELETE_SUBSCR; break;
3273 case Param:
3274 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003275 "invalid %s kind %d in subscript\n",
3276 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003277 return 0;
3278 }
3279 if (ctx == AugLoad) {
3280 ADDOP_I(c, DUP_TOPX, 2);
3281 }
3282 else if (ctx == AugStore) {
3283 ADDOP(c, ROT_THREE);
3284 }
3285 ADDOP(c, op);
3286 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287}
3288
3289static int
3290compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3291{
3292 int n = 2;
3293 assert(s->kind == Slice_kind);
3294
3295 /* only handles the cases where BUILD_SLICE is emitted */
3296 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 }
3299 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003300 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003302
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003304 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305 }
3306 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003307 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 }
3309
3310 if (s->v.Slice.step) {
3311 n++;
3312 VISIT(c, expr, s->v.Slice.step);
3313 }
3314 ADDOP_I(c, BUILD_SLICE, n);
3315 return 1;
3316}
3317
3318static int
3319compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3320{
3321 int op = 0, slice_offset = 0, stack_count = 0;
3322
3323 assert(s->v.Slice.step == NULL);
3324 if (s->v.Slice.lower) {
3325 slice_offset++;
3326 stack_count++;
3327 if (ctx != AugStore)
3328 VISIT(c, expr, s->v.Slice.lower);
3329 }
3330 if (s->v.Slice.upper) {
3331 slice_offset += 2;
3332 stack_count++;
3333 if (ctx != AugStore)
3334 VISIT(c, expr, s->v.Slice.upper);
3335 }
3336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003337 if (ctx == AugLoad) {
3338 switch (stack_count) {
3339 case 0: ADDOP(c, DUP_TOP); break;
3340 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3341 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3342 }
3343 }
3344 else if (ctx == AugStore) {
3345 switch (stack_count) {
3346 case 0: ADDOP(c, ROT_TWO); break;
3347 case 1: ADDOP(c, ROT_THREE); break;
3348 case 2: ADDOP(c, ROT_FOUR); break;
3349 }
3350 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351
3352 switch (ctx) {
3353 case AugLoad: /* fall through to Load */
3354 case Load: op = SLICE; break;
3355 case AugStore:/* fall through to Store */
3356 case Store: op = STORE_SLICE; break;
3357 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003358 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003359 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003360 PyErr_SetString(PyExc_SystemError,
3361 "param invalid in simple slice");
3362 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363 }
3364
3365 ADDOP(c, op + slice_offset);
3366 return 1;
3367}
3368
3369static int
3370compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3371 expr_context_ty ctx)
3372{
3373 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003374 case Slice_kind:
3375 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376 case Index_kind:
3377 VISIT(c, expr, s->v.Index.value);
3378 break;
3379 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003380 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003381 PyErr_SetString(PyExc_SystemError,
3382 "extended slice invalid in nested slice");
3383 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 }
3385 return 1;
3386}
3387
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003388static int
3389compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3390{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003391 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003393 case Index_kind:
3394 kindname = "index";
3395 if (ctx != AugStore) {
3396 VISIT(c, expr, s->v.Index.value);
3397 }
3398 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003399 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003400 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401 if (!s->v.Slice.step)
3402 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003403 if (ctx != AugStore) {
3404 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 return 0;
3406 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003407 break;
3408 case ExtSlice_kind:
3409 kindname = "extended slice";
3410 if (ctx != AugStore) {
3411 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3412 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003413 slice_ty sub = (slice_ty)asdl_seq_GET(
3414 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003415 if (!compiler_visit_nested_slice(c, sub, ctx))
3416 return 0;
3417 }
3418 ADDOP_I(c, BUILD_TUPLE, n);
3419 }
3420 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003421 default:
3422 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003423 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003424 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003426 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427}
3428
Thomas Wouters89f507f2006-12-13 04:49:30 +00003429
3430/* End of the compiler section, beginning of the assembler section */
3431
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003432/* do depth-first search of basic block graph, starting with block.
3433 post records the block indices in post-order.
3434
3435 XXX must handle implicit jumps from one block to next
3436*/
3437
Thomas Wouters89f507f2006-12-13 04:49:30 +00003438struct assembler {
3439 PyObject *a_bytecode; /* string containing bytecode */
3440 int a_offset; /* offset into bytecode */
3441 int a_nblocks; /* number of reachable blocks */
3442 basicblock **a_postorder; /* list of blocks in dfs postorder */
3443 PyObject *a_lnotab; /* string containing lnotab */
3444 int a_lnotab_off; /* offset into lnotab */
3445 int a_lineno; /* last lineno of emitted instruction */
3446 int a_lineno_off; /* bytecode offset of last lineno */
3447};
3448
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003449static void
3450dfs(struct compiler *c, basicblock *b, struct assembler *a)
3451{
3452 int i;
3453 struct instr *instr = NULL;
3454
3455 if (b->b_seen)
3456 return;
3457 b->b_seen = 1;
3458 if (b->b_next != NULL)
3459 dfs(c, b->b_next, a);
3460 for (i = 0; i < b->b_iused; i++) {
3461 instr = &b->b_instr[i];
3462 if (instr->i_jrel || instr->i_jabs)
3463 dfs(c, instr->i_target, a);
3464 }
3465 a->a_postorder[a->a_nblocks++] = b;
3466}
3467
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003468static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003469stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3470{
3471 int i;
3472 struct instr *instr;
3473 if (b->b_seen || b->b_startdepth >= depth)
3474 return maxdepth;
3475 b->b_seen = 1;
3476 b->b_startdepth = depth;
3477 for (i = 0; i < b->b_iused; i++) {
3478 instr = &b->b_instr[i];
3479 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3480 if (depth > maxdepth)
3481 maxdepth = depth;
3482 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3483 if (instr->i_jrel || instr->i_jabs) {
3484 maxdepth = stackdepth_walk(c, instr->i_target,
3485 depth, maxdepth);
3486 if (instr->i_opcode == JUMP_ABSOLUTE ||
3487 instr->i_opcode == JUMP_FORWARD) {
3488 goto out; /* remaining code is dead */
3489 }
3490 }
3491 }
3492 if (b->b_next)
3493 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3494out:
3495 b->b_seen = 0;
3496 return maxdepth;
3497}
3498
3499/* Find the flow path that needs the largest stack. We assume that
3500 * cycles in the flow graph have no net effect on the stack depth.
3501 */
3502static int
3503stackdepth(struct compiler *c)
3504{
3505 basicblock *b, *entryblock;
3506 entryblock = NULL;
3507 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3508 b->b_seen = 0;
3509 b->b_startdepth = INT_MIN;
3510 entryblock = b;
3511 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003512 if (!entryblock)
3513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 return stackdepth_walk(c, entryblock, 0, 0);
3515}
3516
3517static int
3518assemble_init(struct assembler *a, int nblocks, int firstlineno)
3519{
3520 memset(a, 0, sizeof(struct assembler));
3521 a->a_lineno = firstlineno;
3522 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3523 if (!a->a_bytecode)
3524 return 0;
3525 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3526 if (!a->a_lnotab)
3527 return 0;
3528 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003529 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003530 if (!a->a_postorder) {
3531 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003533 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 return 1;
3535}
3536
3537static void
3538assemble_free(struct assembler *a)
3539{
3540 Py_XDECREF(a->a_bytecode);
3541 Py_XDECREF(a->a_lnotab);
3542 if (a->a_postorder)
3543 PyObject_Free(a->a_postorder);
3544}
3545
3546/* Return the size of a basic block in bytes. */
3547
3548static int
3549instrsize(struct instr *instr)
3550{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003551 if (!instr->i_hasarg)
3552 return 1;
3553 if (instr->i_oparg > 0xffff)
3554 return 6;
3555 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556}
3557
3558static int
3559blocksize(basicblock *b)
3560{
3561 int i;
3562 int size = 0;
3563
3564 for (i = 0; i < b->b_iused; i++)
3565 size += instrsize(&b->b_instr[i]);
3566 return size;
3567}
3568
3569/* All about a_lnotab.
3570
3571c_lnotab is an array of unsigned bytes disguised as a Python string.
3572It is used to map bytecode offsets to source code line #s (when needed
3573for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003574
Tim Peters2a7f3842001-06-09 09:26:21 +00003575The array is conceptually a list of
3576 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003577pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003578
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003579 byte code offset source code line number
3580 0 1
3581 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003582 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003583 350 307
3584 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003585
3586The first trick is that these numbers aren't stored, only the increments
3587from one row to the next (this doesn't really work, but it's a start):
3588
3589 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3590
3591The second trick is that an unsigned byte can't hold negative values, or
3592values larger than 255, so (a) there's a deep assumption that byte code
3593offsets and their corresponding line #s both increase monotonically, and (b)
3594if at least one column jumps by more than 255 from one row to the next, more
3595than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003596from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003597part. A user of c_lnotab desiring to find the source line number
3598corresponding to a bytecode address A should do something like this
3599
3600 lineno = addr = 0
3601 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003602 addr += addr_incr
3603 if addr > A:
3604 return lineno
3605 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003606
3607In order for this to work, when the addr field increments by more than 255,
3608the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003609increment is < 256. So, in the example above, assemble_lnotab (it used
3610to be called com_set_lineno) should not (as was actually done until 2.2)
3611expand 300, 300 to 255, 255, 45, 45,
3612 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003613*/
3614
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003615static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003617{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 int d_bytecode, d_lineno;
3619 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621
3622 d_bytecode = a->a_offset - a->a_lineno_off;
3623 d_lineno = i->i_lineno - a->a_lineno;
3624
3625 assert(d_bytecode >= 0);
3626 assert(d_lineno >= 0);
3627
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003628 /* XXX(nnorwitz): is there a better way to handle this?
3629 for loops are special, we want to be able to trace them
3630 each time around, so we need to set an extra line number. */
3631 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003632 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003633
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003635 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 nbytes = a->a_lnotab_off + 2 * ncodes;
3637 len = PyString_GET_SIZE(a->a_lnotab);
3638 if (nbytes >= len) {
3639 if (len * 2 < nbytes)
3640 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003641 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 len *= 2;
3643 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3644 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003645 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003646 lnotab = (unsigned char *)
3647 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003648 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649 *lnotab++ = 255;
3650 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003651 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 d_bytecode -= ncodes * 255;
3653 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003654 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 assert(d_bytecode <= 255);
3656 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003657 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 nbytes = a->a_lnotab_off + 2 * ncodes;
3659 len = PyString_GET_SIZE(a->a_lnotab);
3660 if (nbytes >= len) {
3661 if (len * 2 < nbytes)
3662 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003663 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664 len *= 2;
3665 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3666 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003667 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003668 lnotab = (unsigned char *)
3669 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003671 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003673 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003675 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003676 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 d_lineno -= ncodes * 255;
3678 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003679 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003680
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681 len = PyString_GET_SIZE(a->a_lnotab);
3682 if (a->a_lnotab_off + 2 >= len) {
3683 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003684 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003685 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 lnotab = (unsigned char *)
3687 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 a->a_lnotab_off += 2;
3690 if (d_bytecode) {
3691 *lnotab++ = d_bytecode;
3692 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003693 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003694 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 *lnotab++ = 0;
3696 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698 a->a_lineno = i->i_lineno;
3699 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003700 return 1;
3701}
3702
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703/* assemble_emit()
3704 Extend the bytecode with a new instruction.
3705 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003706*/
3707
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003708static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003710{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003711 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003712 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 char *code;
3714
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003715 size = instrsize(i);
3716 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003718 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003719 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003721 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722 if (a->a_offset + size >= len) {
3723 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003724 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003725 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3727 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003728 if (size == 6) {
3729 assert(i->i_hasarg);
3730 *code++ = (char)EXTENDED_ARG;
3731 *code++ = ext & 0xff;
3732 *code++ = ext >> 8;
3733 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003734 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003736 if (i->i_hasarg) {
3737 assert(size == 3 || size == 6);
3738 *code++ = arg & 0xff;
3739 *code++ = arg >> 8;
3740 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003742}
3743
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003744static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003746{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003748 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003749 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 /* Compute the size of each block and fixup jump args.
3752 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003753start:
3754 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003756 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 bsize = blocksize(b);
3758 b->b_offset = totsize;
3759 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003760 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003761 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3763 bsize = b->b_offset;
3764 for (i = 0; i < b->b_iused; i++) {
3765 struct instr *instr = &b->b_instr[i];
3766 /* Relative jumps are computed relative to
3767 the instruction pointer after fetching
3768 the jump instruction.
3769 */
3770 bsize += instrsize(instr);
3771 if (instr->i_jabs)
3772 instr->i_oparg = instr->i_target->b_offset;
3773 else if (instr->i_jrel) {
3774 int delta = instr->i_target->b_offset - bsize;
3775 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003776 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003777 else
3778 continue;
3779 if (instr->i_oparg > 0xffff)
3780 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003781 }
3782 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003783
3784 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003785 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003786 with a better solution.
3787
3788 In the meantime, should the goto be dropped in favor
3789 of a loop?
3790
3791 The issue is that in the first loop blocksize() is called
3792 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003793 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003794 i_oparg is calculated in the second loop above.
3795
3796 So we loop until we stop seeing new EXTENDED_ARGs.
3797 The only EXTENDED_ARGs that could be popping up are
3798 ones in jump instructions. So this should converge
3799 fairly quickly.
3800 */
3801 if (last_extended_arg_count != extended_arg_count) {
3802 last_extended_arg_count = extended_arg_count;
3803 goto start;
3804 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003805}
3806
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003807static PyObject *
3808dict_keys_inorder(PyObject *dict, int offset)
3809{
3810 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003811 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003812
3813 tuple = PyTuple_New(size);
3814 if (tuple == NULL)
3815 return NULL;
3816 while (PyDict_Next(dict, &pos, &k, &v)) {
3817 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003818 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003819 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003820 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003821 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003822 PyTuple_SET_ITEM(tuple, i - offset, k);
3823 }
3824 return tuple;
3825}
3826
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003827static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003829{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830 PySTEntryObject *ste = c->u->u_ste;
3831 int flags = 0, n;
3832 if (ste->ste_type != ModuleBlock)
3833 flags |= CO_NEWLOCALS;
3834 if (ste->ste_type == FunctionBlock) {
3835 if (!ste->ste_unoptimized)
3836 flags |= CO_OPTIMIZED;
3837 if (ste->ste_nested)
3838 flags |= CO_NESTED;
3839 if (ste->ste_generator)
3840 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 if (ste->ste_varargs)
3843 flags |= CO_VARARGS;
3844 if (ste->ste_varkeywords)
3845 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003846 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003848
3849 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003850 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003851
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003852 n = PyDict_Size(c->u->u_freevars);
3853 if (n < 0)
3854 return -1;
3855 if (n == 0) {
3856 n = PyDict_Size(c->u->u_cellvars);
3857 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003858 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 if (n == 0) {
3860 flags |= CO_NOFREE;
3861 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003862 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003863
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003864 return flags;
3865}
3866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867static PyCodeObject *
3868makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003869{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 PyObject *tmp;
3871 PyCodeObject *co = NULL;
3872 PyObject *consts = NULL;
3873 PyObject *names = NULL;
3874 PyObject *varnames = NULL;
3875 PyObject *filename = NULL;
3876 PyObject *name = NULL;
3877 PyObject *freevars = NULL;
3878 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003879 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003881
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882 tmp = dict_keys_inorder(c->u->u_consts, 0);
3883 if (!tmp)
3884 goto error;
3885 consts = PySequence_List(tmp); /* optimize_code requires a list */
3886 Py_DECREF(tmp);
3887
3888 names = dict_keys_inorder(c->u->u_names, 0);
3889 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3890 if (!consts || !names || !varnames)
3891 goto error;
3892
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003893 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3894 if (!cellvars)
3895 goto error;
3896 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3897 if (!freevars)
3898 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 filename = PyString_FromString(c->c_filename);
3900 if (!filename)
3901 goto error;
3902
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003903 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 flags = compute_code_flags(c);
3905 if (flags < 0)
3906 goto error;
3907
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003908 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 if (!bytecode)
3910 goto error;
3911
3912 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3913 if (!tmp)
3914 goto error;
3915 Py_DECREF(consts);
3916 consts = tmp;
3917
Guido van Rossum4f72a782006-10-27 23:31:49 +00003918 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3919 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920 bytecode, consts, names, varnames,
3921 freevars, cellvars,
3922 filename, c->u->u_name,
3923 c->u->u_firstlineno,
3924 a->a_lnotab);
3925 error:
3926 Py_XDECREF(consts);
3927 Py_XDECREF(names);
3928 Py_XDECREF(varnames);
3929 Py_XDECREF(filename);
3930 Py_XDECREF(name);
3931 Py_XDECREF(freevars);
3932 Py_XDECREF(cellvars);
3933 Py_XDECREF(bytecode);
3934 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003935}
3936
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003937
3938/* For debugging purposes only */
3939#if 0
3940static void
3941dump_instr(const struct instr *i)
3942{
3943 const char *jrel = i->i_jrel ? "jrel " : "";
3944 const char *jabs = i->i_jabs ? "jabs " : "";
3945 char arg[128];
3946
3947 *arg = '\0';
3948 if (i->i_hasarg)
3949 sprintf(arg, "arg: %d ", i->i_oparg);
3950
3951 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3952 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3953}
3954
3955static void
3956dump_basicblock(const basicblock *b)
3957{
3958 const char *seen = b->b_seen ? "seen " : "";
3959 const char *b_return = b->b_return ? "return " : "";
3960 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3961 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3962 if (b->b_instr) {
3963 int i;
3964 for (i = 0; i < b->b_iused; i++) {
3965 fprintf(stderr, " [%02d] ", i);
3966 dump_instr(b->b_instr + i);
3967 }
3968 }
3969}
3970#endif
3971
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972static PyCodeObject *
3973assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003974{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975 basicblock *b, *entryblock;
3976 struct assembler a;
3977 int i, j, nblocks;
3978 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003979
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980 /* Make sure every block that falls off the end returns None.
3981 XXX NEXT_BLOCK() isn't quite right, because if the last
3982 block ends with a jump or return b_next shouldn't set.
3983 */
3984 if (!c->u->u_curblock->b_return) {
3985 NEXT_BLOCK(c);
3986 if (addNone)
3987 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3988 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003989 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003990
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991 nblocks = 0;
3992 entryblock = NULL;
3993 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3994 nblocks++;
3995 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003996 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003997
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003998 /* Set firstlineno if it wasn't explicitly set. */
3999 if (!c->u->u_firstlineno) {
4000 if (entryblock && entryblock->b_instr)
4001 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4002 else
4003 c->u->u_firstlineno = 1;
4004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4006 goto error;
4007 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004008
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004010 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004011
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004012 /* Emit code in reverse postorder from dfs. */
4013 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004014 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004015 for (j = 0; j < b->b_iused; j++)
4016 if (!assemble_emit(&a, &b->b_instr[j]))
4017 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004018 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4021 goto error;
4022 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4023 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004025 co = makecode(c, &a);
4026 error:
4027 assemble_free(&a);
4028 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004029}