blob: 1e4dddf891b1f17cefebfe29d76c426345255e68 [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 Hylton81e95022007-02-27 06:50:52 +00002242 case Nonlocal_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002244 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002246 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002247 ADDOP(c, PRINT_EXPR);
2248 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002249 else if (s->v.Expr.value->kind != Str_kind &&
2250 s->v.Expr.value->kind != Num_kind) {
2251 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002252 ADDOP(c, POP_TOP);
2253 }
2254 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002255 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002257 case Break_kind:
Thomas Wouters89f507f2006-12-13 04:49:30 +00002258 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259 return compiler_error(c, "'break' outside loop");
2260 ADDOP(c, BREAK_LOOP);
2261 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002264 case With_kind:
2265 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 }
2267 return 1;
2268}
2269
2270static int
2271unaryop(unaryop_ty op)
2272{
2273 switch (op) {
2274 case Invert:
2275 return UNARY_INVERT;
2276 case Not:
2277 return UNARY_NOT;
2278 case UAdd:
2279 return UNARY_POSITIVE;
2280 case USub:
2281 return UNARY_NEGATIVE;
2282 }
2283 return 0;
2284}
2285
2286static int
2287binop(struct compiler *c, operator_ty op)
2288{
2289 switch (op) {
2290 case Add:
2291 return BINARY_ADD;
2292 case Sub:
2293 return BINARY_SUBTRACT;
2294 case Mult:
2295 return BINARY_MULTIPLY;
2296 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002297 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 case Mod:
2299 return BINARY_MODULO;
2300 case Pow:
2301 return BINARY_POWER;
2302 case LShift:
2303 return BINARY_LSHIFT;
2304 case RShift:
2305 return BINARY_RSHIFT;
2306 case BitOr:
2307 return BINARY_OR;
2308 case BitXor:
2309 return BINARY_XOR;
2310 case BitAnd:
2311 return BINARY_AND;
2312 case FloorDiv:
2313 return BINARY_FLOOR_DIVIDE;
2314 }
2315 return 0;
2316}
2317
2318static int
2319cmpop(cmpop_ty op)
2320{
2321 switch (op) {
2322 case Eq:
2323 return PyCmp_EQ;
2324 case NotEq:
2325 return PyCmp_NE;
2326 case Lt:
2327 return PyCmp_LT;
2328 case LtE:
2329 return PyCmp_LE;
2330 case Gt:
2331 return PyCmp_GT;
2332 case GtE:
2333 return PyCmp_GE;
2334 case Is:
2335 return PyCmp_IS;
2336 case IsNot:
2337 return PyCmp_IS_NOT;
2338 case In:
2339 return PyCmp_IN;
2340 case NotIn:
2341 return PyCmp_NOT_IN;
2342 }
2343 return PyCmp_BAD;
2344}
2345
2346static int
2347inplace_binop(struct compiler *c, operator_ty op)
2348{
2349 switch (op) {
2350 case Add:
2351 return INPLACE_ADD;
2352 case Sub:
2353 return INPLACE_SUBTRACT;
2354 case Mult:
2355 return INPLACE_MULTIPLY;
2356 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002357 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358 case Mod:
2359 return INPLACE_MODULO;
2360 case Pow:
2361 return INPLACE_POWER;
2362 case LShift:
2363 return INPLACE_LSHIFT;
2364 case RShift:
2365 return INPLACE_RSHIFT;
2366 case BitOr:
2367 return INPLACE_OR;
2368 case BitXor:
2369 return INPLACE_XOR;
2370 case BitAnd:
2371 return INPLACE_AND;
2372 case FloorDiv:
2373 return INPLACE_FLOOR_DIVIDE;
2374 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002375 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002376 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377 return 0;
2378}
2379
2380static int
2381compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2382{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002383 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002384 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2385
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002386 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002387 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388 /* XXX AugStore isn't used anywhere! */
2389
2390 /* First check for assignment to __debug__. Param? */
2391 if ((ctx == Store || ctx == AugStore || ctx == Del)
2392 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2393 return compiler_error(c, "can not assign to __debug__");
2394 }
2395
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002396 mangled = _Py_Mangle(c->u->u_private, name);
2397 if (!mangled)
2398 return 0;
2399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400 op = 0;
2401 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002402 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403 switch (scope) {
2404 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002405 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406 optype = OP_DEREF;
2407 break;
2408 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002409 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410 optype = OP_DEREF;
2411 break;
2412 case LOCAL:
2413 if (c->u->u_ste->ste_type == FunctionBlock)
2414 optype = OP_FAST;
2415 break;
2416 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002417 if (c->u->u_ste->ste_type == FunctionBlock &&
2418 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419 optype = OP_GLOBAL;
2420 break;
2421 case GLOBAL_EXPLICIT:
2422 optype = OP_GLOBAL;
2423 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002424 default:
2425 /* scope can be 0 */
2426 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427 }
2428
2429 /* XXX Leave assert here, but handle __doc__ and the like better */
2430 assert(scope || PyString_AS_STRING(name)[0] == '_');
2431
2432 switch (optype) {
2433 case OP_DEREF:
2434 switch (ctx) {
2435 case Load: op = LOAD_DEREF; break;
2436 case Store: op = STORE_DEREF; break;
2437 case AugLoad:
2438 case AugStore:
2439 break;
2440 case Del:
2441 PyErr_Format(PyExc_SyntaxError,
2442 "can not delete variable '%s' referenced "
2443 "in nested scope",
2444 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002445 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002448 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002449 PyErr_SetString(PyExc_SystemError,
2450 "param invalid for deref variable");
2451 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002452 }
2453 break;
2454 case OP_FAST:
2455 switch (ctx) {
2456 case Load: op = LOAD_FAST; break;
2457 case Store: op = STORE_FAST; break;
2458 case Del: op = DELETE_FAST; break;
2459 case AugLoad:
2460 case AugStore:
2461 break;
2462 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002463 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002464 PyErr_SetString(PyExc_SystemError,
2465 "param invalid for local variable");
2466 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002468 ADDOP_O(c, op, mangled, varnames);
2469 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 return 1;
2471 case OP_GLOBAL:
2472 switch (ctx) {
2473 case Load: op = LOAD_GLOBAL; break;
2474 case Store: op = STORE_GLOBAL; break;
2475 case Del: op = DELETE_GLOBAL; break;
2476 case AugLoad:
2477 case AugStore:
2478 break;
2479 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002480 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002481 PyErr_SetString(PyExc_SystemError,
2482 "param invalid for global variable");
2483 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 }
2485 break;
2486 case OP_NAME:
2487 switch (ctx) {
2488 case Load: op = LOAD_NAME; break;
2489 case Store: op = STORE_NAME; break;
2490 case Del: op = DELETE_NAME; break;
2491 case AugLoad:
2492 case AugStore:
2493 break;
2494 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002495 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002496 PyErr_SetString(PyExc_SystemError,
2497 "param invalid for name variable");
2498 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 }
2500 break;
2501 }
2502
2503 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002504 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002505 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002506 if (arg < 0)
2507 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002508 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509}
2510
2511static int
2512compiler_boolop(struct compiler *c, expr_ty e)
2513{
2514 basicblock *end;
2515 int jumpi, i, n;
2516 asdl_seq *s;
2517
2518 assert(e->kind == BoolOp_kind);
2519 if (e->v.BoolOp.op == And)
2520 jumpi = JUMP_IF_FALSE;
2521 else
2522 jumpi = JUMP_IF_TRUE;
2523 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002524 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 return 0;
2526 s = e->v.BoolOp.values;
2527 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002528 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002530 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 ADDOP_JREL(c, jumpi, end);
2532 ADDOP(c, POP_TOP)
2533 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002534 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535 compiler_use_next_block(c, end);
2536 return 1;
2537}
2538
2539static int
2540compiler_list(struct compiler *c, expr_ty e)
2541{
2542 int n = asdl_seq_LEN(e->v.List.elts);
2543 if (e->v.List.ctx == Store) {
2544 ADDOP_I(c, UNPACK_SEQUENCE, n);
2545 }
2546 VISIT_SEQ(c, expr, e->v.List.elts);
2547 if (e->v.List.ctx == Load) {
2548 ADDOP_I(c, BUILD_LIST, n);
2549 }
2550 return 1;
2551}
2552
2553static int
2554compiler_tuple(struct compiler *c, expr_ty e)
2555{
2556 int n = asdl_seq_LEN(e->v.Tuple.elts);
2557 if (e->v.Tuple.ctx == Store) {
2558 ADDOP_I(c, UNPACK_SEQUENCE, n);
2559 }
2560 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2561 if (e->v.Tuple.ctx == Load) {
2562 ADDOP_I(c, BUILD_TUPLE, n);
2563 }
2564 return 1;
2565}
2566
2567static int
2568compiler_compare(struct compiler *c, expr_ty e)
2569{
2570 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002571 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572
2573 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2574 VISIT(c, expr, e->v.Compare.left);
2575 n = asdl_seq_LEN(e->v.Compare.ops);
2576 assert(n > 0);
2577 if (n > 1) {
2578 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002579 if (cleanup == NULL)
2580 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002581 VISIT(c, expr,
2582 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 }
2584 for (i = 1; i < n; i++) {
2585 ADDOP(c, DUP_TOP);
2586 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002588 cmpop((cmpop_ty)(asdl_seq_GET(
2589 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2591 NEXT_BLOCK(c);
2592 ADDOP(c, POP_TOP);
2593 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002594 VISIT(c, expr,
2595 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002597 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002599 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 if (n > 1) {
2601 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 if (end == NULL)
2603 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604 ADDOP_JREL(c, JUMP_FORWARD, end);
2605 compiler_use_next_block(c, cleanup);
2606 ADDOP(c, ROT_TWO);
2607 ADDOP(c, POP_TOP);
2608 compiler_use_next_block(c, end);
2609 }
2610 return 1;
2611}
2612
2613static int
2614compiler_call(struct compiler *c, expr_ty e)
2615{
2616 int n, code = 0;
2617
2618 VISIT(c, expr, e->v.Call.func);
2619 n = asdl_seq_LEN(e->v.Call.args);
2620 VISIT_SEQ(c, expr, e->v.Call.args);
2621 if (e->v.Call.keywords) {
2622 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2623 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2624 }
2625 if (e->v.Call.starargs) {
2626 VISIT(c, expr, e->v.Call.starargs);
2627 code |= 1;
2628 }
2629 if (e->v.Call.kwargs) {
2630 VISIT(c, expr, e->v.Call.kwargs);
2631 code |= 2;
2632 }
2633 switch (code) {
2634 case 0:
2635 ADDOP_I(c, CALL_FUNCTION, n);
2636 break;
2637 case 1:
2638 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2639 break;
2640 case 2:
2641 ADDOP_I(c, CALL_FUNCTION_KW, n);
2642 break;
2643 case 3:
2644 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2645 break;
2646 }
2647 return 1;
2648}
2649
2650static int
2651compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 asdl_seq *generators, int gen_index,
2653 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654{
2655 /* generate code for the iterator, then each of the ifs,
2656 and then write to the element */
2657
2658 comprehension_ty l;
2659 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002660 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661
2662 start = compiler_new_block(c);
2663 skip = compiler_new_block(c);
2664 if_cleanup = compiler_new_block(c);
2665 anchor = compiler_new_block(c);
2666
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2668 anchor == NULL)
2669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002671 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 VISIT(c, expr, l->iter);
2673 ADDOP(c, GET_ITER);
2674 compiler_use_next_block(c, start);
2675 ADDOP_JREL(c, FOR_ITER, anchor);
2676 NEXT_BLOCK(c);
2677 VISIT(c, expr, l->target);
2678
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002679 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 n = asdl_seq_LEN(l->ifs);
2681 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 VISIT(c, expr, e);
2684 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2685 NEXT_BLOCK(c);
2686 ADDOP(c, POP_TOP);
2687 }
2688
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 if (++gen_index < asdl_seq_LEN(generators))
2690 if (!compiler_listcomp_generator(c, tmpname,
2691 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002694 /* only append after the last for generator */
2695 if (gen_index >= asdl_seq_LEN(generators)) {
2696 if (!compiler_nameop(c, tmpname, Load))
2697 return 0;
2698 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002699 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700
2701 compiler_use_next_block(c, skip);
2702 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 for (i = 0; i < n; i++) {
2704 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002705 if (i == 0)
2706 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 ADDOP(c, POP_TOP);
2708 }
2709 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2710 compiler_use_next_block(c, anchor);
Thomas Wouters89f507f2006-12-13 04:49:30 +00002711 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 return 0;
2715
2716 return 1;
2717}
2718
2719static int
2720compiler_listcomp(struct compiler *c, expr_ty e)
2721{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002723 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 asdl_seq *generators = e->v.ListComp.generators;
2725
2726 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002727 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 if (!tmp)
2729 return 0;
2730 ADDOP_I(c, BUILD_LIST, 0);
2731 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002733 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2734 e->v.ListComp.elt);
2735 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736 return rc;
2737}
2738
2739static int
2740compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002741 asdl_seq *generators, int gen_index,
2742 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743{
2744 /* generate code for the iterator, then each of the ifs,
2745 and then write to the element */
2746
2747 comprehension_ty ge;
2748 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002749 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750
2751 start = compiler_new_block(c);
2752 skip = compiler_new_block(c);
2753 if_cleanup = compiler_new_block(c);
2754 anchor = compiler_new_block(c);
2755 end = compiler_new_block(c);
2756
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002757 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758 anchor == NULL || end == NULL)
2759 return 0;
2760
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002761 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762 ADDOP_JREL(c, SETUP_LOOP, end);
2763 if (!compiler_push_fblock(c, LOOP, start))
2764 return 0;
2765
2766 if (gen_index == 0) {
2767 /* Receive outermost iter as an implicit argument */
2768 c->u->u_argcount = 1;
2769 ADDOP_I(c, LOAD_FAST, 0);
2770 }
2771 else {
2772 /* Sub-iter - calculate on the fly */
2773 VISIT(c, expr, ge->iter);
2774 ADDOP(c, GET_ITER);
2775 }
2776 compiler_use_next_block(c, start);
2777 ADDOP_JREL(c, FOR_ITER, anchor);
2778 NEXT_BLOCK(c);
2779 VISIT(c, expr, ge->target);
2780
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782 n = asdl_seq_LEN(ge->ifs);
2783 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002784 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 VISIT(c, expr, e);
2786 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2787 NEXT_BLOCK(c);
2788 ADDOP(c, POP_TOP);
2789 }
2790
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002791 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002792 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2793 return 0;
2794
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002795 /* only append after the last 'for' generator */
2796 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797 VISIT(c, expr, elt);
2798 ADDOP(c, YIELD_VALUE);
2799 ADDOP(c, POP_TOP);
2800
2801 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002803 for (i = 0; i < n; i++) {
2804 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002805 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002806 compiler_use_next_block(c, if_cleanup);
2807
2808 ADDOP(c, POP_TOP);
2809 }
2810 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2811 compiler_use_next_block(c, anchor);
2812 ADDOP(c, POP_BLOCK);
2813 compiler_pop_fblock(c, LOOP, start);
2814 compiler_use_next_block(c, end);
2815
2816 return 1;
2817}
2818
2819static int
2820compiler_genexp(struct compiler *c, expr_ty e)
2821{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002822 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002823 PyCodeObject *co;
2824 expr_ty outermost_iter = ((comprehension_ty)
2825 (asdl_seq_GET(e->v.GeneratorExp.generators,
2826 0)))->iter;
2827
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002828 if (!name) {
2829 name = PyString_FromString("<genexpr>");
2830 if (!name)
2831 return 0;
2832 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833
2834 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2835 return 0;
2836 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2837 e->v.GeneratorExp.elt);
2838 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002839 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 if (co == NULL)
2841 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002844 Py_DECREF(co);
2845
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 VISIT(c, expr, outermost_iter);
2847 ADDOP(c, GET_ITER);
2848 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849
2850 return 1;
2851}
2852
2853static int
2854compiler_visit_keyword(struct compiler *c, keyword_ty k)
2855{
2856 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2857 VISIT(c, expr, k->value);
2858 return 1;
2859}
2860
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 whether they are true or false.
2863
2864 Return values: 1 for true, 0 for false, -1 for non-constant.
2865 */
2866
2867static int
2868expr_constant(expr_ty e)
2869{
2870 switch (e->kind) {
Georg Brandl52318d62006-09-06 07:06:08 +00002871 case Ellipsis_kind:
2872 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873 case Num_kind:
2874 return PyObject_IsTrue(e->v.Num.n);
2875 case Str_kind:
2876 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002877 case Name_kind:
2878 /* __debug__ is not assignable, so we can optimize
2879 * it away in if and while statements */
2880 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2881 "__debug__") == 0)
2882 return ! Py_OptimizeFlag;
2883 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 default:
2885 return -1;
2886 }
2887}
2888
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889/*
2890 Implements the with statement from PEP 343.
2891
2892 The semantics outlined in that PEP are as follows:
2893
2894 with EXPR as VAR:
2895 BLOCK
2896
2897 It is implemented roughly as:
2898
Thomas Wouters477c8d52006-05-27 19:21:47 +00002899 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900 exit = context.__exit__ # not calling it
2901 value = context.__enter__()
2902 try:
2903 VAR = value # if VAR present in the syntax
2904 BLOCK
2905 finally:
2906 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002907 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002909 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002910 exit(*exc)
2911 */
2912static int
2913compiler_with(struct compiler *c, stmt_ty s)
2914{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002915 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002916 basicblock *block, *finally;
2917 identifier tmpexit, tmpvalue = NULL;
2918
2919 assert(s->kind == With_kind);
2920
Guido van Rossumc2e20742006-02-27 22:32:47 +00002921 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 enter_attr = PyString_InternFromString("__enter__");
2923 if (!enter_attr)
2924 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002925 }
2926 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002927 exit_attr = PyString_InternFromString("__exit__");
2928 if (!exit_attr)
2929 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002930 }
2931
2932 block = compiler_new_block(c);
2933 finally = compiler_new_block(c);
2934 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002935 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002936
2937 /* Create a temporary variable to hold context.__exit__ */
2938 tmpexit = compiler_new_tmpname(c);
2939 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002940 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002941 PyArena_AddPyObject(c->c_arena, tmpexit);
2942
2943 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002945 We need to do this rather than preserving it on the stack
2946 because SETUP_FINALLY remembers the stack level.
2947 We need to do the assignment *inside* the try/finally
2948 so that context.__exit__() is called when the assignment
2949 fails. But we need to call context.__enter__() *before*
2950 the try/finally so that if it fails we won't call
2951 context.__exit__().
2952 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002954 if (tmpvalue == NULL)
2955 return 0;
2956 PyArena_AddPyObject(c->c_arena, tmpvalue);
2957 }
2958
Thomas Wouters477c8d52006-05-27 19:21:47 +00002959 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002960 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002961
2962 /* Squirrel away context.__exit__ */
2963 ADDOP(c, DUP_TOP);
2964 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2965 if (!compiler_nameop(c, tmpexit, Store))
2966 return 0;
2967
2968 /* Call context.__enter__() */
2969 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2970 ADDOP_I(c, CALL_FUNCTION, 0);
2971
2972 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002973 /* Store it in tmpvalue */
2974 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002975 return 0;
2976 }
2977 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002978 /* Discard result from context.__enter__() */
2979 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002980 }
2981
2982 /* Start the try block */
2983 ADDOP_JREL(c, SETUP_FINALLY, finally);
2984
2985 compiler_use_next_block(c, block);
2986 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002987 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002988 }
2989
2990 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 /* Bind saved result of context.__enter__() to VAR */
2992 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002993 !compiler_nameop(c, tmpvalue, Del))
2994 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002995 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002996 }
2997
2998 /* BLOCK code */
2999 VISIT_SEQ(c, stmt, s->v.With.body);
3000
3001 /* End of try block; start the finally block */
3002 ADDOP(c, POP_BLOCK);
3003 compiler_pop_fblock(c, FINALLY_TRY, block);
3004
3005 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3006 compiler_use_next_block(c, finally);
3007 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003008 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003009
3010 /* Finally block starts; push tmpexit and issue our magic opcode. */
3011 if (!compiler_nameop(c, tmpexit, Load) ||
3012 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003013 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003014 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003015
3016 /* Finally block ends. */
3017 ADDOP(c, END_FINALLY);
3018 compiler_pop_fblock(c, FINALLY_END, finally);
3019 return 1;
3020}
3021
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022static int
3023compiler_visit_expr(struct compiler *c, expr_ty e)
3024{
3025 int i, n;
3026
Thomas Wouters89f507f2006-12-13 04:49:30 +00003027 /* If expr e has a different line number than the last expr/stmt,
3028 set a new line number for the next instruction.
3029 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 if (e->lineno > c->u->u_lineno) {
3031 c->u->u_lineno = e->lineno;
Neal Norwitz6baa4c42007-02-26 19:14:12 +00003032 c->u->u_lineno_set = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 }
3034 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003035 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 VISIT(c, expr, e->v.BinOp.left);
3039 VISIT(c, expr, e->v.BinOp.right);
3040 ADDOP(c, binop(c, e->v.BinOp.op));
3041 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043 VISIT(c, expr, e->v.UnaryOp.operand);
3044 ADDOP(c, unaryop(e->v.UnaryOp.op));
3045 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003046 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003048 case IfExp_kind:
3049 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003050 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 /* XXX get rid of arg? */
3052 ADDOP_I(c, BUILD_MAP, 0);
3053 n = asdl_seq_LEN(e->v.Dict.values);
3054 /* We must arrange things just right for STORE_SUBSCR.
3055 It wants the stack to look like (value) (dict) (key) */
3056 for (i = 0; i < n; i++) {
3057 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003058 VISIT(c, expr,
3059 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003061 VISIT(c, expr,
3062 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 ADDOP(c, STORE_SUBSCR);
3064 }
3065 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00003066 case Set_kind:
3067 n = asdl_seq_LEN(e->v.Set.elts);
3068 VISIT_SEQ(c, expr, e->v.Set.elts);
3069 ADDOP_I(c, BUILD_SET, n);
3070 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003071 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003073 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 return compiler_genexp(c, e);
3075 case Yield_kind:
3076 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003077 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 if (e->v.Yield.value) {
3079 VISIT(c, expr, e->v.Yield.value);
3080 }
3081 else {
3082 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3083 }
3084 ADDOP(c, YIELD_VALUE);
3085 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003086 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003088 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003090 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3092 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003093 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3095 break;
Thomas Wouters00e41de2007-02-23 19:56:57 +00003096 case Bytes_kind:
3097 ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts);
3098 ADDOP(c, MAKE_BYTES);
3099 break;
Georg Brandl52318d62006-09-06 07:06:08 +00003100 case Ellipsis_kind:
3101 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3102 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003103 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003104 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105 if (e->v.Attribute.ctx != AugStore)
3106 VISIT(c, expr, e->v.Attribute.value);
3107 switch (e->v.Attribute.ctx) {
3108 case AugLoad:
3109 ADDOP(c, DUP_TOP);
3110 /* Fall through to load */
3111 case Load:
3112 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3113 break;
3114 case AugStore:
3115 ADDOP(c, ROT_TWO);
3116 /* Fall through to save */
3117 case Store:
3118 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3119 break;
3120 case Del:
3121 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3122 break;
3123 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003124 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003125 PyErr_SetString(PyExc_SystemError,
3126 "param invalid in attribute expression");
3127 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128 }
3129 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003130 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131 switch (e->v.Subscript.ctx) {
3132 case AugLoad:
3133 VISIT(c, expr, e->v.Subscript.value);
3134 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3135 break;
3136 case Load:
3137 VISIT(c, expr, e->v.Subscript.value);
3138 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3139 break;
3140 case AugStore:
3141 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3142 break;
3143 case Store:
3144 VISIT(c, expr, e->v.Subscript.value);
3145 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3146 break;
3147 case Del:
3148 VISIT(c, expr, e->v.Subscript.value);
3149 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3150 break;
3151 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003152 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003153 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003154 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 }
3157 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3160 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164 return compiler_tuple(c, e);
3165 }
3166 return 1;
3167}
3168
3169static int
3170compiler_augassign(struct compiler *c, stmt_ty s)
3171{
3172 expr_ty e = s->v.AugAssign.target;
3173 expr_ty auge;
3174
3175 assert(s->kind == AugAssign_kind);
3176
3177 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003178 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003180 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 if (auge == NULL)
3182 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183 VISIT(c, expr, auge);
3184 VISIT(c, expr, s->v.AugAssign.value);
3185 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3186 auge->v.Attribute.ctx = AugStore;
3187 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 break;
3189 case Subscript_kind:
3190 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003191 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 if (auge == NULL)
3193 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 VISIT(c, expr, auge);
3195 VISIT(c, expr, s->v.AugAssign.value);
3196 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003199 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003201 if (!compiler_nameop(c, e->v.Name.id, Load))
3202 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 VISIT(c, expr, s->v.AugAssign.value);
3204 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3205 return compiler_nameop(c, e->v.Name.id, Store);
3206 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003207 PyErr_Format(PyExc_SystemError,
3208 "invalid node type (%d) for augmented assignment",
3209 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211 }
3212 return 1;
3213}
3214
3215static int
3216compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3217{
3218 struct fblockinfo *f;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003219 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3220 PyErr_SetString(PyExc_SystemError,
3221 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 return 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +00003223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 f = &c->u->u_fblock[c->u->u_nfblocks++];
3225 f->fb_type = t;
3226 f->fb_block = b;
3227 return 1;
3228}
3229
3230static void
3231compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3232{
3233 struct compiler_unit *u = c->u;
3234 assert(u->u_nfblocks > 0);
3235 u->u_nfblocks--;
3236 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3237 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3238}
3239
Thomas Wouters89f507f2006-12-13 04:49:30 +00003240static int
3241compiler_in_loop(struct compiler *c) {
3242 int i;
3243 struct compiler_unit *u = c->u;
3244 for (i = 0; i < u->u_nfblocks; ++i) {
3245 if (u->u_fblock[i].fb_type == LOOP)
3246 return 1;
3247 }
3248 return 0;
3249}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250/* Raises a SyntaxError and returns 0.
3251 If something goes wrong, a different exception may be raised.
3252*/
3253
3254static int
3255compiler_error(struct compiler *c, const char *errstr)
3256{
3257 PyObject *loc;
3258 PyObject *u = NULL, *v = NULL;
3259
3260 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3261 if (!loc) {
3262 Py_INCREF(Py_None);
3263 loc = Py_None;
3264 }
3265 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3266 Py_None, loc);
3267 if (!u)
3268 goto exit;
3269 v = Py_BuildValue("(zO)", errstr, u);
3270 if (!v)
3271 goto exit;
3272 PyErr_SetObject(PyExc_SyntaxError, v);
3273 exit:
3274 Py_DECREF(loc);
3275 Py_XDECREF(u);
3276 Py_XDECREF(v);
3277 return 0;
3278}
3279
3280static int
3281compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003282 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003284 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003286 /* XXX this code is duplicated */
3287 switch (ctx) {
3288 case AugLoad: /* fall through to Load */
3289 case Load: op = BINARY_SUBSCR; break;
3290 case AugStore:/* fall through to Store */
3291 case Store: op = STORE_SUBSCR; break;
3292 case Del: op = DELETE_SUBSCR; break;
3293 case Param:
3294 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003295 "invalid %s kind %d in subscript\n",
3296 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 return 0;
3298 }
3299 if (ctx == AugLoad) {
3300 ADDOP_I(c, DUP_TOPX, 2);
3301 }
3302 else if (ctx == AugStore) {
3303 ADDOP(c, ROT_THREE);
3304 }
3305 ADDOP(c, op);
3306 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307}
3308
3309static int
3310compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3311{
3312 int n = 2;
3313 assert(s->kind == Slice_kind);
3314
3315 /* only handles the cases where BUILD_SLICE is emitted */
3316 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003317 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318 }
3319 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003320 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003324 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 }
3326 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003327 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 }
3329
3330 if (s->v.Slice.step) {
3331 n++;
3332 VISIT(c, expr, s->v.Slice.step);
3333 }
3334 ADDOP_I(c, BUILD_SLICE, n);
3335 return 1;
3336}
3337
3338static int
3339compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3340{
3341 int op = 0, slice_offset = 0, stack_count = 0;
3342
3343 assert(s->v.Slice.step == NULL);
3344 if (s->v.Slice.lower) {
3345 slice_offset++;
3346 stack_count++;
3347 if (ctx != AugStore)
3348 VISIT(c, expr, s->v.Slice.lower);
3349 }
3350 if (s->v.Slice.upper) {
3351 slice_offset += 2;
3352 stack_count++;
3353 if (ctx != AugStore)
3354 VISIT(c, expr, s->v.Slice.upper);
3355 }
3356
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003357 if (ctx == AugLoad) {
3358 switch (stack_count) {
3359 case 0: ADDOP(c, DUP_TOP); break;
3360 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3361 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3362 }
3363 }
3364 else if (ctx == AugStore) {
3365 switch (stack_count) {
3366 case 0: ADDOP(c, ROT_TWO); break;
3367 case 1: ADDOP(c, ROT_THREE); break;
3368 case 2: ADDOP(c, ROT_FOUR); break;
3369 }
3370 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371
3372 switch (ctx) {
3373 case AugLoad: /* fall through to Load */
3374 case Load: op = SLICE; break;
3375 case AugStore:/* fall through to Store */
3376 case Store: op = STORE_SLICE; break;
3377 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003378 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003379 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003380 PyErr_SetString(PyExc_SystemError,
3381 "param invalid in simple slice");
3382 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383 }
3384
3385 ADDOP(c, op + slice_offset);
3386 return 1;
3387}
3388
3389static int
3390compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3391 expr_context_ty ctx)
3392{
3393 switch (s->kind) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 case Slice_kind:
3395 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003396 case Index_kind:
3397 VISIT(c, expr, s->v.Index.value);
3398 break;
3399 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003400 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003401 PyErr_SetString(PyExc_SystemError,
3402 "extended slice invalid in nested slice");
3403 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003404 }
3405 return 1;
3406}
3407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408static int
3409compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3410{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003411 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003413 case Index_kind:
3414 kindname = "index";
3415 if (ctx != AugStore) {
3416 VISIT(c, expr, s->v.Index.value);
3417 }
3418 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003419 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003420 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421 if (!s->v.Slice.step)
3422 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003423 if (ctx != AugStore) {
3424 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 return 0;
3426 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003427 break;
3428 case ExtSlice_kind:
3429 kindname = "extended slice";
3430 if (ctx != AugStore) {
3431 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3432 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003433 slice_ty sub = (slice_ty)asdl_seq_GET(
3434 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003435 if (!compiler_visit_nested_slice(c, sub, ctx))
3436 return 0;
3437 }
3438 ADDOP_I(c, BUILD_TUPLE, n);
3439 }
3440 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003441 default:
3442 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003443 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003444 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003445 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003446 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447}
3448
Thomas Wouters89f507f2006-12-13 04:49:30 +00003449/* End of the compiler section, beginning of the assembler section */
3450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003451/* do depth-first search of basic block graph, starting with block.
3452 post records the block indices in post-order.
3453
3454 XXX must handle implicit jumps from one block to next
3455*/
3456
Thomas Wouters89f507f2006-12-13 04:49:30 +00003457struct assembler {
3458 PyObject *a_bytecode; /* string containing bytecode */
3459 int a_offset; /* offset into bytecode */
3460 int a_nblocks; /* number of reachable blocks */
3461 basicblock **a_postorder; /* list of blocks in dfs postorder */
3462 PyObject *a_lnotab; /* string containing lnotab */
3463 int a_lnotab_off; /* offset into lnotab */
3464 int a_lineno; /* last lineno of emitted instruction */
3465 int a_lineno_off; /* bytecode offset of last lineno */
3466};
3467
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003468static void
3469dfs(struct compiler *c, basicblock *b, struct assembler *a)
3470{
3471 int i;
3472 struct instr *instr = NULL;
3473
3474 if (b->b_seen)
3475 return;
3476 b->b_seen = 1;
3477 if (b->b_next != NULL)
3478 dfs(c, b->b_next, a);
3479 for (i = 0; i < b->b_iused; i++) {
3480 instr = &b->b_instr[i];
3481 if (instr->i_jrel || instr->i_jabs)
3482 dfs(c, instr->i_target, a);
3483 }
3484 a->a_postorder[a->a_nblocks++] = b;
3485}
3486
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003487static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003488stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3489{
3490 int i;
3491 struct instr *instr;
3492 if (b->b_seen || b->b_startdepth >= depth)
3493 return maxdepth;
3494 b->b_seen = 1;
3495 b->b_startdepth = depth;
3496 for (i = 0; i < b->b_iused; i++) {
3497 instr = &b->b_instr[i];
3498 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3499 if (depth > maxdepth)
3500 maxdepth = depth;
3501 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3502 if (instr->i_jrel || instr->i_jabs) {
3503 maxdepth = stackdepth_walk(c, instr->i_target,
3504 depth, maxdepth);
3505 if (instr->i_opcode == JUMP_ABSOLUTE ||
3506 instr->i_opcode == JUMP_FORWARD) {
3507 goto out; /* remaining code is dead */
3508 }
3509 }
3510 }
3511 if (b->b_next)
3512 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3513out:
3514 b->b_seen = 0;
3515 return maxdepth;
3516}
3517
3518/* Find the flow path that needs the largest stack. We assume that
3519 * cycles in the flow graph have no net effect on the stack depth.
3520 */
3521static int
3522stackdepth(struct compiler *c)
3523{
3524 basicblock *b, *entryblock;
3525 entryblock = NULL;
3526 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3527 b->b_seen = 0;
3528 b->b_startdepth = INT_MIN;
3529 entryblock = b;
3530 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003531 if (!entryblock)
3532 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 return stackdepth_walk(c, entryblock, 0, 0);
3534}
3535
3536static int
3537assemble_init(struct assembler *a, int nblocks, int firstlineno)
3538{
3539 memset(a, 0, sizeof(struct assembler));
3540 a->a_lineno = firstlineno;
3541 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3542 if (!a->a_bytecode)
3543 return 0;
3544 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3545 if (!a->a_lnotab)
3546 return 0;
3547 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003548 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003549 if (!a->a_postorder) {
3550 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 return 1;
3554}
3555
3556static void
3557assemble_free(struct assembler *a)
3558{
3559 Py_XDECREF(a->a_bytecode);
3560 Py_XDECREF(a->a_lnotab);
3561 if (a->a_postorder)
3562 PyObject_Free(a->a_postorder);
3563}
3564
3565/* Return the size of a basic block in bytes. */
3566
3567static int
3568instrsize(struct instr *instr)
3569{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003570 if (!instr->i_hasarg)
3571 return 1;
3572 if (instr->i_oparg > 0xffff)
3573 return 6;
3574 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575}
3576
3577static int
3578blocksize(basicblock *b)
3579{
3580 int i;
3581 int size = 0;
3582
3583 for (i = 0; i < b->b_iused; i++)
3584 size += instrsize(&b->b_instr[i]);
3585 return size;
3586}
3587
3588/* All about a_lnotab.
3589
3590c_lnotab is an array of unsigned bytes disguised as a Python string.
3591It is used to map bytecode offsets to source code line #s (when needed
3592for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003593
Tim Peters2a7f3842001-06-09 09:26:21 +00003594The array is conceptually a list of
3595 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003596pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003597
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003598 byte code offset source code line number
3599 0 1
3600 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003601 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003602 350 307
3603 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003604
3605The first trick is that these numbers aren't stored, only the increments
3606from one row to the next (this doesn't really work, but it's a start):
3607
3608 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3609
3610The second trick is that an unsigned byte can't hold negative values, or
3611values larger than 255, so (a) there's a deep assumption that byte code
3612offsets and their corresponding line #s both increase monotonically, and (b)
3613if at least one column jumps by more than 255 from one row to the next, more
3614than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003615from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003616part. A user of c_lnotab desiring to find the source line number
3617corresponding to a bytecode address A should do something like this
3618
3619 lineno = addr = 0
3620 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 addr += addr_incr
3622 if addr > A:
3623 return lineno
3624 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003625
3626In order for this to work, when the addr field increments by more than 255,
3627the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003628increment is < 256. So, in the example above, assemble_lnotab (it used
3629to be called com_set_lineno) should not (as was actually done until 2.2)
3630expand 300, 300 to 255, 255, 45, 45,
3631 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003632*/
3633
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003634static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003636{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 int d_bytecode, d_lineno;
3638 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003639 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640
3641 d_bytecode = a->a_offset - a->a_lineno_off;
3642 d_lineno = i->i_lineno - a->a_lineno;
3643
3644 assert(d_bytecode >= 0);
3645 assert(d_lineno >= 0);
3646
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003647 /* XXX(nnorwitz): is there a better way to handle this?
3648 for loops are special, we want to be able to trace them
3649 each time around, so we need to set an extra line number. */
3650 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003651 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003652
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003654 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 nbytes = a->a_lnotab_off + 2 * ncodes;
3656 len = PyString_GET_SIZE(a->a_lnotab);
3657 if (nbytes >= len) {
3658 if (len * 2 < nbytes)
3659 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003660 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661 len *= 2;
3662 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3663 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003664 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003665 lnotab = (unsigned char *)
3666 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003667 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 *lnotab++ = 255;
3669 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003670 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 d_bytecode -= ncodes * 255;
3672 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003673 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 assert(d_bytecode <= 255);
3675 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003676 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677 nbytes = a->a_lnotab_off + 2 * ncodes;
3678 len = PyString_GET_SIZE(a->a_lnotab);
3679 if (nbytes >= len) {
3680 if (len * 2 < nbytes)
3681 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003682 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 len *= 2;
3684 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3685 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003686 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003687 lnotab = (unsigned char *)
3688 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003690 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003692 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003693 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003694 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003696 d_lineno -= ncodes * 255;
3697 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003698 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003699
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 len = PyString_GET_SIZE(a->a_lnotab);
3701 if (a->a_lnotab_off + 2 >= len) {
3702 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003703 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003704 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003705 lnotab = (unsigned char *)
3706 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003707
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708 a->a_lnotab_off += 2;
3709 if (d_bytecode) {
3710 *lnotab++ = d_bytecode;
3711 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003712 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003713 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714 *lnotab++ = 0;
3715 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003716 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717 a->a_lineno = i->i_lineno;
3718 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003719 return 1;
3720}
3721
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722/* assemble_emit()
3723 Extend the bytecode with a new instruction.
3724 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003725*/
3726
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003727static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003729{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003730 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003731 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732 char *code;
3733
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003734 size = instrsize(i);
3735 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003737 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003738 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003740 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 if (a->a_offset + size >= len) {
3742 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003743 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003744 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3746 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003747 if (size == 6) {
3748 assert(i->i_hasarg);
3749 *code++ = (char)EXTENDED_ARG;
3750 *code++ = ext & 0xff;
3751 *code++ = ext >> 8;
3752 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003755 if (i->i_hasarg) {
3756 assert(size == 3 || size == 6);
3757 *code++ = arg & 0xff;
3758 *code++ = arg >> 8;
3759 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003761}
3762
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003763static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003765{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003767 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003768 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003769
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 /* Compute the size of each block and fixup jump args.
3771 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003772start:
3773 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003775 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 bsize = blocksize(b);
3777 b->b_offset = totsize;
3778 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003779 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003780 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3782 bsize = b->b_offset;
3783 for (i = 0; i < b->b_iused; i++) {
3784 struct instr *instr = &b->b_instr[i];
3785 /* Relative jumps are computed relative to
3786 the instruction pointer after fetching
3787 the jump instruction.
3788 */
3789 bsize += instrsize(instr);
3790 if (instr->i_jabs)
3791 instr->i_oparg = instr->i_target->b_offset;
3792 else if (instr->i_jrel) {
3793 int delta = instr->i_target->b_offset - bsize;
3794 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003795 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003796 else
3797 continue;
3798 if (instr->i_oparg > 0xffff)
3799 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003800 }
3801 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003802
3803 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003804 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003805 with a better solution.
3806
3807 In the meantime, should the goto be dropped in favor
3808 of a loop?
3809
3810 The issue is that in the first loop blocksize() is called
3811 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003812 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003813 i_oparg is calculated in the second loop above.
3814
3815 So we loop until we stop seeing new EXTENDED_ARGs.
3816 The only EXTENDED_ARGs that could be popping up are
3817 ones in jump instructions. So this should converge
3818 fairly quickly.
3819 */
3820 if (last_extended_arg_count != extended_arg_count) {
3821 last_extended_arg_count = extended_arg_count;
3822 goto start;
3823 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003824}
3825
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003826static PyObject *
3827dict_keys_inorder(PyObject *dict, int offset)
3828{
3829 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003830 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003831
3832 tuple = PyTuple_New(size);
3833 if (tuple == NULL)
3834 return NULL;
3835 while (PyDict_Next(dict, &pos, &k, &v)) {
3836 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003837 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003838 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003839 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003840 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003841 PyTuple_SET_ITEM(tuple, i - offset, k);
3842 }
3843 return tuple;
3844}
3845
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003846static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003848{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 PySTEntryObject *ste = c->u->u_ste;
3850 int flags = 0, n;
3851 if (ste->ste_type != ModuleBlock)
3852 flags |= CO_NEWLOCALS;
3853 if (ste->ste_type == FunctionBlock) {
3854 if (!ste->ste_unoptimized)
3855 flags |= CO_OPTIMIZED;
3856 if (ste->ste_nested)
3857 flags |= CO_NESTED;
3858 if (ste->ste_generator)
3859 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 if (ste->ste_varargs)
3862 flags |= CO_VARARGS;
3863 if (ste->ste_varkeywords)
3864 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003865 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003867
3868 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003869 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003870
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871 n = PyDict_Size(c->u->u_freevars);
3872 if (n < 0)
3873 return -1;
3874 if (n == 0) {
3875 n = PyDict_Size(c->u->u_cellvars);
3876 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003877 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 if (n == 0) {
3879 flags |= CO_NOFREE;
3880 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003881 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003882
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003883 return flags;
3884}
3885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886static PyCodeObject *
3887makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003888{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 PyObject *tmp;
3890 PyCodeObject *co = NULL;
3891 PyObject *consts = NULL;
3892 PyObject *names = NULL;
3893 PyObject *varnames = NULL;
3894 PyObject *filename = NULL;
3895 PyObject *name = NULL;
3896 PyObject *freevars = NULL;
3897 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003898 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 tmp = dict_keys_inorder(c->u->u_consts, 0);
3902 if (!tmp)
3903 goto error;
3904 consts = PySequence_List(tmp); /* optimize_code requires a list */
3905 Py_DECREF(tmp);
3906
3907 names = dict_keys_inorder(c->u->u_names, 0);
3908 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3909 if (!consts || !names || !varnames)
3910 goto error;
3911
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003912 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3913 if (!cellvars)
3914 goto error;
3915 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3916 if (!freevars)
3917 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 filename = PyString_FromString(c->c_filename);
3919 if (!filename)
3920 goto error;
3921
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003922 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 flags = compute_code_flags(c);
3924 if (flags < 0)
3925 goto error;
3926
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003927 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003928 if (!bytecode)
3929 goto error;
3930
3931 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3932 if (!tmp)
3933 goto error;
3934 Py_DECREF(consts);
3935 consts = tmp;
3936
Guido van Rossum4f72a782006-10-27 23:31:49 +00003937 co = PyCode_New(c->u->u_argcount, c->u->u_kwonlyargcount,
3938 nlocals, stackdepth(c), flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939 bytecode, consts, names, varnames,
3940 freevars, cellvars,
3941 filename, c->u->u_name,
3942 c->u->u_firstlineno,
3943 a->a_lnotab);
3944 error:
3945 Py_XDECREF(consts);
3946 Py_XDECREF(names);
3947 Py_XDECREF(varnames);
3948 Py_XDECREF(filename);
3949 Py_XDECREF(name);
3950 Py_XDECREF(freevars);
3951 Py_XDECREF(cellvars);
3952 Py_XDECREF(bytecode);
3953 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003954}
3955
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003956
3957/* For debugging purposes only */
3958#if 0
3959static void
3960dump_instr(const struct instr *i)
3961{
3962 const char *jrel = i->i_jrel ? "jrel " : "";
3963 const char *jabs = i->i_jabs ? "jabs " : "";
3964 char arg[128];
3965
3966 *arg = '\0';
3967 if (i->i_hasarg)
3968 sprintf(arg, "arg: %d ", i->i_oparg);
3969
3970 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3971 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3972}
3973
3974static void
3975dump_basicblock(const basicblock *b)
3976{
3977 const char *seen = b->b_seen ? "seen " : "";
3978 const char *b_return = b->b_return ? "return " : "";
3979 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3980 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3981 if (b->b_instr) {
3982 int i;
3983 for (i = 0; i < b->b_iused; i++) {
3984 fprintf(stderr, " [%02d] ", i);
3985 dump_instr(b->b_instr + i);
3986 }
3987 }
3988}
3989#endif
3990
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991static PyCodeObject *
3992assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003993{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994 basicblock *b, *entryblock;
3995 struct assembler a;
3996 int i, j, nblocks;
3997 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003999 /* Make sure every block that falls off the end returns None.
4000 XXX NEXT_BLOCK() isn't quite right, because if the last
4001 block ends with a jump or return b_next shouldn't set.
4002 */
4003 if (!c->u->u_curblock->b_return) {
4004 NEXT_BLOCK(c);
4005 if (addNone)
4006 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4007 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004008 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004009
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004010 nblocks = 0;
4011 entryblock = NULL;
4012 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4013 nblocks++;
4014 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004015 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004016
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004017 /* Set firstlineno if it wasn't explicitly set. */
4018 if (!c->u->u_firstlineno) {
4019 if (entryblock && entryblock->b_instr)
4020 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4021 else
4022 c->u->u_firstlineno = 1;
4023 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4025 goto error;
4026 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004027
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004028 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004029 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004030
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004031 /* Emit code in reverse postorder from dfs. */
4032 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004033 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004034 for (j = 0; j < b->b_iused; j++)
4035 if (!assemble_emit(&a, &b->b_instr[j]))
4036 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004037 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004038
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004039 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4040 goto error;
4041 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4042 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004044 co = makecode(c, &a);
4045 error:
4046 assemble_free(&a);
4047 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004048}