blob: 7f0fc503bb47bb75f47dd5e758aff1bfb9128eb5 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Thomas Wouters89f507f2006-12-13 04:49:30 +000011 * this file.
12 * 5. Optimize the byte code (peephole optimizations). See peephole.c
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Guido van Rossum4f72a782006-10-27 23:31:49 +0000110 int u_kwonlyargcount; /* number of keyword only arguments for block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000111 /* Pointer to the most recently allocated block. By following b_list
112 members, you can reach all early allocated blocks. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114 basicblock *u_curblock; /* pointer to current block */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000115 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116
117 int u_nfblocks;
118 struct fblockinfo u_fblock[CO_MAXBLOCKS];
119
120 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000121 int u_lineno; /* the lineno for the current stmt */
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000122 int u_lineno_set; /* boolean to indicate whether instr
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123 has been generated with current lineno */
124};
125
126/* This struct captures the global state of a compilation.
127
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128The u pointer points to the current compilation unit, while units
129for enclosing blocks are stored in c_stack. The u and c_stack are
130managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000131*/
132
133struct compiler {
134 const char *c_filename;
135 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000136 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137 PyCompilerFlags *c_flags;
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000142 struct compiler_unit *u; /* compiler state for current block */
143 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000145 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000146};
147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148static int compiler_enter_scope(struct compiler *, identifier, void *, int);
149static void compiler_free(struct compiler *);
150static basicblock *compiler_new_block(struct compiler *);
151static int compiler_next_instr(struct compiler *, basicblock *);
152static int compiler_addop(struct compiler *, int);
153static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
154static int compiler_addop_i(struct compiler *, int, int);
155static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156static basicblock *compiler_use_new_block(struct compiler *);
157static int compiler_error(struct compiler *, const char *);
158static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
159
160static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
161static int compiler_visit_stmt(struct compiler *, stmt_ty);
162static int compiler_visit_keyword(struct compiler *, keyword_ty);
163static int compiler_visit_expr(struct compiler *, expr_ty);
164static int compiler_augassign(struct compiler *, stmt_ty);
165static int compiler_visit_slice(struct compiler *, slice_ty,
166 expr_context_ty);
167
168static int compiler_push_fblock(struct compiler *, enum fblocktype,
169 basicblock *);
170static void compiler_pop_fblock(struct compiler *, enum fblocktype,
171 basicblock *);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000172/* Returns true if there is a loop on the fblock stack. */
173static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174
175static int inplace_binop(struct compiler *, operator_ty);
176static int expr_constant(expr_ty e);
177
Guido van Rossumc2e20742006-02-27 22:32:47 +0000178static int compiler_with(struct compiler *, stmt_ty);
179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000180static PyCodeObject *assemble(struct compiler *, int addNone);
181static PyObject *__doc__;
182
183PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000185{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186 /* Name mangling: __private becomes _classname__private.
187 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000188 const char *p, *name = PyString_AsString(ident);
189 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000190 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000191 if (privateobj == NULL || !PyString_Check(privateobj) ||
192 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000193 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000195 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000197 nlen = strlen(name);
198 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000199 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000200 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000201 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Strip leading underscores from class name */
203 while (*p == '_')
204 p++;
205 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000210 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
211 if (!ident)
212 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 buffer = PyString_AS_STRING(ident);
215 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 strncpy(buffer+1, p, plen);
217 strcpy(buffer+1+plen, name);
218 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000219}
220
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221static int
222compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000223{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 c->c_stack = PyList_New(0);
227 if (!c->c_stack)
228 return 0;
229
230 return 1;
231}
232
233PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000234PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000235 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000236{
237 struct compiler c;
238 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000239 PyCompilerFlags local_flags;
240 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000241
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000242 if (!__doc__) {
243 __doc__ = PyString_InternFromString("__doc__");
244 if (!__doc__)
245 return NULL;
246 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000247
248 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000249 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252 c.c_future = PyFuture_FromAST(mod, filename);
253 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000254 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000256 local_flags.cf_flags = 0;
257 flags = &local_flags;
258 }
259 merged = c.c_future->ff_features | flags->cf_flags;
260 c.c_future->ff_features = merged;
261 flags->cf_flags = merged;
262 c.c_flags = flags;
263 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
265 c.c_st = PySymtable_Build(mod, filename, c.c_future);
266 if (c.c_st == NULL) {
267 if (!PyErr_Occurred())
268 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000269 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 }
271
272 /* XXX initialize to NULL for now, need to handle */
273 c.c_encoding = NULL;
274
275 co = compiler_mod(&c, mod);
276
Thomas Wouters1175c432006-02-27 22:49:54 +0000277 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000278 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000279 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280 return co;
281}
282
283PyCodeObject *
284PyNode_Compile(struct _node *n, const char *filename)
285{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000286 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000287 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000288 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000289 if (!arena)
290 return NULL;
291 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000292 if (mod)
293 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000294 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000295 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000296}
297
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000298static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000299compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000300{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000301 if (c->c_st)
302 PySymtable_Free(c->c_st);
303 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000306}
307
Guido van Rossum79f25d91997-04-29 20:08:16 +0000308static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000310{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312 PyObject *v, *k;
313 PyObject *dict = PyDict_New();
314 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316 n = PyList_Size(list);
317 for (i = 0; i < n; i++) {
318 v = PyInt_FromLong(i);
319 if (!v) {
320 Py_DECREF(dict);
321 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000322 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000323 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
326 Py_XDECREF(k);
327 Py_DECREF(v);
328 Py_DECREF(dict);
329 return NULL;
330 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000331 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000333 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 return dict;
335}
336
337/* Return new dict containing names from src that match scope(s).
338
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339src is a symbol table dictionary. If the scope of a name matches
340either scope_type or flag is set, insert it into the new dict. The
341values are integers, starting at offset and increasing by one for
342each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343*/
344
345static PyObject *
346dictbytype(PyObject *src, int scope_type, int flag, int offset)
347{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000348 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349 PyObject *k, *v, *dest = PyDict_New();
350
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000351 assert(offset >= 0);
352 if (dest == NULL)
353 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
355 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000356 /* XXX this should probably be a macro in symtable.h */
357 assert(PyInt_Check(v));
358 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000360 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
361 PyObject *tuple, *item = PyInt_FromLong(i);
362 if (item == NULL) {
363 Py_DECREF(dest);
364 return NULL;
365 }
366 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
369 Py_DECREF(item);
370 Py_DECREF(dest);
371 Py_XDECREF(tuple);
372 return NULL;
373 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000374 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000375 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377 }
378 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000379}
380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381static void
382compiler_unit_check(struct compiler_unit *u)
383{
384 basicblock *block;
385 for (block = u->u_blocks; block != NULL; block = block->b_list) {
386 assert(block != (void *)0xcbcbcbcb);
387 assert(block != (void *)0xfbfbfbfb);
388 assert(block != (void *)0xdbdbdbdb);
389 if (block->b_instr != NULL) {
390 assert(block->b_ialloc > 0);
391 assert(block->b_iused > 0);
392 assert(block->b_ialloc >= block->b_iused);
393 }
394 else {
395 assert (block->b_iused == 0);
396 assert (block->b_ialloc == 0);
397 }
398 }
399}
400
401static void
402compiler_unit_free(struct compiler_unit *u)
403{
404 basicblock *b, *next;
405
406 compiler_unit_check(u);
407 b = u->u_blocks;
408 while (b != NULL) {
409 if (b->b_instr)
410 PyObject_Free((void *)b->b_instr);
411 next = b->b_list;
412 PyObject_Free((void *)b);
413 b = next;
414 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000415 Py_CLEAR(u->u_ste);
416 Py_CLEAR(u->u_name);
417 Py_CLEAR(u->u_consts);
418 Py_CLEAR(u->u_names);
419 Py_CLEAR(u->u_varnames);
420 Py_CLEAR(u->u_freevars);
421 Py_CLEAR(u->u_cellvars);
422 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423 PyObject_Free(u);
424}
425
426static int
427compiler_enter_scope(struct compiler *c, identifier name, void *key,
428 int lineno)
429{
430 struct compiler_unit *u;
431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
433 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000434 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000435 PyErr_NoMemory();
436 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000437 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000438 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000439 u->u_argcount = 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000440 u->u_kwonlyargcount = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000441 u->u_ste = PySymtable_Lookup(c->c_st, key);
442 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000443 compiler_unit_free(u);
444 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000445 }
446 Py_INCREF(name);
447 u->u_name = name;
448 u->u_varnames = list2dict(u->u_ste->ste_varnames);
449 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000450 if (!u->u_varnames || !u->u_cellvars) {
451 compiler_unit_free(u);
452 return 0;
453 }
454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000455 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457 if (!u->u_freevars) {
458 compiler_unit_free(u);
459 return 0;
460 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461
462 u->u_blocks = NULL;
463 u->u_tmpname = 0;
464 u->u_nfblocks = 0;
465 u->u_firstlineno = lineno;
466 u->u_lineno = 0;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000467 u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468 u->u_consts = PyDict_New();
469 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000470 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000471 return 0;
472 }
473 u->u_names = PyDict_New();
474 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000475 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000476 return 0;
477 }
478
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000479 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480
481 /* Push the old compiler_unit on the stack. */
482 if (c->u) {
483 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
485 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000486 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000487 return 0;
488 }
489 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000490 u->u_private = c->u->u_private;
491 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492 }
493 c->u = u;
494
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000496 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497 return 0;
498
499 return 1;
500}
501
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000502static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000503compiler_exit_scope(struct compiler *c)
504{
505 int n;
506 PyObject *wrapper;
507
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000508 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000509 compiler_unit_free(c->u);
510 /* Restore c->u to the parent unit. */
511 n = PyList_GET_SIZE(c->c_stack) - 1;
512 if (n >= 0) {
513 wrapper = PyList_GET_ITEM(c->c_stack, n);
514 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000515 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000516 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000518 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519 compiler_unit_check(c->u);
520 }
521 else
522 c->u = NULL;
523
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000524}
525
Guido van Rossumc2e20742006-02-27 22:32:47 +0000526/* Allocate a new "anonymous" local variable.
527 Used by list comprehensions and with statements.
528*/
529
530static PyObject *
531compiler_new_tmpname(struct compiler *c)
532{
533 char tmpname[256];
534 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
535 return PyString_FromString(tmpname);
536}
537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000538/* Allocate a new block and return a pointer to it.
539 Returns NULL on error.
540*/
541
542static basicblock *
543compiler_new_block(struct compiler *c)
544{
545 basicblock *b;
546 struct compiler_unit *u;
547
548 u = c->u;
549 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000550 if (b == NULL) {
551 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters89f507f2006-12-13 04:49:30 +0000555 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556 b->b_list = u->u_blocks;
557 u->u_blocks = b;
558 return b;
559}
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561static basicblock *
562compiler_use_new_block(struct compiler *c)
563{
564 basicblock *block = compiler_new_block(c);
565 if (block == NULL)
566 return NULL;
567 c->u->u_curblock = block;
568 return block;
569}
570
571static basicblock *
572compiler_next_block(struct compiler *c)
573{
574 basicblock *block = compiler_new_block(c);
575 if (block == NULL)
576 return NULL;
577 c->u->u_curblock->b_next = block;
578 c->u->u_curblock = block;
579 return block;
580}
581
582static basicblock *
583compiler_use_next_block(struct compiler *c, basicblock *block)
584{
585 assert(block != NULL);
586 c->u->u_curblock->b_next = block;
587 c->u->u_curblock = block;
588 return block;
589}
590
591/* Returns the offset of the next instruction in the current block's
592 b_instr array. Resizes the b_instr as necessary.
593 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000595
596static int
597compiler_next_instr(struct compiler *c, basicblock *b)
598{
599 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000600 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601 b->b_instr = (struct instr *)PyObject_Malloc(
602 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603 if (b->b_instr == NULL) {
604 PyErr_NoMemory();
605 return -1;
606 }
607 b->b_ialloc = DEFAULT_BLOCK_SIZE;
608 memset((char *)b->b_instr, 0,
609 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613 size_t oldsize, newsize;
614 oldsize = b->b_ialloc * sizeof(struct instr);
615 newsize = oldsize << 1;
616 if (newsize == 0) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000621 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000622 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623 if (tmp == NULL) {
624 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000625 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626 }
627 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000628 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
629 }
630 return b->b_iused++;
631}
632
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633/* Set the i_lineno member of the instruction at offse off if the
634 line number for the current expression/statement (?) has not
635 already been set. If it has been set, the call has no effect.
636
637 Every time a new node is b
Thomas Wouters89f507f2006-12-13 04:49:30 +0000638*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000639
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640static void
641compiler_set_lineno(struct compiler *c, int off)
642{
643 basicblock *b;
644 if (c->u->u_lineno_set)
645 return;
Neal Norwitz6baa4c42007-02-26 19:14:12 +0000646 c->u->u_lineno_set = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000648 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649}
650
651static int
652opcode_stack_effect(int opcode, int oparg)
653{
654 switch (opcode) {
655 case POP_TOP:
656 return -1;
657 case ROT_TWO:
658 case ROT_THREE:
659 return 0;
660 case DUP_TOP:
661 return 1;
662 case ROT_FOUR:
663 return 0;
664
665 case UNARY_POSITIVE:
666 case UNARY_NEGATIVE:
667 case UNARY_NOT:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668 case UNARY_INVERT:
669 return 0;
670
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000671 case LIST_APPEND:
672 return -2;
673
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000674 case BINARY_POWER:
675 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000676 case BINARY_MODULO:
677 case BINARY_ADD:
678 case BINARY_SUBTRACT:
679 case BINARY_SUBSCR:
680 case BINARY_FLOOR_DIVIDE:
681 case BINARY_TRUE_DIVIDE:
682 return -1;
683 case INPLACE_FLOOR_DIVIDE:
684 case INPLACE_TRUE_DIVIDE:
685 return -1;
686
687 case SLICE+0:
688 return 1;
689 case SLICE+1:
690 return 0;
691 case SLICE+2:
692 return 0;
693 case SLICE+3:
694 return -1;
695
696 case STORE_SLICE+0:
697 return -2;
698 case STORE_SLICE+1:
699 return -3;
700 case STORE_SLICE+2:
701 return -3;
702 case STORE_SLICE+3:
703 return -4;
704
705 case DELETE_SLICE+0:
706 return -1;
707 case DELETE_SLICE+1:
708 return -2;
709 case DELETE_SLICE+2:
710 return -2;
711 case DELETE_SLICE+3:
712 return -3;
713
714 case INPLACE_ADD:
715 case INPLACE_SUBTRACT:
716 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000717 case INPLACE_MODULO:
718 return -1;
719 case STORE_SUBSCR:
720 return -3;
721 case DELETE_SUBSCR:
722 return -2;
723
724 case BINARY_LSHIFT:
725 case BINARY_RSHIFT:
726 case BINARY_AND:
727 case BINARY_XOR:
728 case BINARY_OR:
729 return -1;
730 case INPLACE_POWER:
731 return -1;
732 case GET_ITER:
733 return 0;
734
735 case PRINT_EXPR:
736 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737 case INPLACE_LSHIFT:
738 case INPLACE_RSHIFT:
739 case INPLACE_AND:
740 case INPLACE_XOR:
741 case INPLACE_OR:
742 return -1;
743 case BREAK_LOOP:
744 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000745 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000746 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747 case LOAD_LOCALS:
748 return 1;
749 case RETURN_VALUE:
750 return -1;
751 case IMPORT_STAR:
752 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000753 case YIELD_VALUE:
754 return 0;
755
756 case POP_BLOCK:
757 return 0;
758 case END_FINALLY:
759 return -1; /* or -2 or -3 if exception occurred */
760 case BUILD_CLASS:
761 return -2;
762
763 case STORE_NAME:
764 return -1;
765 case DELETE_NAME:
766 return 0;
767 case UNPACK_SEQUENCE:
768 return oparg-1;
769 case FOR_ITER:
770 return 1;
771
772 case STORE_ATTR:
773 return -2;
774 case DELETE_ATTR:
775 return -1;
776 case STORE_GLOBAL:
777 return -1;
778 case DELETE_GLOBAL:
779 return 0;
780 case DUP_TOPX:
781 return oparg;
782 case LOAD_CONST:
783 return 1;
784 case LOAD_NAME:
785 return 1;
786 case BUILD_TUPLE:
787 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000788 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789 return 1-oparg;
790 case BUILD_MAP:
791 return 1;
Thomas Wouters00e41de2007-02-23 19:56:57 +0000792 case MAKE_BYTES:
793 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794 case LOAD_ATTR:
795 return 0;
796 case COMPARE_OP:
797 return -1;
798 case IMPORT_NAME:
799 return 0;
800 case IMPORT_FROM:
801 return 1;
802
803 case JUMP_FORWARD:
804 case JUMP_IF_FALSE:
805 case JUMP_IF_TRUE:
806 case JUMP_ABSOLUTE:
807 return 0;
808
809 case LOAD_GLOBAL:
810 return 1;
811
812 case CONTINUE_LOOP:
813 return 0;
814 case SETUP_LOOP:
815 return 0;
816 case SETUP_EXCEPT:
817 case SETUP_FINALLY:
818 return 3; /* actually pushed by an exception */
819
820 case LOAD_FAST:
821 return 1;
822 case STORE_FAST:
823 return -1;
824 case DELETE_FAST:
825 return 0;
826
827 case RAISE_VARARGS:
828 return -oparg;
Neal Norwitzc1505362006-12-28 06:47:50 +0000829#define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830 case CALL_FUNCTION:
831 return -NARGS(oparg);
832 case CALL_FUNCTION_VAR:
833 case CALL_FUNCTION_KW:
834 return -NARGS(oparg)-1;
835 case CALL_FUNCTION_VAR_KW:
836 return -NARGS(oparg)-2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837 case MAKE_FUNCTION:
Neal Norwitzc1505362006-12-28 06:47:50 +0000838 return -NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum0240b922007-02-26 21:23:50 +0000839 case MAKE_CLOSURE:
840 return -1 - NARGS(oparg) - ((oparg >> 16) & 0xffff);
Guido van Rossum4f72a782006-10-27 23:31:49 +0000841#undef NARGS
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000842 case BUILD_SLICE:
843 if (oparg == 3)
844 return -2;
845 else
846 return -1;
847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000848 case LOAD_CLOSURE:
849 return 1;
850 case LOAD_DEREF:
851 return 1;
852 case STORE_DEREF:
853 return -1;
854 default:
855 fprintf(stderr, "opcode = %d\n", opcode);
856 Py_FatalError("opcode_stack_effect()");
857
858 }
859 return 0; /* not reachable */
860}
861
862/* Add an opcode with no argument.
863 Returns 0 on failure, 1 on success.
864*/
865
866static int
867compiler_addop(struct compiler *c, int opcode)
868{
869 basicblock *b;
870 struct instr *i;
871 int off;
872 off = compiler_next_instr(c, c->u->u_curblock);
873 if (off < 0)
874 return 0;
875 b = c->u->u_curblock;
876 i = &b->b_instr[off];
877 i->i_opcode = opcode;
878 i->i_hasarg = 0;
879 if (opcode == RETURN_VALUE)
880 b->b_return = 1;
881 compiler_set_lineno(c, off);
882 return 1;
883}
884
885static int
886compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
887{
888 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000889 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000891 /* necessary to make sure types aren't coerced (e.g., int and long) */
892 t = PyTuple_Pack(2, o, o->ob_type);
893 if (t == NULL)
894 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
896 v = PyDict_GetItem(dict, t);
897 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000898 if (PyErr_Occurred())
899 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000900 arg = PyDict_Size(dict);
901 v = PyInt_FromLong(arg);
902 if (!v) {
903 Py_DECREF(t);
904 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000905 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000906 if (PyDict_SetItem(dict, t, v) < 0) {
907 Py_DECREF(t);
908 Py_DECREF(v);
909 return -1;
910 }
911 Py_DECREF(v);
912 }
913 else
914 arg = PyInt_AsLong(v);
915 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000916 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000917}
918
919static int
920compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
921 PyObject *o)
922{
923 int arg = compiler_add_o(c, dict, o);
924 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000925 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926 return compiler_addop_i(c, opcode, arg);
927}
928
929static int
930compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000931 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932{
933 int arg;
934 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
935 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000936 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937 arg = compiler_add_o(c, dict, mangled);
938 Py_DECREF(mangled);
939 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000940 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941 return compiler_addop_i(c, opcode, arg);
942}
943
944/* Add an opcode with an integer argument.
945 Returns 0 on failure, 1 on success.
946*/
947
948static int
949compiler_addop_i(struct compiler *c, int opcode, int oparg)
950{
951 struct instr *i;
952 int off;
953 off = compiler_next_instr(c, c->u->u_curblock);
954 if (off < 0)
955 return 0;
956 i = &c->u->u_curblock->b_instr[off];
957 i->i_opcode = opcode;
958 i->i_oparg = oparg;
959 i->i_hasarg = 1;
960 compiler_set_lineno(c, off);
961 return 1;
962}
963
964static int
965compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
966{
967 struct instr *i;
968 int off;
969
970 assert(b != NULL);
971 off = compiler_next_instr(c, c->u->u_curblock);
972 if (off < 0)
973 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 i = &c->u->u_curblock->b_instr[off];
975 i->i_opcode = opcode;
976 i->i_target = b;
977 i->i_hasarg = 1;
978 if (absolute)
979 i->i_jabs = 1;
980 else
981 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000982 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000983 return 1;
984}
985
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
987 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 it as the current block. NEXT_BLOCK() also creates an implicit jump
989 from the current block to the new block.
990*/
991
Thomas Wouters89f507f2006-12-13 04:49:30 +0000992/* The returns inside these macros make it impossible to decref objects
993 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994*/
995
996
997#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 if (compiler_use_new_block((C)) == NULL) \
999 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000}
1001
1002#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 if (compiler_next_block((C)) == NULL) \
1004 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005}
1006
1007#define ADDOP(C, OP) { \
1008 if (!compiler_addop((C), (OP))) \
1009 return 0; \
1010}
1011
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001012#define ADDOP_IN_SCOPE(C, OP) { \
1013 if (!compiler_addop((C), (OP))) { \
1014 compiler_exit_scope(c); \
1015 return 0; \
1016 } \
1017}
1018
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019#define ADDOP_O(C, OP, O, TYPE) { \
1020 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1021 return 0; \
1022}
1023
1024#define ADDOP_NAME(C, OP, O, TYPE) { \
1025 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1026 return 0; \
1027}
1028
1029#define ADDOP_I(C, OP, O) { \
1030 if (!compiler_addop_i((C), (OP), (O))) \
1031 return 0; \
1032}
1033
1034#define ADDOP_JABS(C, OP, O) { \
1035 if (!compiler_addop_j((C), (OP), (O), 1)) \
1036 return 0; \
1037}
1038
1039#define ADDOP_JREL(C, OP, O) { \
1040 if (!compiler_addop_j((C), (OP), (O), 0)) \
1041 return 0; \
1042}
1043
1044/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1045 the ASDL name to synthesize the name of the C type and the visit function.
1046*/
1047
1048#define VISIT(C, TYPE, V) {\
1049 if (!compiler_visit_ ## TYPE((C), (V))) \
1050 return 0; \
1051}
1052
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001053#define VISIT_IN_SCOPE(C, TYPE, V) {\
1054 if (!compiler_visit_ ## TYPE((C), (V))) { \
1055 compiler_exit_scope(c); \
1056 return 0; \
1057 } \
1058}
1059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001060#define VISIT_SLICE(C, V, CTX) {\
1061 if (!compiler_visit_slice((C), (V), (CTX))) \
1062 return 0; \
1063}
1064
1065#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001066 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001068 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001070 if (!compiler_visit_ ## TYPE((C), elt)) \
1071 return 0; \
1072 } \
1073}
1074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001076 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001077 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001078 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001080 if (!compiler_visit_ ## TYPE((C), elt)) { \
1081 compiler_exit_scope(c); \
1082 return 0; \
1083 } \
1084 } \
1085}
1086
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087static int
1088compiler_isdocstring(stmt_ty s)
1089{
1090 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001092 return s->v.Expr.value->kind == Str_kind;
1093}
1094
1095/* Compile a sequence of statements, checking for a docstring. */
1096
1097static int
1098compiler_body(struct compiler *c, asdl_seq *stmts)
1099{
1100 int i = 0;
1101 stmt_ty st;
1102
1103 if (!asdl_seq_LEN(stmts))
1104 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001105 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106 if (compiler_isdocstring(st)) {
1107 i = 1;
1108 VISIT(c, expr, st->v.Expr.value);
1109 if (!compiler_nameop(c, __doc__, Store))
1110 return 0;
1111 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001113 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114 return 1;
1115}
1116
1117static PyCodeObject *
1118compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001119{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001120 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001121 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122 static PyObject *module;
1123 if (!module) {
1124 module = PyString_FromString("<module>");
1125 if (!module)
1126 return NULL;
1127 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1129 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001130 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 switch (mod->kind) {
1132 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001133 if (!compiler_body(c, mod->v.Module.body)) {
1134 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 break;
1138 case Interactive_kind:
1139 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001140 VISIT_SEQ_IN_SCOPE(c, stmt,
1141 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001142 break;
1143 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001145 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 break;
1147 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001148 PyErr_SetString(PyExc_SystemError,
1149 "suite should not be possible");
1150 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001152 PyErr_Format(PyExc_SystemError,
1153 "module kind %d should not be possible",
1154 mod->kind);
1155 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 co = assemble(c, addNone);
1158 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001159 return co;
1160}
1161
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162/* The test for LOCAL must come before the test for FREE in order to
1163 handle classes where name is both local and free. The local var is
1164 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001165*/
1166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167static int
1168get_ref_type(struct compiler *c, PyObject *name)
1169{
1170 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001171 if (scope == 0) {
1172 char buf[350];
1173 PyOS_snprintf(buf, sizeof(buf),
1174 "unknown scope for %.100s in %.100s(%s) in %s\n"
1175 "symbols: %s\nlocals: %s\nglobals: %s\n",
1176 PyString_AS_STRING(name),
1177 PyString_AS_STRING(c->u->u_name),
1178 PyObject_REPR(c->u->u_ste->ste_id),
1179 c->c_filename,
1180 PyObject_REPR(c->u->u_ste->ste_symbols),
1181 PyObject_REPR(c->u->u_varnames),
1182 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 Py_FatalError(buf);
1185 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001186
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001187 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001188}
1189
1190static int
1191compiler_lookup_arg(PyObject *dict, PyObject *name)
1192{
1193 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001196 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001198 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001200 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 return PyInt_AS_LONG(v);
1202}
1203
1204static int
1205compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1206{
1207 int i, free = PyCode_GetNumFree(co);
1208 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1210 ADDOP_I(c, MAKE_FUNCTION, args);
1211 return 1;
1212 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 for (i = 0; i < free; ++i) {
1214 /* Bypass com_addop_varname because it will generate
1215 LOAD_DEREF but LOAD_CLOSURE is needed.
1216 */
1217 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1218 int arg, reftype;
1219
1220 /* Special case: If a class contains a method with a
1221 free variable that has the same name as a method,
1222 the name will be considered free *and* local in the
1223 class. It should be handled by the closure, as
1224 well as by the normal name loookup logic.
1225 */
1226 reftype = get_ref_type(c, name);
1227 if (reftype == CELL)
1228 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1229 else /* (reftype == FREE) */
1230 arg = compiler_lookup_arg(c->u->u_freevars, name);
1231 if (arg == -1) {
1232 printf("lookup %s in %s %d %d\n"
1233 "freevars of %s: %s\n",
1234 PyObject_REPR(name),
1235 PyString_AS_STRING(c->u->u_name),
1236 reftype, arg,
1237 PyString_AS_STRING(co->co_name),
1238 PyObject_REPR(co->co_freevars));
1239 Py_FatalError("compiler_make_closure()");
1240 }
1241 ADDOP_I(c, LOAD_CLOSURE, arg);
1242 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 ADDOP_I(c, MAKE_CLOSURE, args);
1246 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247}
1248
1249static int
1250compiler_decorators(struct compiler *c, asdl_seq* decos)
1251{
1252 int i;
1253
1254 if (!decos)
1255 return 1;
1256
1257 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 }
1260 return 1;
1261}
1262
1263static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001264compiler_unpack_nested(struct compiler *c, asdl_seq *args) {
1265 int i, len;
1266 len = asdl_seq_LEN(args);
1267 ADDOP_I(c, UNPACK_SEQUENCE, len);
1268 for (i = 0; i < len; i++) {
1269 arg_ty elt = (arg_ty)asdl_seq_GET(args, i);
1270 switch (elt->kind) {
1271 case SimpleArg_kind:
1272 if (!compiler_nameop(c, elt->v.SimpleArg.arg, Store))
1273 return 0;
1274 break;
1275 case NestedArgs_kind:
1276 if (!compiler_unpack_nested(c, elt->v.NestedArgs.args))
1277 return 0;
1278 break;
1279 default:
1280 return 0;
1281 }
1282 }
1283 return 1;
1284}
1285
1286static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287compiler_arguments(struct compiler *c, arguments_ty args)
1288{
1289 int i;
1290 int n = asdl_seq_LEN(args->args);
Neal Norwitzc1505362006-12-28 06:47:50 +00001291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292 for (i = 0; i < n; i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001293 arg_ty arg = (arg_ty)asdl_seq_GET(args->args, i);
1294 if (arg->kind == NestedArgs_kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001295 PyObject *id = PyString_FromFormat(".%d", i);
1296 if (id == NULL) {
1297 return 0;
1298 }
1299 if (!compiler_nameop(c, id, Load)) {
1300 Py_DECREF(id);
1301 return 0;
1302 }
1303 Py_DECREF(id);
Neal Norwitzc1505362006-12-28 06:47:50 +00001304 if (!compiler_unpack_nested(c, arg->v.NestedArgs.args))
1305 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 }
1307 }
1308 return 1;
1309}
1310
1311static int
Guido van Rossum4f72a782006-10-27 23:31:49 +00001312compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
1313 asdl_seq *kw_defaults)
1314{
1315 int i, default_count = 0;
1316 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001317 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001318 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1319 if (default_) {
Neal Norwitzc1505362006-12-28 06:47:50 +00001320 ADDOP_O(c, LOAD_CONST, arg->v.SimpleArg.arg, consts);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001321 if (!compiler_visit_expr(c, default_)) {
1322 return -1;
1323 }
1324 default_count++;
1325 }
1326 }
1327 return default_count;
1328}
1329
1330static int
Neal Norwitzc1505362006-12-28 06:47:50 +00001331compiler_visit_argannotation(struct compiler *c, identifier id,
1332 expr_ty annotation, PyObject *names)
1333{
1334 if (annotation) {
1335 VISIT(c, expr, annotation);
1336 if (PyList_Append(names, id))
1337 return -1;
1338 }
1339 return 0;
1340}
1341
1342static int
1343compiler_visit_argannotations(struct compiler *c, asdl_seq* args,
1344 PyObject *names)
1345{
1346 int i, error;
1347 for (i = 0; i < asdl_seq_LEN(args); i++) {
1348 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1349 if (arg->kind == NestedArgs_kind)
1350 error = compiler_visit_argannotations(
1351 c,
1352 arg->v.NestedArgs.args,
1353 names);
1354 else
1355 error = compiler_visit_argannotation(
1356 c,
1357 arg->v.SimpleArg.arg,
1358 arg->v.SimpleArg.annotation,
1359 names);
1360 if (error)
1361 return error;
1362 }
1363 return 0;
1364}
1365
1366static int
1367compiler_visit_annotations(struct compiler *c, arguments_ty args,
1368 expr_ty returns)
1369{
Guido van Rossum0240b922007-02-26 21:23:50 +00001370 /* Push arg annotations and a list of the argument names. Return the #
1371 of items pushed. The expressions are evaluated out-of-order wrt the
1372 source code.
1373
1374 More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
1375 */
Neal Norwitzc1505362006-12-28 06:47:50 +00001376 static identifier return_str;
1377 PyObject *names;
1378 int len;
1379 names = PyList_New(0);
1380 if (!names)
1381 return -1;
1382
1383 if (compiler_visit_argannotations(c, args->args, names))
1384 goto error;
1385 if (args->varargannotation &&
1386 compiler_visit_argannotation(c, args->vararg,
1387 args->varargannotation, names))
1388 goto error;
1389 if (compiler_visit_argannotations(c, args->kwonlyargs, names))
1390 goto error;
1391 if (args->kwargannotation &&
1392 compiler_visit_argannotation(c, args->kwarg,
1393 args->kwargannotation, names))
1394 goto error;
1395
1396 if (!return_str) {
1397 return_str = PyString_InternFromString("return");
1398 if (!return_str)
1399 goto error;
1400 }
1401 if (compiler_visit_argannotation(c, return_str, returns, names)) {
1402 goto error;
1403 }
1404
1405 len = PyList_GET_SIZE(names);
Guido van Rossum0240b922007-02-26 21:23:50 +00001406 if (len > 65534) {
1407 /* len must fit in 16 bits, and len is incremented below */
1408 PyErr_SetString(PyExc_SyntaxError,
1409 "too many annotations");
1410 goto error;
1411 }
Neal Norwitzc1505362006-12-28 06:47:50 +00001412 if (len) {
1413 /* convert names to a tuple and place on stack */
1414 PyObject *elt;
1415 int i;
1416 PyObject *s = PyTuple_New(len);
1417 if (!s)
1418 goto error;
1419 for (i = 0; i < len; i++) {
1420 elt = PyList_GET_ITEM(names, i);
1421 Py_INCREF(elt);
1422 PyTuple_SET_ITEM(s, i, elt);
1423 }
1424 ADDOP_O(c, LOAD_CONST, s, consts);
1425 Py_DECREF(s);
1426 len++; /* include the just-pushed tuple */
1427 }
1428 Py_DECREF(names);
1429 return len;
1430
1431error:
1432 Py_DECREF(names);
1433 return -1;
1434}
1435
1436static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437compiler_function(struct compiler *c, stmt_ty s)
1438{
1439 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001440 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 arguments_ty args = s->v.FunctionDef.args;
Neal Norwitzc1505362006-12-28 06:47:50 +00001442 expr_ty returns = s->v.FunctionDef.returns;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001444 stmt_ty st;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001445 int i, n, docstring, kw_default_count = 0, arglength;
Neal Norwitzc1505362006-12-28 06:47:50 +00001446 int num_annotations;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447
1448 assert(s->kind == FunctionDef_kind);
1449
1450 if (!compiler_decorators(c, decos))
1451 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001452 if (args->kwonlyargs) {
1453 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1454 args->kw_defaults);
1455 if (res < 0)
1456 return 0;
1457 kw_default_count = res;
1458 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 if (args->defaults)
1460 VISIT_SEQ(c, expr, args->defaults);
Neal Norwitzc1505362006-12-28 06:47:50 +00001461 num_annotations = compiler_visit_annotations(c, args, returns);
Guido van Rossum0240b922007-02-26 21:23:50 +00001462 if (num_annotations < 0)
1463 return 0;
1464 assert((num_annotations & 0xFFFF) == num_annotations);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1467 s->lineno))
1468 return 0;
1469
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001470 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001471 docstring = compiler_isdocstring(st);
1472 if (docstring)
1473 first_const = st->v.Expr.value->v.Str.s;
1474 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001475 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001476 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001478
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001479 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001480 compiler_arguments(c, args);
1481
1482 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001483 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001485 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1488 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 }
1490 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001491 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001492 if (co == NULL)
1493 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494
Guido van Rossum4f72a782006-10-27 23:31:49 +00001495 arglength = asdl_seq_LEN(args->defaults);
1496 arglength |= kw_default_count << 8;
Neal Norwitzc1505362006-12-28 06:47:50 +00001497 arglength |= num_annotations << 16;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001498 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001499 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500
Neal Norwitzc1505362006-12-28 06:47:50 +00001501 /* decorators */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1503 ADDOP_I(c, CALL_FUNCTION, 1);
1504 }
1505
1506 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1507}
1508
1509static int
1510compiler_class(struct compiler *c, stmt_ty s)
1511{
1512 int n;
1513 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001514 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515 /* push class name on stack, needed by BUILD_CLASS */
1516 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1517 /* push the tuple of base classes on the stack */
1518 n = asdl_seq_LEN(s->v.ClassDef.bases);
1519 if (n > 0)
1520 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1521 ADDOP_I(c, BUILD_TUPLE, n);
1522 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1523 s->lineno))
1524 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001525 c->u->u_private = s->v.ClassDef.name;
1526 Py_INCREF(c->u->u_private);
1527 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528 if (!str || !compiler_nameop(c, str, Load)) {
1529 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001530 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001531 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001532 }
1533
1534 Py_DECREF(str);
1535 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 if (!str || !compiler_nameop(c, str, Store)) {
1537 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001538 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001540 }
1541 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001543 if (!compiler_body(c, s->v.ClassDef.body)) {
1544 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001546 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001548 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1549 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001551 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552 if (co == NULL)
1553 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001554
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001555 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001556 Py_DECREF(co);
1557
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001558 ADDOP_I(c, CALL_FUNCTION, 0);
1559 ADDOP(c, BUILD_CLASS);
1560 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1561 return 0;
1562 return 1;
1563}
1564
1565static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001566compiler_ifexp(struct compiler *c, expr_ty e)
1567{
1568 basicblock *end, *next;
1569
1570 assert(e->kind == IfExp_kind);
1571 end = compiler_new_block(c);
1572 if (end == NULL)
1573 return 0;
1574 next = compiler_new_block(c);
1575 if (next == NULL)
1576 return 0;
1577 VISIT(c, expr, e->v.IfExp.test);
1578 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1579 ADDOP(c, POP_TOP);
1580 VISIT(c, expr, e->v.IfExp.body);
1581 ADDOP_JREL(c, JUMP_FORWARD, end);
1582 compiler_use_next_block(c, next);
1583 ADDOP(c, POP_TOP);
1584 VISIT(c, expr, e->v.IfExp.orelse);
1585 compiler_use_next_block(c, end);
1586 return 1;
1587}
1588
1589static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590compiler_lambda(struct compiler *c, expr_ty e)
1591{
1592 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001593 static identifier name;
Guido van Rossum4f72a782006-10-27 23:31:49 +00001594 int kw_default_count = 0, arglength;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595 arguments_ty args = e->v.Lambda.args;
1596 assert(e->kind == Lambda_kind);
1597
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001598 if (!name) {
1599 name = PyString_InternFromString("<lambda>");
1600 if (!name)
1601 return 0;
1602 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603
Guido van Rossum4f72a782006-10-27 23:31:49 +00001604 if (args->kwonlyargs) {
1605 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
1606 args->kw_defaults);
1607 if (res < 0) return 0;
1608 kw_default_count = res;
1609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610 if (args->defaults)
1611 VISIT_SEQ(c, expr, args->defaults);
1612 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1613 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001614
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001615 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616 compiler_arguments(c, args);
1617
1618 c->u->u_argcount = asdl_seq_LEN(args->args);
Guido van Rossum4f72a782006-10-27 23:31:49 +00001619 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001620 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1621 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001623 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624 if (co == NULL)
1625 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626
Guido van Rossum4f72a782006-10-27 23:31:49 +00001627 arglength = asdl_seq_LEN(args->defaults);
1628 arglength |= kw_default_count << 8;
1629 compiler_make_closure(c, co, arglength);
Neal Norwitz4737b232005-11-19 23:58:29 +00001630 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631
1632 return 1;
1633}
1634
1635static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636compiler_if(struct compiler *c, stmt_ty s)
1637{
1638 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001639 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640 assert(s->kind == If_kind);
1641 end = compiler_new_block(c);
1642 if (end == NULL)
1643 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001644 next = compiler_new_block(c);
1645 if (next == NULL)
1646 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001647
1648 constant = expr_constant(s->v.If.test);
1649 /* constant = 0: "if 0"
1650 * constant = 1: "if 1", "if 2", ...
1651 * constant = -1: rest */
1652 if (constant == 0) {
1653 if (s->v.If.orelse)
1654 VISIT_SEQ(c, stmt, s->v.If.orelse);
1655 } else if (constant == 1) {
1656 VISIT_SEQ(c, stmt, s->v.If.body);
1657 } else {
1658 VISIT(c, expr, s->v.If.test);
1659 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1660 ADDOP(c, POP_TOP);
1661 VISIT_SEQ(c, stmt, s->v.If.body);
1662 ADDOP_JREL(c, JUMP_FORWARD, end);
1663 compiler_use_next_block(c, next);
1664 ADDOP(c, POP_TOP);
1665 if (s->v.If.orelse)
1666 VISIT_SEQ(c, stmt, s->v.If.orelse);
1667 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 compiler_use_next_block(c, end);
1669 return 1;
1670}
1671
1672static int
1673compiler_for(struct compiler *c, stmt_ty s)
1674{
1675 basicblock *start, *cleanup, *end;
1676
1677 start = compiler_new_block(c);
1678 cleanup = compiler_new_block(c);
1679 end = compiler_new_block(c);
1680 if (start == NULL || end == NULL || cleanup == NULL)
1681 return 0;
1682 ADDOP_JREL(c, SETUP_LOOP, end);
1683 if (!compiler_push_fblock(c, LOOP, start))
1684 return 0;
1685 VISIT(c, expr, s->v.For.iter);
1686 ADDOP(c, GET_ITER);
1687 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001688 /* XXX(nnorwitz): is there a better way to handle this?
1689 for loops are special, we want to be able to trace them
1690 each time around, so we need to set an extra line number. */
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001691 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 ADDOP_JREL(c, FOR_ITER, cleanup);
1693 VISIT(c, expr, s->v.For.target);
1694 VISIT_SEQ(c, stmt, s->v.For.body);
1695 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1696 compiler_use_next_block(c, cleanup);
1697 ADDOP(c, POP_BLOCK);
1698 compiler_pop_fblock(c, LOOP, start);
1699 VISIT_SEQ(c, stmt, s->v.For.orelse);
1700 compiler_use_next_block(c, end);
1701 return 1;
1702}
1703
1704static int
1705compiler_while(struct compiler *c, stmt_ty s)
1706{
1707 basicblock *loop, *orelse, *end, *anchor = NULL;
1708 int constant = expr_constant(s->v.While.test);
1709
1710 if (constant == 0)
1711 return 1;
1712 loop = compiler_new_block(c);
1713 end = compiler_new_block(c);
1714 if (constant == -1) {
1715 anchor = compiler_new_block(c);
1716 if (anchor == NULL)
1717 return 0;
1718 }
1719 if (loop == NULL || end == NULL)
1720 return 0;
1721 if (s->v.While.orelse) {
1722 orelse = compiler_new_block(c);
1723 if (orelse == NULL)
1724 return 0;
1725 }
1726 else
1727 orelse = NULL;
1728
1729 ADDOP_JREL(c, SETUP_LOOP, end);
1730 compiler_use_next_block(c, loop);
1731 if (!compiler_push_fblock(c, LOOP, loop))
1732 return 0;
1733 if (constant == -1) {
1734 VISIT(c, expr, s->v.While.test);
1735 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1736 ADDOP(c, POP_TOP);
1737 }
1738 VISIT_SEQ(c, stmt, s->v.While.body);
1739 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1740
1741 /* XXX should the two POP instructions be in a separate block
1742 if there is no else clause ?
1743 */
1744
1745 if (constant == -1) {
1746 compiler_use_next_block(c, anchor);
1747 ADDOP(c, POP_TOP);
1748 ADDOP(c, POP_BLOCK);
1749 }
1750 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001751 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752 VISIT_SEQ(c, stmt, s->v.While.orelse);
1753 compiler_use_next_block(c, end);
1754
1755 return 1;
1756}
1757
1758static int
1759compiler_continue(struct compiler *c)
1760{
1761 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Thomas Wouters89f507f2006-12-13 04:49:30 +00001762 static const char IN_FINALLY_ERROR_MSG[] =
1763 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 int i;
1765
1766 if (!c->u->u_nfblocks)
1767 return compiler_error(c, LOOP_ERROR_MSG);
1768 i = c->u->u_nfblocks - 1;
1769 switch (c->u->u_fblock[i].fb_type) {
1770 case LOOP:
1771 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1772 break;
1773 case EXCEPT:
1774 case FINALLY_TRY:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001775 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1776 /* Prevent continue anywhere under a finally
1777 even if hidden in a sub-try or except. */
1778 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1779 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1780 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 if (i == -1)
1782 return compiler_error(c, LOOP_ERROR_MSG);
1783 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1784 break;
1785 case FINALLY_END:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001786 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787 }
1788
1789 return 1;
1790}
1791
1792/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1793
1794 SETUP_FINALLY L
1795 <code for body>
1796 POP_BLOCK
1797 LOAD_CONST <None>
1798 L: <code for finalbody>
1799 END_FINALLY
1800
1801 The special instructions use the block stack. Each block
1802 stack entry contains the instruction that created it (here
1803 SETUP_FINALLY), the level of the value stack at the time the
1804 block stack entry was created, and a label (here L).
1805
1806 SETUP_FINALLY:
1807 Pushes the current value stack level and the label
1808 onto the block stack.
1809 POP_BLOCK:
1810 Pops en entry from the block stack, and pops the value
1811 stack until its level is the same as indicated on the
1812 block stack. (The label is ignored.)
1813 END_FINALLY:
1814 Pops a variable number of entries from the *value* stack
1815 and re-raises the exception they specify. The number of
1816 entries popped depends on the (pseudo) exception type.
1817
1818 The block stack is unwound when an exception is raised:
1819 when a SETUP_FINALLY entry is found, the exception is pushed
1820 onto the value stack (and the exception condition is cleared),
1821 and the interpreter jumps to the label gotten from the block
1822 stack.
1823*/
1824
1825static int
1826compiler_try_finally(struct compiler *c, stmt_ty s)
1827{
1828 basicblock *body, *end;
1829 body = compiler_new_block(c);
1830 end = compiler_new_block(c);
1831 if (body == NULL || end == NULL)
1832 return 0;
1833
1834 ADDOP_JREL(c, SETUP_FINALLY, end);
1835 compiler_use_next_block(c, body);
1836 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1837 return 0;
1838 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1839 ADDOP(c, POP_BLOCK);
1840 compiler_pop_fblock(c, FINALLY_TRY, body);
1841
1842 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1843 compiler_use_next_block(c, end);
1844 if (!compiler_push_fblock(c, FINALLY_END, end))
1845 return 0;
1846 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1847 ADDOP(c, END_FINALLY);
1848 compiler_pop_fblock(c, FINALLY_END, end);
1849
1850 return 1;
1851}
1852
1853/*
1854 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1855 (The contents of the value stack is shown in [], with the top
1856 at the right; 'tb' is trace-back info, 'val' the exception's
1857 associated value, and 'exc' the exception.)
1858
1859 Value stack Label Instruction Argument
1860 [] SETUP_EXCEPT L1
1861 [] <code for S>
1862 [] POP_BLOCK
1863 [] JUMP_FORWARD L0
1864
1865 [tb, val, exc] L1: DUP )
1866 [tb, val, exc, exc] <evaluate E1> )
1867 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1868 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1869 [tb, val, exc, 1] POP )
1870 [tb, val, exc] POP
1871 [tb, val] <assign to V1> (or POP if no V1)
1872 [tb] POP
1873 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001874 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875
1876 [tb, val, exc, 0] L2: POP
1877 [tb, val, exc] DUP
1878 .............................etc.......................
1879
1880 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001881 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882
1883 [] L0: <next statement>
1884
1885 Of course, parts are not generated if Vi or Ei is not present.
1886*/
1887static int
1888compiler_try_except(struct compiler *c, stmt_ty s)
1889{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001890 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891 int i, n;
1892
1893 body = compiler_new_block(c);
1894 except = compiler_new_block(c);
1895 orelse = compiler_new_block(c);
1896 end = compiler_new_block(c);
1897 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1898 return 0;
1899 ADDOP_JREL(c, SETUP_EXCEPT, except);
1900 compiler_use_next_block(c, body);
1901 if (!compiler_push_fblock(c, EXCEPT, body))
1902 return 0;
1903 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1904 ADDOP(c, POP_BLOCK);
1905 compiler_pop_fblock(c, EXCEPT, body);
1906 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1907 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1908 compiler_use_next_block(c, except);
1909 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001910 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911 s->v.TryExcept.handlers, i);
1912 if (!handler->type && i < n-1)
1913 return compiler_error(c, "default 'except:' must be last");
Neal Norwitz6baa4c42007-02-26 19:14:12 +00001914 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001915 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 except = compiler_new_block(c);
1917 if (except == NULL)
1918 return 0;
1919 if (handler->type) {
1920 ADDOP(c, DUP_TOP);
1921 VISIT(c, expr, handler->type);
1922 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1923 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1924 ADDOP(c, POP_TOP);
1925 }
1926 ADDOP(c, POP_TOP);
1927 if (handler->name) {
Guido van Rossumb940e112007-01-10 16:19:56 +00001928 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00001929
1930 cleanup_end = compiler_new_block(c);
1931 cleanup_body = compiler_new_block(c);
1932 if(!(cleanup_end || cleanup_body))
1933 return 0;
1934
Guido van Rossum16be03e2007-01-10 18:51:35 +00001935 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001936 ADDOP(c, POP_TOP);
1937
1938 /*
1939 try:
1940 # body
1941 except type as name:
1942 try:
1943 # body
1944 finally:
1945 name = None
1946 del name
1947 */
1948
1949 /* second try: */
1950 ADDOP_JREL(c, SETUP_FINALLY, cleanup_end);
1951 compiler_use_next_block(c, cleanup_body);
1952 if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body))
1953 return 0;
1954
1955 /* second # body */
1956 VISIT_SEQ(c, stmt, handler->body);
1957 ADDOP(c, POP_BLOCK);
1958 compiler_pop_fblock(c, FINALLY_TRY, cleanup_body);
1959
1960 /* finally: */
1961 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1962 compiler_use_next_block(c, cleanup_end);
1963 if (!compiler_push_fblock(c, FINALLY_END, cleanup_end))
1964 return 0;
1965
1966 /* name = None */
1967 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Guido van Rossum16be03e2007-01-10 18:51:35 +00001968 compiler_nameop(c, handler->name, Store);
Guido van Rossumb940e112007-01-10 16:19:56 +00001969
Guido van Rossum16be03e2007-01-10 18:51:35 +00001970 /* del name */
1971 compiler_nameop(c, handler->name, Del);
Guido van Rossumb940e112007-01-10 16:19:56 +00001972
1973 ADDOP(c, END_FINALLY);
1974 compiler_pop_fblock(c, FINALLY_END, cleanup_end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975 }
1976 else {
Guido van Rossumb940e112007-01-10 16:19:56 +00001977 ADDOP(c, POP_TOP);
1978 ADDOP(c, POP_TOP);
1979 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 ADDOP_JREL(c, JUMP_FORWARD, end);
1982 compiler_use_next_block(c, except);
1983 if (handler->type)
1984 ADDOP(c, POP_TOP);
1985 }
1986 ADDOP(c, END_FINALLY);
1987 compiler_use_next_block(c, orelse);
1988 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1989 compiler_use_next_block(c, end);
1990 return 1;
1991}
1992
1993static int
1994compiler_import_as(struct compiler *c, identifier name, identifier asname)
1995{
1996 /* The IMPORT_NAME opcode was already generated. This function
1997 merely needs to bind the result to a name.
1998
1999 If there is a dot in name, we need to split it and emit a
2000 LOAD_ATTR for each name.
2001 */
2002 const char *src = PyString_AS_STRING(name);
2003 const char *dot = strchr(src, '.');
2004 if (dot) {
2005 /* Consume the base module name to get the first attribute */
2006 src = dot + 1;
2007 while (dot) {
2008 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002009 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002011 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002013 if (!attr)
2014 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002016 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 src = dot + 1;
2018 }
2019 }
2020 return compiler_nameop(c, asname, Store);
2021}
2022
2023static int
2024compiler_import(struct compiler *c, stmt_ty s)
2025{
2026 /* The Import node stores a module name like a.b.c as a single
2027 string. This is convenient for all cases except
2028 import a.b.c as d
2029 where we need to parse that string to extract the individual
2030 module names.
2031 XXX Perhaps change the representation to make this case simpler?
2032 */
2033 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002036 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002038 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039
Guido van Rossum45aecf42006-03-15 04:58:47 +00002040 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002041 if (level == NULL)
2042 return 0;
2043
2044 ADDOP_O(c, LOAD_CONST, level, consts);
2045 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2047 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2048
2049 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002050 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002051 if (!r)
2052 return r;
2053 }
2054 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 identifier tmp = alias->name;
2056 const char *base = PyString_AS_STRING(alias->name);
2057 char *dot = strchr(base, '.');
2058 if (dot)
2059 tmp = PyString_FromStringAndSize(base,
2060 dot - base);
2061 r = compiler_nameop(c, tmp, Store);
2062 if (dot) {
2063 Py_DECREF(tmp);
2064 }
2065 if (!r)
2066 return r;
2067 }
2068 }
2069 return 1;
2070}
2071
2072static int
2073compiler_from_import(struct compiler *c, stmt_ty s)
2074{
2075 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076
2077 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002078 PyObject *level;
2079
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 if (!names)
2081 return 0;
2082
Guido van Rossum45aecf42006-03-15 04:58:47 +00002083 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002084 if (!level) {
2085 Py_DECREF(names);
2086 return 0;
2087 }
2088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 /* build up the names */
2090 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002091 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 Py_INCREF(alias->name);
2093 PyTuple_SET_ITEM(names, i, alias->name);
2094 }
2095
2096 if (s->lineno > c->c_future->ff_lineno) {
2097 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2098 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002099 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 Py_DECREF(names);
2101 return compiler_error(c,
2102 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
2105 }
2106 }
2107
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002108 ADDOP_O(c, LOAD_CONST, level, consts);
2109 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002111 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2113 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002114 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 identifier store_name;
2116
2117 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2118 assert(n == 1);
2119 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002120 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 }
2122
2123 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2124 store_name = alias->name;
2125 if (alias->asname)
2126 store_name = alias->asname;
2127
2128 if (!compiler_nameop(c, store_name, Store)) {
2129 Py_DECREF(names);
2130 return 0;
2131 }
2132 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002133 /* remove imported module */
2134 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 return 1;
2136}
2137
2138static int
2139compiler_assert(struct compiler *c, stmt_ty s)
2140{
2141 static PyObject *assertion_error = NULL;
2142 basicblock *end;
2143
2144 if (Py_OptimizeFlag)
2145 return 1;
2146 if (assertion_error == NULL) {
2147 assertion_error = PyString_FromString("AssertionError");
2148 if (assertion_error == NULL)
2149 return 0;
2150 }
2151 VISIT(c, expr, s->v.Assert.test);
2152 end = compiler_new_block(c);
2153 if (end == NULL)
2154 return 0;
2155 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2156 ADDOP(c, POP_TOP);
2157 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2158 if (s->v.Assert.msg) {
2159 VISIT(c, expr, s->v.Assert.msg);
2160 ADDOP_I(c, RAISE_VARARGS, 2);
2161 }
2162 else {
2163 ADDOP_I(c, RAISE_VARARGS, 1);
2164 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002165 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002166 ADDOP(c, POP_TOP);
2167 return 1;
2168}
2169
2170static int
2171compiler_visit_stmt(struct compiler *c, stmt_ty s)
2172{
2173 int i, n;
2174
Thomas Wouters89f507f2006-12-13 04:49:30 +00002175 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002176 c->u->u_lineno = s->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00002177 c->u->u_lineno_set = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002179 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002180 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002182 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002183 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002184 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 if (c->u->u_ste->ste_type != FunctionBlock)
2186 return compiler_error(c, "'return' outside function");
2187 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002188 VISIT(c, expr, s->v.Return.value);
2189 }
2190 else
2191 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2192 ADDOP(c, RETURN_VALUE);
2193 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002194 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002195 VISIT_SEQ(c, expr, s->v.Delete.targets)
2196 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002197 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002198 n = asdl_seq_LEN(s->v.Assign.targets);
2199 VISIT(c, expr, s->v.Assign.value);
2200 for (i = 0; i < n; i++) {
2201 if (i < n - 1)
2202 ADDOP(c, DUP_TOP);
2203 VISIT(c, expr,
2204 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2205 }
2206 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002207 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002208 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002209 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002210 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002211 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002212 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002213 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002215 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216 n = 0;
2217 if (s->v.Raise.type) {
2218 VISIT(c, expr, s->v.Raise.type);
2219 n++;
2220 if (s->v.Raise.inst) {
2221 VISIT(c, expr, s->v.Raise.inst);
2222 n++;
2223 if (s->v.Raise.tback) {
2224 VISIT(c, expr, s->v.Raise.tback);
2225 n++;
2226 }
2227 }
2228 }
2229 ADDOP_I(c, RAISE_VARARGS, n);
2230 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002231 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002232 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002233 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002235 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002236 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002237 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002239 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002241 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002242 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002243 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002245 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 ADDOP(c, PRINT_EXPR);
2247 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002248 else if (s->v.Expr.value->kind != Str_kind &&
2249 s->v.Expr.value->kind != Num_kind) {
2250 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002251 ADDOP(c, POP_TOP);
2252 }
2253 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002254 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002256 case Break_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002257 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 return compiler_error(c, "'break' outside loop");
2259 ADDOP(c, BREAK_LOOP);
2260 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002261 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002263 case With_kind:
2264 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 }
2266 return 1;
2267}
2268
2269static int
2270unaryop(unaryop_ty op)
2271{
2272 switch (op) {
2273 case Invert:
2274 return UNARY_INVERT;
2275 case Not:
2276 return UNARY_NOT;
2277 case UAdd:
2278 return UNARY_POSITIVE;
2279 case USub:
2280 return UNARY_NEGATIVE;
2281 }
2282 return 0;
2283}
2284
2285static int
2286binop(struct compiler *c, operator_ty op)
2287{
2288 switch (op) {
2289 case Add:
2290 return BINARY_ADD;
2291 case Sub:
2292 return BINARY_SUBTRACT;
2293 case Mult:
2294 return BINARY_MULTIPLY;
2295 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002296 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 case Mod:
2298 return BINARY_MODULO;
2299 case Pow:
2300 return BINARY_POWER;
2301 case LShift:
2302 return BINARY_LSHIFT;
2303 case RShift:
2304 return BINARY_RSHIFT;
2305 case BitOr:
2306 return BINARY_OR;
2307 case BitXor:
2308 return BINARY_XOR;
2309 case BitAnd:
2310 return BINARY_AND;
2311 case FloorDiv:
2312 return BINARY_FLOOR_DIVIDE;
2313 }
2314 return 0;
2315}
2316
2317static int
2318cmpop(cmpop_ty op)
2319{
2320 switch (op) {
2321 case Eq:
2322 return PyCmp_EQ;
2323 case NotEq:
2324 return PyCmp_NE;
2325 case Lt:
2326 return PyCmp_LT;
2327 case LtE:
2328 return PyCmp_LE;
2329 case Gt:
2330 return PyCmp_GT;
2331 case GtE:
2332 return PyCmp_GE;
2333 case Is:
2334 return PyCmp_IS;
2335 case IsNot:
2336 return PyCmp_IS_NOT;
2337 case In:
2338 return PyCmp_IN;
2339 case NotIn:
2340 return PyCmp_NOT_IN;
2341 }
2342 return PyCmp_BAD;
2343}
2344
2345static int
2346inplace_binop(struct compiler *c, operator_ty op)
2347{
2348 switch (op) {
2349 case Add:
2350 return INPLACE_ADD;
2351 case Sub:
2352 return INPLACE_SUBTRACT;
2353 case Mult:
2354 return INPLACE_MULTIPLY;
2355 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002356 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 case Mod:
2358 return INPLACE_MODULO;
2359 case Pow:
2360 return INPLACE_POWER;
2361 case LShift:
2362 return INPLACE_LSHIFT;
2363 case RShift:
2364 return INPLACE_RSHIFT;
2365 case BitOr:
2366 return INPLACE_OR;
2367 case BitXor:
2368 return INPLACE_XOR;
2369 case BitAnd:
2370 return INPLACE_AND;
2371 case FloorDiv:
2372 return INPLACE_FLOOR_DIVIDE;
2373 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002374 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002375 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376 return 0;
2377}
2378
2379static int
2380compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2381{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002382 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2384
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002385 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002386 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 /* XXX AugStore isn't used anywhere! */
2388
2389 /* First check for assignment to __debug__. Param? */
2390 if ((ctx == Store || ctx == AugStore || ctx == Del)
2391 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2392 return compiler_error(c, "can not assign to __debug__");
2393 }
2394
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002395 mangled = _Py_Mangle(c->u->u_private, name);
2396 if (!mangled)
2397 return 0;
2398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 op = 0;
2400 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002401 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002402 switch (scope) {
2403 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002404 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405 optype = OP_DEREF;
2406 break;
2407 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002408 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409 optype = OP_DEREF;
2410 break;
2411 case LOCAL:
2412 if (c->u->u_ste->ste_type == FunctionBlock)
2413 optype = OP_FAST;
2414 break;
2415 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002416 if (c->u->u_ste->ste_type == FunctionBlock &&
2417 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418 optype = OP_GLOBAL;
2419 break;
2420 case GLOBAL_EXPLICIT:
2421 optype = OP_GLOBAL;
2422 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002423 default:
2424 /* scope can be 0 */
2425 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002426 }
2427
2428 /* XXX Leave assert here, but handle __doc__ and the like better */
2429 assert(scope || PyString_AS_STRING(name)[0] == '_');
2430
2431 switch (optype) {
2432 case OP_DEREF:
2433 switch (ctx) {
2434 case Load: op = LOAD_DEREF; break;
2435 case Store: op = STORE_DEREF; break;
2436 case AugLoad:
2437 case AugStore:
2438 break;
2439 case Del:
2440 PyErr_Format(PyExc_SyntaxError,
2441 "can not delete variable '%s' referenced "
2442 "in nested scope",
2443 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002444 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002445 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 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 deref variable");
2450 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 }
2452 break;
2453 case OP_FAST:
2454 switch (ctx) {
2455 case Load: op = LOAD_FAST; break;
2456 case Store: op = STORE_FAST; break;
2457 case Del: op = DELETE_FAST; break;
2458 case AugLoad:
2459 case AugStore:
2460 break;
2461 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002462 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002463 PyErr_SetString(PyExc_SystemError,
2464 "param invalid for local variable");
2465 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002467 ADDOP_O(c, op, mangled, varnames);
2468 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 return 1;
2470 case OP_GLOBAL:
2471 switch (ctx) {
2472 case Load: op = LOAD_GLOBAL; break;
2473 case Store: op = STORE_GLOBAL; break;
2474 case Del: op = DELETE_GLOBAL; 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 global variable");
2482 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 }
2484 break;
2485 case OP_NAME:
2486 switch (ctx) {
2487 case Load: op = LOAD_NAME; break;
2488 case Store: op = STORE_NAME; break;
2489 case Del: op = DELETE_NAME; break;
2490 case AugLoad:
2491 case AugStore:
2492 break;
2493 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002494 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002495 PyErr_SetString(PyExc_SystemError,
2496 "param invalid for name variable");
2497 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 }
2499 break;
2500 }
2501
2502 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002503 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002504 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002505 if (arg < 0)
2506 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002507 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508}
2509
2510static int
2511compiler_boolop(struct compiler *c, expr_ty e)
2512{
2513 basicblock *end;
2514 int jumpi, i, n;
2515 asdl_seq *s;
2516
2517 assert(e->kind == BoolOp_kind);
2518 if (e->v.BoolOp.op == And)
2519 jumpi = JUMP_IF_FALSE;
2520 else
2521 jumpi = JUMP_IF_TRUE;
2522 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002523 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 return 0;
2525 s = e->v.BoolOp.values;
2526 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002527 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002528 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002529 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 ADDOP_JREL(c, jumpi, end);
2531 ADDOP(c, POP_TOP)
2532 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002533 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 compiler_use_next_block(c, end);
2535 return 1;
2536}
2537
2538static int
2539compiler_list(struct compiler *c, expr_ty e)
2540{
2541 int n = asdl_seq_LEN(e->v.List.elts);
2542 if (e->v.List.ctx == Store) {
2543 ADDOP_I(c, UNPACK_SEQUENCE, n);
2544 }
2545 VISIT_SEQ(c, expr, e->v.List.elts);
2546 if (e->v.List.ctx == Load) {
2547 ADDOP_I(c, BUILD_LIST, n);
2548 }
2549 return 1;
2550}
2551
2552static int
2553compiler_tuple(struct compiler *c, expr_ty e)
2554{
2555 int n = asdl_seq_LEN(e->v.Tuple.elts);
2556 if (e->v.Tuple.ctx == Store) {
2557 ADDOP_I(c, UNPACK_SEQUENCE, n);
2558 }
2559 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2560 if (e->v.Tuple.ctx == Load) {
2561 ADDOP_I(c, BUILD_TUPLE, n);
2562 }
2563 return 1;
2564}
2565
2566static int
2567compiler_compare(struct compiler *c, expr_ty e)
2568{
2569 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002570 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
2572 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2573 VISIT(c, expr, e->v.Compare.left);
2574 n = asdl_seq_LEN(e->v.Compare.ops);
2575 assert(n > 0);
2576 if (n > 1) {
2577 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002578 if (cleanup == NULL)
2579 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580 VISIT(c, expr,
2581 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 }
2583 for (i = 1; i < n; i++) {
2584 ADDOP(c, DUP_TOP);
2585 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002587 cmpop((cmpop_ty)(asdl_seq_GET(
2588 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002589 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2590 NEXT_BLOCK(c);
2591 ADDOP(c, POP_TOP);
2592 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002593 VISIT(c, expr,
2594 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002596 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002598 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599 if (n > 1) {
2600 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 if (end == NULL)
2602 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 ADDOP_JREL(c, JUMP_FORWARD, end);
2604 compiler_use_next_block(c, cleanup);
2605 ADDOP(c, ROT_TWO);
2606 ADDOP(c, POP_TOP);
2607 compiler_use_next_block(c, end);
2608 }
2609 return 1;
2610}
2611
2612static int
2613compiler_call(struct compiler *c, expr_ty e)
2614{
2615 int n, code = 0;
2616
2617 VISIT(c, expr, e->v.Call.func);
2618 n = asdl_seq_LEN(e->v.Call.args);
2619 VISIT_SEQ(c, expr, e->v.Call.args);
2620 if (e->v.Call.keywords) {
2621 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2622 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2623 }
2624 if (e->v.Call.starargs) {
2625 VISIT(c, expr, e->v.Call.starargs);
2626 code |= 1;
2627 }
2628 if (e->v.Call.kwargs) {
2629 VISIT(c, expr, e->v.Call.kwargs);
2630 code |= 2;
2631 }
2632 switch (code) {
2633 case 0:
2634 ADDOP_I(c, CALL_FUNCTION, n);
2635 break;
2636 case 1:
2637 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2638 break;
2639 case 2:
2640 ADDOP_I(c, CALL_FUNCTION_KW, n);
2641 break;
2642 case 3:
2643 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2644 break;
2645 }
2646 return 1;
2647}
2648
2649static int
2650compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 asdl_seq *generators, int gen_index,
2652 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653{
2654 /* generate code for the iterator, then each of the ifs,
2655 and then write to the element */
2656
2657 comprehension_ty l;
2658 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
2661 start = compiler_new_block(c);
2662 skip = compiler_new_block(c);
2663 if_cleanup = compiler_new_block(c);
2664 anchor = compiler_new_block(c);
2665
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002666 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2667 anchor == NULL)
2668 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002670 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 VISIT(c, expr, l->iter);
2672 ADDOP(c, GET_ITER);
2673 compiler_use_next_block(c, start);
2674 ADDOP_JREL(c, FOR_ITER, anchor);
2675 NEXT_BLOCK(c);
2676 VISIT(c, expr, l->target);
2677
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 n = asdl_seq_LEN(l->ifs);
2680 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002681 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 VISIT(c, expr, e);
2683 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2684 NEXT_BLOCK(c);
2685 ADDOP(c, POP_TOP);
2686 }
2687
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002688 if (++gen_index < asdl_seq_LEN(generators))
2689 if (!compiler_listcomp_generator(c, tmpname,
2690 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 /* only append after the last for generator */
2694 if (gen_index >= asdl_seq_LEN(generators)) {
2695 if (!compiler_nameop(c, tmpname, Load))
2696 return 0;
2697 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002698 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699
2700 compiler_use_next_block(c, skip);
2701 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 for (i = 0; i < n; i++) {
2703 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 if (i == 0)
2705 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 ADDOP(c, POP_TOP);
2707 }
2708 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2709 compiler_use_next_block(c, anchor);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002710 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 return 0;
2714
2715 return 1;
2716}
2717
2718static int
2719compiler_listcomp(struct compiler *c, expr_ty e)
2720{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002722 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723 asdl_seq *generators = e->v.ListComp.generators;
2724
2725 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002726 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 if (!tmp)
2728 return 0;
2729 ADDOP_I(c, BUILD_LIST, 0);
2730 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002732 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2733 e->v.ListComp.elt);
2734 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 return rc;
2736}
2737
2738static int
2739compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002740 asdl_seq *generators, int gen_index,
2741 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742{
2743 /* generate code for the iterator, then each of the ifs,
2744 and then write to the element */
2745
2746 comprehension_ty ge;
2747 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002748 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002749
2750 start = compiler_new_block(c);
2751 skip = compiler_new_block(c);
2752 if_cleanup = compiler_new_block(c);
2753 anchor = compiler_new_block(c);
2754 end = compiler_new_block(c);
2755
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 anchor == NULL || end == NULL)
2758 return 0;
2759
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002760 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 ADDOP_JREL(c, SETUP_LOOP, end);
2762 if (!compiler_push_fblock(c, LOOP, start))
2763 return 0;
2764
2765 if (gen_index == 0) {
2766 /* Receive outermost iter as an implicit argument */
2767 c->u->u_argcount = 1;
2768 ADDOP_I(c, LOAD_FAST, 0);
2769 }
2770 else {
2771 /* Sub-iter - calculate on the fly */
2772 VISIT(c, expr, ge->iter);
2773 ADDOP(c, GET_ITER);
2774 }
2775 compiler_use_next_block(c, start);
2776 ADDOP_JREL(c, FOR_ITER, anchor);
2777 NEXT_BLOCK(c);
2778 VISIT(c, expr, ge->target);
2779
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002780 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781 n = asdl_seq_LEN(ge->ifs);
2782 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002783 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784 VISIT(c, expr, e);
2785 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2786 NEXT_BLOCK(c);
2787 ADDOP(c, POP_TOP);
2788 }
2789
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002790 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2792 return 0;
2793
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002794 /* only append after the last 'for' generator */
2795 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002796 VISIT(c, expr, elt);
2797 ADDOP(c, YIELD_VALUE);
2798 ADDOP(c, POP_TOP);
2799
2800 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802 for (i = 0; i < n; i++) {
2803 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002804 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805 compiler_use_next_block(c, if_cleanup);
2806
2807 ADDOP(c, POP_TOP);
2808 }
2809 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2810 compiler_use_next_block(c, anchor);
2811 ADDOP(c, POP_BLOCK);
2812 compiler_pop_fblock(c, LOOP, start);
2813 compiler_use_next_block(c, end);
2814
2815 return 1;
2816}
2817
2818static int
2819compiler_genexp(struct compiler *c, expr_ty e)
2820{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002821 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822 PyCodeObject *co;
2823 expr_ty outermost_iter = ((comprehension_ty)
2824 (asdl_seq_GET(e->v.GeneratorExp.generators,
2825 0)))->iter;
2826
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002827 if (!name) {
2828 name = PyString_FromString("<genexpr>");
2829 if (!name)
2830 return 0;
2831 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
2833 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2834 return 0;
2835 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2836 e->v.GeneratorExp.elt);
2837 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002838 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839 if (co == NULL)
2840 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002843 Py_DECREF(co);
2844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845 VISIT(c, expr, outermost_iter);
2846 ADDOP(c, GET_ITER);
2847 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
2849 return 1;
2850}
2851
2852static int
2853compiler_visit_keyword(struct compiler *c, keyword_ty k)
2854{
2855 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2856 VISIT(c, expr, k->value);
2857 return 1;
2858}
2859
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 whether they are true or false.
2862
2863 Return values: 1 for true, 0 for false, -1 for non-constant.
2864 */
2865
2866static int
2867expr_constant(expr_ty e)
2868{
2869 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002870 case Ellipsis_kind:
2871 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 case Num_kind:
2873 return PyObject_IsTrue(e->v.Num.n);
2874 case Str_kind:
2875 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002876 case Name_kind:
2877 /* __debug__ is not assignable, so we can optimize
2878 * it away in if and while statements */
2879 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2880 "__debug__") == 0)
2881 return ! Py_OptimizeFlag;
2882 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 default:
2884 return -1;
2885 }
2886}
2887
Guido van Rossumc2e20742006-02-27 22:32:47 +00002888/*
2889 Implements the with statement from PEP 343.
2890
2891 The semantics outlined in that PEP are as follows:
2892
2893 with EXPR as VAR:
2894 BLOCK
2895
2896 It is implemented roughly as:
2897
Thomas Wouters477c8d52006-05-27 19:21:47 +00002898 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002899 exit = context.__exit__ # not calling it
2900 value = context.__enter__()
2901 try:
2902 VAR = value # if VAR present in the syntax
2903 BLOCK
2904 finally:
2905 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002908 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002909 exit(*exc)
2910 */
2911static int
2912compiler_with(struct compiler *c, stmt_ty s)
2913{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002914 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002915 basicblock *block, *finally;
2916 identifier tmpexit, tmpvalue = NULL;
2917
2918 assert(s->kind == With_kind);
2919
Guido van Rossumc2e20742006-02-27 22:32:47 +00002920 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002921 enter_attr = PyString_InternFromString("__enter__");
2922 if (!enter_attr)
2923 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002924 }
2925 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 exit_attr = PyString_InternFromString("__exit__");
2927 if (!exit_attr)
2928 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002929 }
2930
2931 block = compiler_new_block(c);
2932 finally = compiler_new_block(c);
2933 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002934 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002935
2936 /* Create a temporary variable to hold context.__exit__ */
2937 tmpexit = compiler_new_tmpname(c);
2938 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002939 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002940 PyArena_AddPyObject(c->c_arena, tmpexit);
2941
2942 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002944 We need to do this rather than preserving it on the stack
2945 because SETUP_FINALLY remembers the stack level.
2946 We need to do the assignment *inside* the try/finally
2947 so that context.__exit__() is called when the assignment
2948 fails. But we need to call context.__enter__() *before*
2949 the try/finally so that if it fails we won't call
2950 context.__exit__().
2951 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002952 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002953 if (tmpvalue == NULL)
2954 return 0;
2955 PyArena_AddPyObject(c->c_arena, tmpvalue);
2956 }
2957
Thomas Wouters477c8d52006-05-27 19:21:47 +00002958 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002959 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002960
2961 /* Squirrel away context.__exit__ */
2962 ADDOP(c, DUP_TOP);
2963 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2964 if (!compiler_nameop(c, tmpexit, Store))
2965 return 0;
2966
2967 /* Call context.__enter__() */
2968 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2969 ADDOP_I(c, CALL_FUNCTION, 0);
2970
2971 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002972 /* Store it in tmpvalue */
2973 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002974 return 0;
2975 }
2976 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 /* Discard result from context.__enter__() */
2978 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002979 }
2980
2981 /* Start the try block */
2982 ADDOP_JREL(c, SETUP_FINALLY, finally);
2983
2984 compiler_use_next_block(c, block);
2985 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002986 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002987 }
2988
2989 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002990 /* Bind saved result of context.__enter__() to VAR */
2991 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002992 !compiler_nameop(c, tmpvalue, Del))
2993 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002994 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002995 }
2996
2997 /* BLOCK code */
2998 VISIT_SEQ(c, stmt, s->v.With.body);
2999
3000 /* End of try block; start the finally block */
3001 ADDOP(c, POP_BLOCK);
3002 compiler_pop_fblock(c, FINALLY_TRY, block);
3003
3004 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3005 compiler_use_next_block(c, finally);
3006 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003007 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003008
3009 /* Finally block starts; push tmpexit and issue our magic opcode. */
3010 if (!compiler_nameop(c, tmpexit, Load) ||
3011 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003012 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003013 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003014
3015 /* Finally block ends. */
3016 ADDOP(c, END_FINALLY);
3017 compiler_pop_fblock(c, FINALLY_END, finally);
3018 return 1;
3019}
3020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021static int
3022compiler_visit_expr(struct compiler *c, expr_ty e)
3023{
3024 int i, n;
3025
Thomas Wouters89f507f2006-12-13 04:49:30 +00003026 /* If expr e has a different line number than the last expr/stmt,
3027 set a new line number for the next instruction.
3028 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 if (e->lineno > c->u->u_lineno) {
3030 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003031 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032 }
3033 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003034 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003036 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 VISIT(c, expr, e->v.BinOp.left);
3038 VISIT(c, expr, e->v.BinOp.right);
3039 ADDOP(c, binop(c, e->v.BinOp.op));
3040 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003041 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042 VISIT(c, expr, e->v.UnaryOp.operand);
3043 ADDOP(c, unaryop(e->v.UnaryOp.op));
3044 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003045 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003047 case IfExp_kind:
3048 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 /* XXX get rid of arg? */
3051 ADDOP_I(c, BUILD_MAP, 0);
3052 n = asdl_seq_LEN(e->v.Dict.values);
3053 /* We must arrange things just right for STORE_SUBSCR.
3054 It wants the stack to look like (value) (dict) (key) */
3055 for (i = 0; i < n; i++) {
3056 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003057 VISIT(c, expr,
3058 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003060 VISIT(c, expr,
3061 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 ADDOP(c, STORE_SUBSCR);
3063 }
3064 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003065 case Set_kind:
3066 n = asdl_seq_LEN(e->v.Set.elts);
3067 VISIT_SEQ(c, expr, e->v.Set.elts);
3068 ADDOP_I(c, BUILD_SET, n);
3069 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003070 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 return compiler_genexp(c, e);
3074 case Yield_kind:
3075 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003076 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 if (e->v.Yield.value) {
3078 VISIT(c, expr, e->v.Yield.value);
3079 }
3080 else {
3081 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3082 }
3083 ADDOP(c, YIELD_VALUE);
3084 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003089 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3091 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003092 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3094 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003095 case Bytes_kind:
3096 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3097 ADDOP(c, MAKE_BYTES);
3098 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003099 case Ellipsis_kind:
3100 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3101 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003103 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104 if (e->v.Attribute.ctx != AugStore)
3105 VISIT(c, expr, e->v.Attribute.value);
3106 switch (e->v.Attribute.ctx) {
3107 case AugLoad:
3108 ADDOP(c, DUP_TOP);
3109 /* Fall through to load */
3110 case Load:
3111 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3112 break;
3113 case AugStore:
3114 ADDOP(c, ROT_TWO);
3115 /* Fall through to save */
3116 case Store:
3117 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3118 break;
3119 case Del:
3120 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3121 break;
3122 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003123 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003124 PyErr_SetString(PyExc_SystemError,
3125 "param invalid in attribute expression");
3126 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127 }
3128 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130 switch (e->v.Subscript.ctx) {
3131 case AugLoad:
3132 VISIT(c, expr, e->v.Subscript.value);
3133 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3134 break;
3135 case Load:
3136 VISIT(c, expr, e->v.Subscript.value);
3137 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3138 break;
3139 case AugStore:
3140 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3141 break;
3142 case Store:
3143 VISIT(c, expr, e->v.Subscript.value);
3144 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3145 break;
3146 case Del:
3147 VISIT(c, expr, e->v.Subscript.value);
3148 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3149 break;
3150 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003151 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003152 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155 }
3156 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3159 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003162 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 return compiler_tuple(c, e);
3164 }
3165 return 1;
3166}
3167
3168static int
3169compiler_augassign(struct compiler *c, stmt_ty s)
3170{
3171 expr_ty e = s->v.AugAssign.target;
3172 expr_ty auge;
3173
3174 assert(s->kind == AugAssign_kind);
3175
3176 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003177 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003179 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003180 if (auge == NULL)
3181 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 VISIT(c, expr, auge);
3183 VISIT(c, expr, s->v.AugAssign.value);
3184 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3185 auge->v.Attribute.ctx = AugStore;
3186 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187 break;
3188 case Subscript_kind:
3189 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003190 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 if (auge == NULL)
3192 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 VISIT(c, expr, auge);
3194 VISIT(c, expr, s->v.AugAssign.value);
3195 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003200 if (!compiler_nameop(c, e->v.Name.id, Load))
3201 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 VISIT(c, expr, s->v.AugAssign.value);
3203 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3204 return compiler_nameop(c, e->v.Name.id, Store);
3205 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003206 PyErr_Format(PyExc_SystemError,
3207 "invalid node type (%d) for augmented assignment",
3208 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 }
3211 return 1;
3212}
3213
3214static int
3215compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3216{
3217 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003218 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3219 PyErr_SetString(PyExc_SystemError,
3220 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003222 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 f = &c->u->u_fblock[c->u->u_nfblocks++];
3224 f->fb_type = t;
3225 f->fb_block = b;
3226 return 1;
3227}
3228
3229static void
3230compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3231{
3232 struct compiler_unit *u = c->u;
3233 assert(u->u_nfblocks > 0);
3234 u->u_nfblocks--;
3235 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3236 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3237}
3238
Thomas Wouters89f507f2006-12-13 04:49:30 +00003239static int
3240compiler_in_loop(struct compiler *c) {
3241 int i;
3242 struct compiler_unit *u = c->u;
3243 for (i = 0; i < u->u_nfblocks; ++i) {
3244 if (u->u_fblock[i].fb_type == LOOP)
3245 return 1;
3246 }
3247 return 0;
3248}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249/* Raises a SyntaxError and returns 0.
3250 If something goes wrong, a different exception may be raised.
3251*/
3252
3253static int
3254compiler_error(struct compiler *c, const char *errstr)
3255{
3256 PyObject *loc;
3257 PyObject *u = NULL, *v = NULL;
3258
3259 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3260 if (!loc) {
3261 Py_INCREF(Py_None);
3262 loc = Py_None;
3263 }
3264 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3265 Py_None, loc);
3266 if (!u)
3267 goto exit;
3268 v = Py_BuildValue("(zO)", errstr, u);
3269 if (!v)
3270 goto exit;
3271 PyErr_SetObject(PyExc_SyntaxError, v);
3272 exit:
3273 Py_DECREF(loc);
3274 Py_XDECREF(u);
3275 Py_XDECREF(v);
3276 return 0;
3277}
3278
3279static int
3280compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003281 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003285 /* XXX this code is duplicated */
3286 switch (ctx) {
3287 case AugLoad: /* fall through to Load */
3288 case Load: op = BINARY_SUBSCR; break;
3289 case AugStore:/* fall through to Store */
3290 case Store: op = STORE_SUBSCR; break;
3291 case Del: op = DELETE_SUBSCR; break;
3292 case Param:
3293 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003294 "invalid %s kind %d in subscript\n",
3295 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003296 return 0;
3297 }
3298 if (ctx == AugLoad) {
3299 ADDOP_I(c, DUP_TOPX, 2);
3300 }
3301 else if (ctx == AugStore) {
3302 ADDOP(c, ROT_THREE);
3303 }
3304 ADDOP(c, op);
3305 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306}
3307
3308static int
3309compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3310{
3311 int n = 2;
3312 assert(s->kind == Slice_kind);
3313
3314 /* only handles the cases where BUILD_SLICE is emitted */
3315 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003316 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317 }
3318 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003321
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003323 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 }
3325 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003326 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327 }
3328
3329 if (s->v.Slice.step) {
3330 n++;
3331 VISIT(c, expr, s->v.Slice.step);
3332 }
3333 ADDOP_I(c, BUILD_SLICE, n);
3334 return 1;
3335}
3336
3337static int
3338compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3339{
3340 int op = 0, slice_offset = 0, stack_count = 0;
3341
3342 assert(s->v.Slice.step == NULL);
3343 if (s->v.Slice.lower) {
3344 slice_offset++;
3345 stack_count++;
3346 if (ctx != AugStore)
3347 VISIT(c, expr, s->v.Slice.lower);
3348 }
3349 if (s->v.Slice.upper) {
3350 slice_offset += 2;
3351 stack_count++;
3352 if (ctx != AugStore)
3353 VISIT(c, expr, s->v.Slice.upper);
3354 }
3355
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003356 if (ctx == AugLoad) {
3357 switch (stack_count) {
3358 case 0: ADDOP(c, DUP_TOP); break;
3359 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3360 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3361 }
3362 }
3363 else if (ctx == AugStore) {
3364 switch (stack_count) {
3365 case 0: ADDOP(c, ROT_TWO); break;
3366 case 1: ADDOP(c, ROT_THREE); break;
3367 case 2: ADDOP(c, ROT_FOUR); break;
3368 }
3369 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003370
3371 switch (ctx) {
3372 case AugLoad: /* fall through to Load */
3373 case Load: op = SLICE; break;
3374 case AugStore:/* fall through to Store */
3375 case Store: op = STORE_SLICE; break;
3376 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003377 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003378 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003379 PyErr_SetString(PyExc_SystemError,
3380 "param invalid in simple slice");
3381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382 }
3383
3384 ADDOP(c, op + slice_offset);
3385 return 1;
3386}
3387
3388static int
3389compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3390 expr_context_ty ctx)
3391{
3392 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003393 case Slice_kind:
3394 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003395 case Index_kind:
3396 VISIT(c, expr, s->v.Index.value);
3397 break;
3398 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003399 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003400 PyErr_SetString(PyExc_SystemError,
3401 "extended slice invalid in nested slice");
3402 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403 }
3404 return 1;
3405}
3406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407static int
3408compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3409{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003410 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003412 case Index_kind:
3413 kindname = "index";
3414 if (ctx != AugStore) {
3415 VISIT(c, expr, s->v.Index.value);
3416 }
3417 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003418 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003419 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003420 if (!s->v.Slice.step)
3421 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003422 if (ctx != AugStore) {
3423 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003424 return 0;
3425 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003426 break;
3427 case ExtSlice_kind:
3428 kindname = "extended slice";
3429 if (ctx != AugStore) {
3430 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3431 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003432 slice_ty sub = (slice_ty)asdl_seq_GET(
3433 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003434 if (!compiler_visit_nested_slice(c, sub, ctx))
3435 return 0;
3436 }
3437 ADDOP_I(c, BUILD_TUPLE, n);
3438 }
3439 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003440 default:
3441 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003442 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003443 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003445 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003446}
3447
Thomas Wouters89f507f2006-12-13 04:49:30 +00003448/* End of the compiler section, beginning of the assembler section */
3449
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450/* do depth-first search of basic block graph, starting with block.
3451 post records the block indices in post-order.
3452
3453 XXX must handle implicit jumps from one block to next
3454*/
3455
Thomas Wouters89f507f2006-12-13 04:49:30 +00003456struct assembler {
3457 PyObject *a_bytecode; /* string containing bytecode */
3458 int a_offset; /* offset into bytecode */
3459 int a_nblocks; /* number of reachable blocks */
3460 basicblock **a_postorder; /* list of blocks in dfs postorder */
3461 PyObject *a_lnotab; /* string containing lnotab */
3462 int a_lnotab_off; /* offset into lnotab */
3463 int a_lineno; /* last lineno of emitted instruction */
3464 int a_lineno_off; /* bytecode offset of last lineno */
3465};
3466
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467static void
3468dfs(struct compiler *c, basicblock *b, struct assembler *a)
3469{
3470 int i;
3471 struct instr *instr = NULL;
3472
3473 if (b->b_seen)
3474 return;
3475 b->b_seen = 1;
3476 if (b->b_next != NULL)
3477 dfs(c, b->b_next, a);
3478 for (i = 0; i < b->b_iused; i++) {
3479 instr = &b->b_instr[i];
3480 if (instr->i_jrel || instr->i_jabs)
3481 dfs(c, instr->i_target, a);
3482 }
3483 a->a_postorder[a->a_nblocks++] = b;
3484}
3485
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003486static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3488{
3489 int i;
3490 struct instr *instr;
3491 if (b->b_seen || b->b_startdepth >= depth)
3492 return maxdepth;
3493 b->b_seen = 1;
3494 b->b_startdepth = depth;
3495 for (i = 0; i < b->b_iused; i++) {
3496 instr = &b->b_instr[i];
3497 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3498 if (depth > maxdepth)
3499 maxdepth = depth;
3500 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3501 if (instr->i_jrel || instr->i_jabs) {
3502 maxdepth = stackdepth_walk(c, instr->i_target,
3503 depth, maxdepth);
3504 if (instr->i_opcode == JUMP_ABSOLUTE ||
3505 instr->i_opcode == JUMP_FORWARD) {
3506 goto out; /* remaining code is dead */
3507 }
3508 }
3509 }
3510 if (b->b_next)
3511 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3512out:
3513 b->b_seen = 0;
3514 return maxdepth;
3515}
3516
3517/* Find the flow path that needs the largest stack. We assume that
3518 * cycles in the flow graph have no net effect on the stack depth.
3519 */
3520static int
3521stackdepth(struct compiler *c)
3522{
3523 basicblock *b, *entryblock;
3524 entryblock = NULL;
3525 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3526 b->b_seen = 0;
3527 b->b_startdepth = INT_MIN;
3528 entryblock = b;
3529 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003530 if (!entryblock)
3531 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 return stackdepth_walk(c, entryblock, 0, 0);
3533}
3534
3535static int
3536assemble_init(struct assembler *a, int nblocks, int firstlineno)
3537{
3538 memset(a, 0, sizeof(struct assembler));
3539 a->a_lineno = firstlineno;
3540 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3541 if (!a->a_bytecode)
3542 return 0;
3543 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3544 if (!a->a_lnotab)
3545 return 0;
3546 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003547 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003548 if (!a->a_postorder) {
3549 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 return 1;
3553}
3554
3555static void
3556assemble_free(struct assembler *a)
3557{
3558 Py_XDECREF(a->a_bytecode);
3559 Py_XDECREF(a->a_lnotab);
3560 if (a->a_postorder)
3561 PyObject_Free(a->a_postorder);
3562}
3563
3564/* Return the size of a basic block in bytes. */
3565
3566static int
3567instrsize(struct instr *instr)
3568{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003569 if (!instr->i_hasarg)
3570 return 1;
3571 if (instr->i_oparg > 0xffff)
3572 return 6;
3573 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574}
3575
3576static int
3577blocksize(basicblock *b)
3578{
3579 int i;
3580 int size = 0;
3581
3582 for (i = 0; i < b->b_iused; i++)
3583 size += instrsize(&b->b_instr[i]);
3584 return size;
3585}
3586
3587/* All about a_lnotab.
3588
3589c_lnotab is an array of unsigned bytes disguised as a Python string.
3590It is used to map bytecode offsets to source code line #s (when needed
3591for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003592
Tim Peters2a7f3842001-06-09 09:26:21 +00003593The array is conceptually a list of
3594 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003595pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003596
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003597 byte code offset source code line number
3598 0 1
3599 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003600 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003601 350 307
3602 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003603
3604The first trick is that these numbers aren't stored, only the increments
3605from one row to the next (this doesn't really work, but it's a start):
3606
3607 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3608
3609The second trick is that an unsigned byte can't hold negative values, or
3610values larger than 255, so (a) there's a deep assumption that byte code
3611offsets and their corresponding line #s both increase monotonically, and (b)
3612if at least one column jumps by more than 255 from one row to the next, more
3613than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003614from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003615part. A user of c_lnotab desiring to find the source line number
3616corresponding to a bytecode address A should do something like this
3617
3618 lineno = addr = 0
3619 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003620 addr += addr_incr
3621 if addr > A:
3622 return lineno
3623 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003624
3625In order for this to work, when the addr field increments by more than 255,
3626the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003627increment is < 256. So, in the example above, assemble_lnotab (it used
3628to be called com_set_lineno) should not (as was actually done until 2.2)
3629expand 300, 300 to 255, 255, 45, 45,
3630 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003631*/
3632
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003633static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003635{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 int d_bytecode, d_lineno;
3637 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003638 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639
3640 d_bytecode = a->a_offset - a->a_lineno_off;
3641 d_lineno = i->i_lineno - a->a_lineno;
3642
3643 assert(d_bytecode >= 0);
3644 assert(d_lineno >= 0);
3645
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003646 /* XXX(nnorwitz): is there a better way to handle this?
3647 for loops are special, we want to be able to trace them
3648 each time around, so we need to set an extra line number. */
3649 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003650 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003651
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003653 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 nbytes = a->a_lnotab_off + 2 * ncodes;
3655 len = PyString_GET_SIZE(a->a_lnotab);
3656 if (nbytes >= len) {
3657 if (len * 2 < nbytes)
3658 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003659 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 len *= 2;
3661 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3662 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003663 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003664 lnotab = (unsigned char *)
3665 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003666 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 *lnotab++ = 255;
3668 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003669 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 d_bytecode -= ncodes * 255;
3671 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003672 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003673 assert(d_bytecode <= 255);
3674 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003675 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 nbytes = a->a_lnotab_off + 2 * ncodes;
3677 len = PyString_GET_SIZE(a->a_lnotab);
3678 if (nbytes >= len) {
3679 if (len * 2 < nbytes)
3680 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003681 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 len *= 2;
3683 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3684 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003685 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003686 lnotab = (unsigned char *)
3687 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003689 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003691 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003693 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003694 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 d_lineno -= ncodes * 255;
3696 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003697 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003698
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699 len = PyString_GET_SIZE(a->a_lnotab);
3700 if (a->a_lnotab_off + 2 >= len) {
3701 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003702 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003703 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003704 lnotab = (unsigned char *)
3705 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003706
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003707 a->a_lnotab_off += 2;
3708 if (d_bytecode) {
3709 *lnotab++ = d_bytecode;
3710 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003711 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003712 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003713 *lnotab++ = 0;
3714 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003715 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716 a->a_lineno = i->i_lineno;
3717 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003718 return 1;
3719}
3720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721/* assemble_emit()
3722 Extend the bytecode with a new instruction.
3723 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003724*/
3725
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003726static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003728{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003729 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003730 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 char *code;
3732
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003733 size = instrsize(i);
3734 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003735 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003736 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003737 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003739 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 if (a->a_offset + size >= len) {
3741 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003742 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003743 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3745 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003746 if (size == 6) {
3747 assert(i->i_hasarg);
3748 *code++ = (char)EXTENDED_ARG;
3749 *code++ = ext & 0xff;
3750 *code++ = ext >> 8;
3751 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003752 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003754 if (i->i_hasarg) {
3755 assert(size == 3 || size == 6);
3756 *code++ = arg & 0xff;
3757 *code++ = arg >> 8;
3758 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003760}
3761
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003762static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003764{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003766 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003767 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 /* Compute the size of each block and fixup jump args.
3770 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003771start:
3772 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003774 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 bsize = blocksize(b);
3776 b->b_offset = totsize;
3777 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003778 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003779 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003780 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3781 bsize = b->b_offset;
3782 for (i = 0; i < b->b_iused; i++) {
3783 struct instr *instr = &b->b_instr[i];
3784 /* Relative jumps are computed relative to
3785 the instruction pointer after fetching
3786 the jump instruction.
3787 */
3788 bsize += instrsize(instr);
3789 if (instr->i_jabs)
3790 instr->i_oparg = instr->i_target->b_offset;
3791 else if (instr->i_jrel) {
3792 int delta = instr->i_target->b_offset - bsize;
3793 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003794 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003795 else
3796 continue;
3797 if (instr->i_oparg > 0xffff)
3798 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003799 }
3800 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003801
3802 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003803 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003804 with a better solution.
3805
3806 In the meantime, should the goto be dropped in favor
3807 of a loop?
3808
3809 The issue is that in the first loop blocksize() is called
3810 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003811 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003812 i_oparg is calculated in the second loop above.
3813
3814 So we loop until we stop seeing new EXTENDED_ARGs.
3815 The only EXTENDED_ARGs that could be popping up are
3816 ones in jump instructions. So this should converge
3817 fairly quickly.
3818 */
3819 if (last_extended_arg_count != extended_arg_count) {
3820 last_extended_arg_count = extended_arg_count;
3821 goto start;
3822 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003823}
3824
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003825static PyObject *
3826dict_keys_inorder(PyObject *dict, int offset)
3827{
3828 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003829 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003830
3831 tuple = PyTuple_New(size);
3832 if (tuple == NULL)
3833 return NULL;
3834 while (PyDict_Next(dict, &pos, &k, &v)) {
3835 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003836 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003837 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003838 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003839 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003840 PyTuple_SET_ITEM(tuple, i - offset, k);
3841 }
3842 return tuple;
3843}
3844
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003845static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003847{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 PySTEntryObject *ste = c->u->u_ste;
3849 int flags = 0, n;
3850 if (ste->ste_type != ModuleBlock)
3851 flags |= CO_NEWLOCALS;
3852 if (ste->ste_type == FunctionBlock) {
3853 if (!ste->ste_unoptimized)
3854 flags |= CO_OPTIMIZED;
3855 if (ste->ste_nested)
3856 flags |= CO_NESTED;
3857 if (ste->ste_generator)
3858 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003859 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003860 if (ste->ste_varargs)
3861 flags |= CO_VARARGS;
3862 if (ste->ste_varkeywords)
3863 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003864 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003866
3867 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003868 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 n = PyDict_Size(c->u->u_freevars);
3871 if (n < 0)
3872 return -1;
3873 if (n == 0) {
3874 n = PyDict_Size(c->u->u_cellvars);
3875 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003876 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 if (n == 0) {
3878 flags |= CO_NOFREE;
3879 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003880 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003881
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003882 return flags;
3883}
3884
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885static PyCodeObject *
3886makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 PyObject *tmp;
3889 PyCodeObject *co = NULL;
3890 PyObject *consts = NULL;
3891 PyObject *names = NULL;
3892 PyObject *varnames = NULL;
3893 PyObject *filename = NULL;
3894 PyObject *name = NULL;
3895 PyObject *freevars = NULL;
3896 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003897 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003899
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 tmp = dict_keys_inorder(c->u->u_consts, 0);
3901 if (!tmp)
3902 goto error;
3903 consts = PySequence_List(tmp); /* optimize_code requires a list */
3904 Py_DECREF(tmp);
3905
3906 names = dict_keys_inorder(c->u->u_names, 0);
3907 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3908 if (!consts || !names || !varnames)
3909 goto error;
3910
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003911 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3912 if (!cellvars)
3913 goto error;
3914 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3915 if (!freevars)
3916 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917 filename = PyString_FromString(c->c_filename);
3918 if (!filename)
3919 goto error;
3920
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003921 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 flags = compute_code_flags(c);
3923 if (flags < 0)
3924 goto error;
3925
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003926 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927 if (!bytecode)
3928 goto error;
3929
3930 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3931 if (!tmp)
3932 goto error;
3933 Py_DECREF(consts);
3934 consts = tmp;
3935
Guido van Rossum4f72a782006-10-27 23:31:49 +00003936 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3937 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938 bytecode, consts, names, varnames,
3939 freevars, cellvars,
3940 filename, c->u->u_name,
3941 c->u->u_firstlineno,
3942 a->a_lnotab);
3943 error:
3944 Py_XDECREF(consts);
3945 Py_XDECREF(names);
3946 Py_XDECREF(varnames);
3947 Py_XDECREF(filename);
3948 Py_XDECREF(name);
3949 Py_XDECREF(freevars);
3950 Py_XDECREF(cellvars);
3951 Py_XDECREF(bytecode);
3952 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003953}
3954
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003955
3956/* For debugging purposes only */
3957#if 0
3958static void
3959dump_instr(const struct instr *i)
3960{
3961 const char *jrel = i->i_jrel ? "jrel " : "";
3962 const char *jabs = i->i_jabs ? "jabs " : "";
3963 char arg[128];
3964
3965 *arg = '\0';
3966 if (i->i_hasarg)
3967 sprintf(arg, "arg: %d ", i->i_oparg);
3968
3969 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3970 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3971}
3972
3973static void
3974dump_basicblock(const basicblock *b)
3975{
3976 const char *seen = b->b_seen ? "seen " : "";
3977 const char *b_return = b->b_return ? "return " : "";
3978 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3979 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3980 if (b->b_instr) {
3981 int i;
3982 for (i = 0; i < b->b_iused; i++) {
3983 fprintf(stderr, " [%02d] ", i);
3984 dump_instr(b->b_instr + i);
3985 }
3986 }
3987}
3988#endif
3989
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990static PyCodeObject *
3991assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003992{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003993 basicblock *b, *entryblock;
3994 struct assembler a;
3995 int i, j, nblocks;
3996 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003997
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003998 /* Make sure every block that falls off the end returns None.
3999 XXX NEXT_BLOCK() isn't quite right, because if the last
4000 block ends with a jump or return b_next shouldn't set.
4001 */
4002 if (!c->u->u_curblock->b_return) {
4003 NEXT_BLOCK(c);
4004 if (addNone)
4005 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4006 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004007 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004008
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009 nblocks = 0;
4010 entryblock = NULL;
4011 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4012 nblocks++;
4013 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004014 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004015
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004016 /* Set firstlineno if it wasn't explicitly set. */
4017 if (!c->u->u_firstlineno) {
4018 if (entryblock && entryblock->b_instr)
4019 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4020 else
4021 c->u->u_firstlineno = 1;
4022 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004023 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4024 goto error;
4025 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004026
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004027 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004028 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004029
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004030 /* Emit code in reverse postorder from dfs. */
4031 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004032 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033 for (j = 0; j < b->b_iused; j++)
4034 if (!assemble_emit(&a, &b->b_instr[j]))
4035 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004036 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004037
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004038 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4039 goto error;
4040 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4041 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004043 co = makecode(c, &a);
4044 error:
4045 assemble_free(&a);
4046 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004047}