blob: 9fa3cb184663f25bbee8b5c40984e24d25ab7541 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
Neal Norwitzf733a012006-10-29 18:30:10 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Neal Norwitzf733a012006-10-29 18:30:10 +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
Neal Norwitzf733a012006-10-29 18:30:10 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000026#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000027#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000028#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000032#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Guido van Rossum8e793d91997-03-03 19:13:14 +000035int Py_OptimizeFlag = 0;
36
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000037#define DEFAULT_BLOCK_SIZE 16
38#define DEFAULT_BLOCKS 8
39#define DEFAULT_CODE_SIZE 128
40#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000041
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000042struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000043 unsigned i_jabs : 1;
44 unsigned i_jrel : 1;
45 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 unsigned char i_opcode;
47 int i_oparg;
48 struct basicblock_ *i_target; /* target block (if jump instruction) */
49 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000050};
51
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000052typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000053 /* Each basicblock in a compilation unit is linked via b_list in the
54 reverse order that the block are allocated. b_list points to the next
55 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000056 struct basicblock_ *b_list;
57 /* number of instructions used */
58 int b_iused;
59 /* length of instruction array (b_instr) */
60 int b_ialloc;
61 /* pointer to an array of instructions, initially NULL */
62 struct instr *b_instr;
63 /* If b_next is non-NULL, it is a pointer to the next
64 block reached by normal control flow. */
65 struct basicblock_ *b_next;
66 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000067 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000068 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000069 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000070 /* depth of stack upon entry of block, computed by stackdepth() */
71 int b_startdepth;
72 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000073 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074} basicblock;
75
76/* fblockinfo tracks the current frame block.
77
Jeremy Hyltone9357b22006-03-01 15:47:05 +000078A frame block is used to handle loops, try/except, and try/finally.
79It's called a frame block to distinguish it from a basic block in the
80compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081*/
82
83enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
84
85struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000087 basicblock *fb_block;
88};
89
90/* The following items change on entry and exit of code blocks.
91 They must be saved and restored when returning to a block.
92*/
93struct compiler_unit {
94 PySTEntryObject *u_ste;
95
96 PyObject *u_name;
97 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +000098 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000099 the argument for opcodes that refer to those collections.
100 */
101 PyObject *u_consts; /* all constants */
102 PyObject *u_names; /* all names */
103 PyObject *u_varnames; /* local variables */
104 PyObject *u_cellvars; /* cell variables */
105 PyObject *u_freevars; /* free variables */
106
107 PyObject *u_private; /* for private name mangling */
108
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000109 int u_argcount; /* number of arguments for block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000110 /* Pointer to the most recently allocated block. By following b_list
111 members, you can reach all early allocated blocks. */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000112 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000113 basicblock *u_curblock; /* pointer to current block */
Neal Norwitzf733a012006-10-29 18:30:10 +0000114 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
116 int u_nfblocks;
117 struct fblockinfo u_fblock[CO_MAXBLOCKS];
118
119 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000120 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 bool u_lineno_set; /* boolean to indicate whether instr
122 has been generated with current lineno */
123};
124
125/* This struct captures the global state of a compilation.
126
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000127The u pointer points to the current compilation unit, while units
128for enclosing blocks are stored in c_stack. The u and c_stack are
129managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000130*/
131
132struct compiler {
133 const char *c_filename;
134 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000136 PyCompilerFlags *c_flags;
137
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000138 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000139 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000141 struct compiler_unit *u; /* compiler state for current block */
142 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145};
146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000147static int compiler_enter_scope(struct compiler *, identifier, void *, int);
148static void compiler_free(struct compiler *);
149static basicblock *compiler_new_block(struct compiler *);
150static int compiler_next_instr(struct compiler *, basicblock *);
151static int compiler_addop(struct compiler *, int);
152static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
153static int compiler_addop_i(struct compiler *, int, int);
154static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000155static basicblock *compiler_use_new_block(struct compiler *);
156static int compiler_error(struct compiler *, const char *);
157static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
158
159static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
160static int compiler_visit_stmt(struct compiler *, stmt_ty);
161static int compiler_visit_keyword(struct compiler *, keyword_ty);
162static int compiler_visit_expr(struct compiler *, expr_ty);
163static int compiler_augassign(struct compiler *, stmt_ty);
164static int compiler_visit_slice(struct compiler *, slice_ty,
165 expr_context_ty);
166
167static int compiler_push_fblock(struct compiler *, enum fblocktype,
168 basicblock *);
169static void compiler_pop_fblock(struct compiler *, enum fblocktype,
170 basicblock *);
Jeremy Hylton82271f12006-10-04 02:24:52 +0000171/* Returns true if there is a loop on the fblock stack. */
172static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173
174static int inplace_binop(struct compiler *, operator_ty);
175static int expr_constant(expr_ty e);
176
Guido van Rossumc2e20742006-02-27 22:32:47 +0000177static int compiler_with(struct compiler *, stmt_ty);
178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179static PyCodeObject *assemble(struct compiler *, int addNone);
180static PyObject *__doc__;
181
182PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000183_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000184{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185 /* Name mangling: __private becomes _classname__private.
186 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000187 const char *p, *name = PyString_AsString(ident);
188 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000189 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000190 if (privateobj == NULL || !PyString_Check(privateobj) ||
191 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000192 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000194 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000195 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196 nlen = strlen(name);
197 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000198 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201 /* Strip leading underscores from class name */
202 while (*p == '_')
203 p++;
204 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000205 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000207 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
210 if (!ident)
211 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000213 buffer = PyString_AS_STRING(ident);
214 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 strncpy(buffer+1, p, plen);
216 strcpy(buffer+1+plen, name);
217 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000218}
219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220static int
221compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000222{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 c->c_stack = PyList_New(0);
226 if (!c->c_stack)
227 return 0;
228
229 return 1;
230}
231
232PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000233PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000234 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235{
236 struct compiler c;
237 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000238 PyCompilerFlags local_flags;
239 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000241 if (!__doc__) {
242 __doc__ = PyString_InternFromString("__doc__");
243 if (!__doc__)
244 return NULL;
245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246
247 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000248 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000250 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251 c.c_future = PyFuture_FromAST(mod, filename);
252 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000253 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 local_flags.cf_flags = 0;
256 flags = &local_flags;
257 }
258 merged = c.c_future->ff_features | flags->cf_flags;
259 c.c_future->ff_features = merged;
260 flags->cf_flags = merged;
261 c.c_flags = flags;
262 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 c.c_st = PySymtable_Build(mod, filename, c.c_future);
265 if (c.c_st == NULL) {
266 if (!PyErr_Occurred())
267 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000268 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000269 }
270
271 /* XXX initialize to NULL for now, need to handle */
272 c.c_encoding = NULL;
273
274 co = compiler_mod(&c, mod);
275
Thomas Wouters1175c432006-02-27 22:49:54 +0000276 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000278 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000279 return co;
280}
281
282PyCodeObject *
283PyNode_Compile(struct _node *n, const char *filename)
284{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000285 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000286 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000287 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000288 if (!arena)
289 return NULL;
290 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000291 if (mod)
292 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000293 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000294 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000295}
296
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000297static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000299{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300 if (c->c_st)
301 PySymtable_Free(c->c_st);
302 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000303 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000305}
306
Guido van Rossum79f25d91997-04-29 20:08:16 +0000307static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000309{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000311 PyObject *v, *k;
312 PyObject *dict = PyDict_New();
313 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000314
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315 n = PyList_Size(list);
316 for (i = 0; i < n; i++) {
317 v = PyInt_FromLong(i);
318 if (!v) {
319 Py_DECREF(dict);
320 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000321 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000322 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000323 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
325 Py_XDECREF(k);
326 Py_DECREF(v);
327 Py_DECREF(dict);
328 return NULL;
329 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000330 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000332 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 return dict;
334}
335
336/* Return new dict containing names from src that match scope(s).
337
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000338src is a symbol table dictionary. If the scope of a name matches
339either scope_type or flag is set, insert it into the new dict. The
340values are integers, starting at offset and increasing by one for
341each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342*/
343
344static PyObject *
345dictbytype(PyObject *src, int scope_type, int flag, int offset)
346{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000347 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348 PyObject *k, *v, *dest = PyDict_New();
349
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000350 assert(offset >= 0);
351 if (dest == NULL)
352 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353
354 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355 /* XXX this should probably be a macro in symtable.h */
356 assert(PyInt_Check(v));
357 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
360 PyObject *tuple, *item = PyInt_FromLong(i);
361 if (item == NULL) {
362 Py_DECREF(dest);
363 return NULL;
364 }
365 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000366 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
368 Py_DECREF(item);
369 Py_DECREF(dest);
370 Py_XDECREF(tuple);
371 return NULL;
372 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000373 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000374 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376 }
377 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000378}
379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000380static void
381compiler_unit_check(struct compiler_unit *u)
382{
383 basicblock *block;
384 for (block = u->u_blocks; block != NULL; block = block->b_list) {
385 assert(block != (void *)0xcbcbcbcb);
386 assert(block != (void *)0xfbfbfbfb);
387 assert(block != (void *)0xdbdbdbdb);
388 if (block->b_instr != NULL) {
389 assert(block->b_ialloc > 0);
390 assert(block->b_iused > 0);
391 assert(block->b_ialloc >= block->b_iused);
392 }
393 else {
394 assert (block->b_iused == 0);
395 assert (block->b_ialloc == 0);
396 }
397 }
398}
399
400static void
401compiler_unit_free(struct compiler_unit *u)
402{
403 basicblock *b, *next;
404
405 compiler_unit_check(u);
406 b = u->u_blocks;
407 while (b != NULL) {
408 if (b->b_instr)
409 PyObject_Free((void *)b->b_instr);
410 next = b->b_list;
411 PyObject_Free((void *)b);
412 b = next;
413 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000414 Py_CLEAR(u->u_ste);
415 Py_CLEAR(u->u_name);
416 Py_CLEAR(u->u_consts);
417 Py_CLEAR(u->u_names);
418 Py_CLEAR(u->u_varnames);
419 Py_CLEAR(u->u_freevars);
420 Py_CLEAR(u->u_cellvars);
421 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000422 PyObject_Free(u);
423}
424
425static int
426compiler_enter_scope(struct compiler *c, identifier name, void *key,
427 int lineno)
428{
429 struct compiler_unit *u;
430
Anthony Baxter7b782b62006-04-11 12:01:56 +0000431 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
432 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000433 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000434 PyErr_NoMemory();
435 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000436 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000437 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438 u->u_argcount = 0;
439 u->u_ste = PySymtable_Lookup(c->c_st, key);
440 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000441 compiler_unit_free(u);
442 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443 }
444 Py_INCREF(name);
445 u->u_name = name;
446 u->u_varnames = list2dict(u->u_ste->ste_varnames);
447 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +0000448 if (!u->u_varnames || !u->u_cellvars) {
449 compiler_unit_free(u);
450 return 0;
451 }
452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000454 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +0000455 if (!u->u_freevars) {
456 compiler_unit_free(u);
457 return 0;
458 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000459
460 u->u_blocks = NULL;
461 u->u_tmpname = 0;
462 u->u_nfblocks = 0;
463 u->u_firstlineno = lineno;
464 u->u_lineno = 0;
465 u->u_lineno_set = false;
466 u->u_consts = PyDict_New();
467 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000468 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469 return 0;
470 }
471 u->u_names = PyDict_New();
472 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000473 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474 return 0;
475 }
476
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000477 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
479 /* Push the old compiler_unit on the stack. */
480 if (c->u) {
481 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000482 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
483 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000484 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000485 return 0;
486 }
487 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000488 u->u_private = c->u->u_private;
489 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490 }
491 c->u = u;
492
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000493 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000494 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495 return 0;
496
497 return 1;
498}
499
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000500static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501compiler_exit_scope(struct compiler *c)
502{
503 int n;
504 PyObject *wrapper;
505
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000506 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000507 compiler_unit_free(c->u);
508 /* Restore c->u to the parent unit. */
509 n = PyList_GET_SIZE(c->c_stack) - 1;
510 if (n >= 0) {
511 wrapper = PyList_GET_ITEM(c->c_stack, n);
512 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neal Norwitz87557cd2006-08-21 18:01:30 +0000513 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000514 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000516 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517 compiler_unit_check(c->u);
518 }
519 else
520 c->u = NULL;
521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000522}
523
Guido van Rossumc2e20742006-02-27 22:32:47 +0000524/* Allocate a new "anonymous" local variable.
525 Used by list comprehensions and with statements.
526*/
527
528static PyObject *
529compiler_new_tmpname(struct compiler *c)
530{
531 char tmpname[256];
532 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
533 return PyString_FromString(tmpname);
534}
535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536/* Allocate a new block and return a pointer to it.
537 Returns NULL on error.
538*/
539
540static basicblock *
541compiler_new_block(struct compiler *c)
542{
543 basicblock *b;
544 struct compiler_unit *u;
545
546 u = c->u;
547 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000548 if (b == NULL) {
549 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000550 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552 memset((void *)b, 0, sizeof(basicblock));
Neal Norwitzf733a012006-10-29 18:30:10 +0000553 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000554 b->b_list = u->u_blocks;
555 u->u_blocks = b;
556 return b;
557}
558
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559static basicblock *
560compiler_use_new_block(struct compiler *c)
561{
562 basicblock *block = compiler_new_block(c);
563 if (block == NULL)
564 return NULL;
565 c->u->u_curblock = block;
566 return block;
567}
568
569static basicblock *
570compiler_next_block(struct compiler *c)
571{
572 basicblock *block = compiler_new_block(c);
573 if (block == NULL)
574 return NULL;
575 c->u->u_curblock->b_next = block;
576 c->u->u_curblock = block;
577 return block;
578}
579
580static basicblock *
581compiler_use_next_block(struct compiler *c, basicblock *block)
582{
583 assert(block != NULL);
584 c->u->u_curblock->b_next = block;
585 c->u->u_curblock = block;
586 return block;
587}
588
589/* Returns the offset of the next instruction in the current block's
590 b_instr array. Resizes the b_instr as necessary.
591 Returns -1 on failure.
Neal Norwitzf733a012006-10-29 18:30:10 +0000592*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000593
594static int
595compiler_next_instr(struct compiler *c, basicblock *b)
596{
597 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000598 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +0000599 b->b_instr = (struct instr *)PyObject_Malloc(
600 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000601 if (b->b_instr == NULL) {
602 PyErr_NoMemory();
603 return -1;
604 }
605 b->b_ialloc = DEFAULT_BLOCK_SIZE;
606 memset((char *)b->b_instr, 0,
607 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000608 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000609 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000610 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611 size_t oldsize, newsize;
612 oldsize = b->b_ialloc * sizeof(struct instr);
613 newsize = oldsize << 1;
614 if (newsize == 0) {
615 PyErr_NoMemory();
616 return -1;
617 }
618 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000619 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +0000620 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000621 if (tmp == NULL) {
622 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000623 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000624 }
625 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
627 }
628 return b->b_iused++;
629}
630
Jeremy Hylton12603c42006-04-01 16:18:02 +0000631/* Set the i_lineno member of the instruction at offse off if the
632 line number for the current expression/statement (?) has not
633 already been set. If it has been set, the call has no effect.
634
635 Every time a new node is b
Neal Norwitzf733a012006-10-29 18:30:10 +0000636*/
Jeremy Hylton12603c42006-04-01 16:18:02 +0000637
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638static void
639compiler_set_lineno(struct compiler *c, int off)
640{
641 basicblock *b;
642 if (c->u->u_lineno_set)
643 return;
644 c->u->u_lineno_set = true;
645 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000646 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000647}
648
649static int
650opcode_stack_effect(int opcode, int oparg)
651{
652 switch (opcode) {
653 case POP_TOP:
654 return -1;
655 case ROT_TWO:
656 case ROT_THREE:
657 return 0;
658 case DUP_TOP:
659 return 1;
660 case ROT_FOUR:
661 return 0;
662
663 case UNARY_POSITIVE:
664 case UNARY_NEGATIVE:
665 case UNARY_NOT:
666 case UNARY_CONVERT:
667 case UNARY_INVERT:
668 return 0;
669
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000670 case LIST_APPEND:
671 return -2;
672
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673 case BINARY_POWER:
674 case BINARY_MULTIPLY:
675 case BINARY_DIVIDE:
676 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:
717 case INPLACE_DIVIDE:
718 case INPLACE_MODULO:
719 return -1;
720 case STORE_SUBSCR:
721 return -3;
722 case DELETE_SUBSCR:
723 return -2;
724
725 case BINARY_LSHIFT:
726 case BINARY_RSHIFT:
727 case BINARY_AND:
728 case BINARY_XOR:
729 case BINARY_OR:
730 return -1;
731 case INPLACE_POWER:
732 return -1;
733 case GET_ITER:
734 return 0;
735
736 case PRINT_EXPR:
737 return -1;
738 case PRINT_ITEM:
739 return -1;
740 case PRINT_NEWLINE:
741 return 0;
742 case PRINT_ITEM_TO:
743 return -2;
744 case PRINT_NEWLINE_TO:
745 return -1;
746 case INPLACE_LSHIFT:
747 case INPLACE_RSHIFT:
748 case INPLACE_AND:
749 case INPLACE_XOR:
750 case INPLACE_OR:
751 return -1;
752 case BREAK_LOOP:
753 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000754 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000755 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000756 case LOAD_LOCALS:
757 return 1;
758 case RETURN_VALUE:
759 return -1;
760 case IMPORT_STAR:
761 return -1;
762 case EXEC_STMT:
763 return -3;
764 case YIELD_VALUE:
765 return 0;
766
767 case POP_BLOCK:
768 return 0;
769 case END_FINALLY:
770 return -1; /* or -2 or -3 if exception occurred */
771 case BUILD_CLASS:
772 return -2;
773
774 case STORE_NAME:
775 return -1;
776 case DELETE_NAME:
777 return 0;
778 case UNPACK_SEQUENCE:
779 return oparg-1;
780 case FOR_ITER:
781 return 1;
782
783 case STORE_ATTR:
784 return -2;
785 case DELETE_ATTR:
786 return -1;
787 case STORE_GLOBAL:
788 return -1;
789 case DELETE_GLOBAL:
790 return 0;
791 case DUP_TOPX:
792 return oparg;
793 case LOAD_CONST:
794 return 1;
795 case LOAD_NAME:
796 return 1;
797 case BUILD_TUPLE:
798 case BUILD_LIST:
799 return 1-oparg;
800 case BUILD_MAP:
801 return 1;
802 case LOAD_ATTR:
803 return 0;
804 case COMPARE_OP:
805 return -1;
806 case IMPORT_NAME:
807 return 0;
808 case IMPORT_FROM:
809 return 1;
810
811 case JUMP_FORWARD:
812 case JUMP_IF_FALSE:
813 case JUMP_IF_TRUE:
814 case JUMP_ABSOLUTE:
815 return 0;
816
817 case LOAD_GLOBAL:
818 return 1;
819
820 case CONTINUE_LOOP:
821 return 0;
822 case SETUP_LOOP:
823 return 0;
824 case SETUP_EXCEPT:
825 case SETUP_FINALLY:
826 return 3; /* actually pushed by an exception */
827
828 case LOAD_FAST:
829 return 1;
830 case STORE_FAST:
831 return -1;
832 case DELETE_FAST:
833 return 0;
834
835 case RAISE_VARARGS:
836 return -oparg;
837#define NARGS(o) (((o) % 256) + 2*((o) / 256))
838 case CALL_FUNCTION:
839 return -NARGS(oparg);
840 case CALL_FUNCTION_VAR:
841 case CALL_FUNCTION_KW:
842 return -NARGS(oparg)-1;
843 case CALL_FUNCTION_VAR_KW:
844 return -NARGS(oparg)-2;
845#undef NARGS
846 case MAKE_FUNCTION:
847 return -oparg;
848 case BUILD_SLICE:
849 if (oparg == 3)
850 return -2;
851 else
852 return -1;
853
854 case MAKE_CLOSURE:
855 return -oparg;
856 case LOAD_CLOSURE:
857 return 1;
858 case LOAD_DEREF:
859 return 1;
860 case STORE_DEREF:
861 return -1;
862 default:
863 fprintf(stderr, "opcode = %d\n", opcode);
864 Py_FatalError("opcode_stack_effect()");
865
866 }
867 return 0; /* not reachable */
868}
869
870/* Add an opcode with no argument.
871 Returns 0 on failure, 1 on success.
872*/
873
874static int
875compiler_addop(struct compiler *c, int opcode)
876{
877 basicblock *b;
878 struct instr *i;
879 int off;
880 off = compiler_next_instr(c, c->u->u_curblock);
881 if (off < 0)
882 return 0;
883 b = c->u->u_curblock;
884 i = &b->b_instr[off];
885 i->i_opcode = opcode;
886 i->i_hasarg = 0;
887 if (opcode == RETURN_VALUE)
888 b->b_return = 1;
889 compiler_set_lineno(c, off);
890 return 1;
891}
892
893static int
894compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
895{
896 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000898
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000899 /* necessary to make sure types aren't coerced (e.g., int and long) */
900 t = PyTuple_Pack(2, o, o->ob_type);
901 if (t == NULL)
902 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903
904 v = PyDict_GetItem(dict, t);
905 if (!v) {
906 arg = PyDict_Size(dict);
907 v = PyInt_FromLong(arg);
908 if (!v) {
909 Py_DECREF(t);
910 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000911 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000912 if (PyDict_SetItem(dict, t, v) < 0) {
913 Py_DECREF(t);
914 Py_DECREF(v);
915 return -1;
916 }
917 Py_DECREF(v);
918 }
919 else
920 arg = PyInt_AsLong(v);
921 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000922 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000923}
924
925static int
926compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
927 PyObject *o)
928{
929 int arg = compiler_add_o(c, dict, o);
930 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000931 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932 return compiler_addop_i(c, opcode, arg);
933}
934
935static int
936compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000937 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938{
939 int arg;
940 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
941 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000942 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943 arg = compiler_add_o(c, dict, mangled);
944 Py_DECREF(mangled);
945 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000946 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000947 return compiler_addop_i(c, opcode, arg);
948}
949
950/* Add an opcode with an integer argument.
951 Returns 0 on failure, 1 on success.
952*/
953
954static int
955compiler_addop_i(struct compiler *c, int opcode, int oparg)
956{
957 struct instr *i;
958 int off;
959 off = compiler_next_instr(c, c->u->u_curblock);
960 if (off < 0)
961 return 0;
962 i = &c->u->u_curblock->b_instr[off];
963 i->i_opcode = opcode;
964 i->i_oparg = oparg;
965 i->i_hasarg = 1;
966 compiler_set_lineno(c, off);
967 return 1;
968}
969
970static int
971compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
972{
973 struct instr *i;
974 int off;
975
976 assert(b != NULL);
977 off = compiler_next_instr(c, c->u->u_curblock);
978 if (off < 0)
979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 i = &c->u->u_curblock->b_instr[off];
981 i->i_opcode = opcode;
982 i->i_target = b;
983 i->i_hasarg = 1;
984 if (absolute)
985 i->i_jabs = 1;
986 else
987 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +0000988 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return 1;
990}
991
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000992/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
993 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994 it as the current block. NEXT_BLOCK() also creates an implicit jump
995 from the current block to the new block.
996*/
997
Neal Norwitzf733a012006-10-29 18:30:10 +0000998/* The returns inside these macros make it impossible to decref objects
999 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000*/
1001
1002
1003#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 if (compiler_use_new_block((C)) == NULL) \
1005 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006}
1007
1008#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001009 if (compiler_next_block((C)) == NULL) \
1010 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001011}
1012
1013#define ADDOP(C, OP) { \
1014 if (!compiler_addop((C), (OP))) \
1015 return 0; \
1016}
1017
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001018#define ADDOP_IN_SCOPE(C, OP) { \
1019 if (!compiler_addop((C), (OP))) { \
1020 compiler_exit_scope(c); \
1021 return 0; \
1022 } \
1023}
1024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025#define ADDOP_O(C, OP, O, TYPE) { \
1026 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1027 return 0; \
1028}
1029
1030#define ADDOP_NAME(C, OP, O, TYPE) { \
1031 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1032 return 0; \
1033}
1034
1035#define ADDOP_I(C, OP, O) { \
1036 if (!compiler_addop_i((C), (OP), (O))) \
1037 return 0; \
1038}
1039
1040#define ADDOP_JABS(C, OP, O) { \
1041 if (!compiler_addop_j((C), (OP), (O), 1)) \
1042 return 0; \
1043}
1044
1045#define ADDOP_JREL(C, OP, O) { \
1046 if (!compiler_addop_j((C), (OP), (O), 0)) \
1047 return 0; \
1048}
1049
1050/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1051 the ASDL name to synthesize the name of the C type and the visit function.
1052*/
1053
1054#define VISIT(C, TYPE, V) {\
1055 if (!compiler_visit_ ## TYPE((C), (V))) \
1056 return 0; \
1057}
1058
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001059#define VISIT_IN_SCOPE(C, TYPE, V) {\
1060 if (!compiler_visit_ ## TYPE((C), (V))) { \
1061 compiler_exit_scope(c); \
1062 return 0; \
1063 } \
1064}
1065
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066#define VISIT_SLICE(C, V, CTX) {\
1067 if (!compiler_visit_slice((C), (V), (CTX))) \
1068 return 0; \
1069}
1070
1071#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001072 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001074 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001075 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001076 if (!compiler_visit_ ## TYPE((C), elt)) \
1077 return 0; \
1078 } \
1079}
1080
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001081#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001082 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001083 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001084 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001085 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001086 if (!compiler_visit_ ## TYPE((C), elt)) { \
1087 compiler_exit_scope(c); \
1088 return 0; \
1089 } \
1090 } \
1091}
1092
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093static int
1094compiler_isdocstring(stmt_ty s)
1095{
1096 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 return s->v.Expr.value->kind == Str_kind;
1099}
1100
1101/* Compile a sequence of statements, checking for a docstring. */
1102
1103static int
1104compiler_body(struct compiler *c, asdl_seq *stmts)
1105{
1106 int i = 0;
1107 stmt_ty st;
1108
1109 if (!asdl_seq_LEN(stmts))
1110 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001111 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001112 if (compiler_isdocstring(st)) {
1113 i = 1;
1114 VISIT(c, expr, st->v.Expr.value);
1115 if (!compiler_nameop(c, __doc__, Store))
1116 return 0;
1117 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001118 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001119 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return 1;
1121}
1122
1123static PyCodeObject *
1124compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001125{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001126 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001127 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 static PyObject *module;
1129 if (!module) {
1130 module = PyString_FromString("<module>");
1131 if (!module)
1132 return NULL;
1133 }
Neal Norwitzed657552006-07-10 00:04:44 +00001134 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1135 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001136 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137 switch (mod->kind) {
1138 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001139 if (!compiler_body(c, mod->v.Module.body)) {
1140 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001142 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 break;
1144 case Interactive_kind:
1145 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001146 VISIT_SEQ_IN_SCOPE(c, stmt,
1147 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001148 break;
1149 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001150 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 break;
1153 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001154 PyErr_SetString(PyExc_SystemError,
1155 "suite should not be possible");
1156 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001157 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001158 PyErr_Format(PyExc_SystemError,
1159 "module kind %d should not be possible",
1160 mod->kind);
1161 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001163 co = assemble(c, addNone);
1164 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001165 return co;
1166}
1167
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168/* The test for LOCAL must come before the test for FREE in order to
1169 handle classes where name is both local and free. The local var is
1170 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001171*/
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173static int
1174get_ref_type(struct compiler *c, PyObject *name)
1175{
1176 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001177 if (scope == 0) {
1178 char buf[350];
1179 PyOS_snprintf(buf, sizeof(buf),
1180 "unknown scope for %.100s in %.100s(%s) in %s\n"
1181 "symbols: %s\nlocals: %s\nglobals: %s\n",
1182 PyString_AS_STRING(name),
1183 PyString_AS_STRING(c->u->u_name),
1184 PyObject_REPR(c->u->u_ste->ste_id),
1185 c->c_filename,
1186 PyObject_REPR(c->u->u_ste->ste_symbols),
1187 PyObject_REPR(c->u->u_varnames),
1188 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001190 Py_FatalError(buf);
1191 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001192
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001193 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194}
1195
1196static int
1197compiler_lookup_arg(PyObject *dict, PyObject *name)
1198{
1199 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001200 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001202 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001204 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001206 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001207 return PyInt_AS_LONG(v);
1208}
1209
1210static int
1211compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1212{
1213 int i, free = PyCode_GetNumFree(co);
1214 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1216 ADDOP_I(c, MAKE_FUNCTION, args);
1217 return 1;
1218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 for (i = 0; i < free; ++i) {
1220 /* Bypass com_addop_varname because it will generate
1221 LOAD_DEREF but LOAD_CLOSURE is needed.
1222 */
1223 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1224 int arg, reftype;
1225
1226 /* Special case: If a class contains a method with a
1227 free variable that has the same name as a method,
1228 the name will be considered free *and* local in the
1229 class. It should be handled by the closure, as
1230 well as by the normal name loookup logic.
1231 */
1232 reftype = get_ref_type(c, name);
1233 if (reftype == CELL)
1234 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1235 else /* (reftype == FREE) */
1236 arg = compiler_lookup_arg(c->u->u_freevars, name);
1237 if (arg == -1) {
1238 printf("lookup %s in %s %d %d\n"
1239 "freevars of %s: %s\n",
1240 PyObject_REPR(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 reftype, arg,
1243 PyString_AS_STRING(co->co_name),
1244 PyObject_REPR(co->co_freevars));
1245 Py_FatalError("compiler_make_closure()");
1246 }
1247 ADDOP_I(c, LOAD_CLOSURE, arg);
1248 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 ADDOP_I(c, MAKE_CLOSURE, args);
1252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
1255static int
1256compiler_decorators(struct compiler *c, asdl_seq* decos)
1257{
1258 int i;
1259
1260 if (!decos)
1261 return 1;
1262
1263 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001264 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 }
1266 return 1;
1267}
1268
1269static int
1270compiler_arguments(struct compiler *c, arguments_ty args)
1271{
1272 int i;
1273 int n = asdl_seq_LEN(args->args);
1274 /* Correctly handle nested argument lists */
1275 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001276 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 if (arg->kind == Tuple_kind) {
1278 PyObject *id = PyString_FromFormat(".%d", i);
1279 if (id == NULL) {
1280 return 0;
1281 }
1282 if (!compiler_nameop(c, id, Load)) {
1283 Py_DECREF(id);
1284 return 0;
1285 }
1286 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001287 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001288 }
1289 }
1290 return 1;
1291}
1292
1293static int
1294compiler_function(struct compiler *c, stmt_ty s)
1295{
1296 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001297 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 arguments_ty args = s->v.FunctionDef.args;
1299 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001300 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301 int i, n, docstring;
1302
1303 assert(s->kind == FunctionDef_kind);
1304
1305 if (!compiler_decorators(c, decos))
1306 return 0;
1307 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001308 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1310 s->lineno))
1311 return 0;
1312
Anthony Baxter7b782b62006-04-11 12:01:56 +00001313 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001314 docstring = compiler_isdocstring(st);
1315 if (docstring)
1316 first_const = st->v.Expr.value->v.Str.s;
1317 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001318 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001319 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001320 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001322 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 compiler_arguments(c, args);
1324
1325 c->u->u_argcount = asdl_seq_LEN(args->args);
1326 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001327 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001328 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001329 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1330 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001331 }
1332 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001333 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 if (co == NULL)
1335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001337 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001338 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339
1340 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1341 ADDOP_I(c, CALL_FUNCTION, 1);
1342 }
1343
1344 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1345}
1346
1347static int
1348compiler_class(struct compiler *c, stmt_ty s)
1349{
1350 int n;
1351 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001352 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353 /* push class name on stack, needed by BUILD_CLASS */
1354 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1355 /* push the tuple of base classes on the stack */
1356 n = asdl_seq_LEN(s->v.ClassDef.bases);
1357 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001358 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 ADDOP_I(c, BUILD_TUPLE, n);
1360 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1361 s->lineno))
1362 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001363 c->u->u_private = s->v.ClassDef.name;
1364 Py_INCREF(c->u->u_private);
1365 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 if (!str || !compiler_nameop(c, str, Load)) {
1367 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001368 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001370 }
1371
1372 Py_DECREF(str);
1373 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001374 if (!str || !compiler_nameop(c, str, Store)) {
1375 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001378 }
1379 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001381 if (!compiler_body(c, s->v.ClassDef.body)) {
1382 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001386 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1387 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001389 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 if (co == NULL)
1391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001394 Py_DECREF(co);
1395
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396 ADDOP_I(c, CALL_FUNCTION, 0);
1397 ADDOP(c, BUILD_CLASS);
1398 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1399 return 0;
1400 return 1;
1401}
1402
1403static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001404compiler_ifexp(struct compiler *c, expr_ty e)
1405{
1406 basicblock *end, *next;
1407
1408 assert(e->kind == IfExp_kind);
1409 end = compiler_new_block(c);
1410 if (end == NULL)
1411 return 0;
1412 next = compiler_new_block(c);
1413 if (next == NULL)
1414 return 0;
1415 VISIT(c, expr, e->v.IfExp.test);
1416 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1417 ADDOP(c, POP_TOP);
1418 VISIT(c, expr, e->v.IfExp.body);
1419 ADDOP_JREL(c, JUMP_FORWARD, end);
1420 compiler_use_next_block(c, next);
1421 ADDOP(c, POP_TOP);
1422 VISIT(c, expr, e->v.IfExp.orelse);
1423 compiler_use_next_block(c, end);
1424 return 1;
1425}
1426
1427static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428compiler_lambda(struct compiler *c, expr_ty e)
1429{
1430 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001431 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 arguments_ty args = e->v.Lambda.args;
1433 assert(e->kind == Lambda_kind);
1434
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001435 if (!name) {
1436 name = PyString_InternFromString("<lambda>");
1437 if (!name)
1438 return 0;
1439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440
1441 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001442 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1444 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001445
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001446 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 compiler_arguments(c, args);
1448
1449 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001450 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1451 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001453 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 if (co == NULL)
1455 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001456
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001457 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001458 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459
1460 return 1;
1461}
1462
1463static int
1464compiler_print(struct compiler *c, stmt_ty s)
1465{
1466 int i, n;
1467 bool dest;
1468
1469 assert(s->kind == Print_kind);
1470 n = asdl_seq_LEN(s->v.Print.values);
1471 dest = false;
1472 if (s->v.Print.dest) {
1473 VISIT(c, expr, s->v.Print.dest);
1474 dest = true;
1475 }
1476 for (i = 0; i < n; i++) {
1477 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1478 if (dest) {
1479 ADDOP(c, DUP_TOP);
1480 VISIT(c, expr, e);
1481 ADDOP(c, ROT_TWO);
1482 ADDOP(c, PRINT_ITEM_TO);
1483 }
1484 else {
1485 VISIT(c, expr, e);
1486 ADDOP(c, PRINT_ITEM);
1487 }
1488 }
1489 if (s->v.Print.nl) {
1490 if (dest)
1491 ADDOP(c, PRINT_NEWLINE_TO)
1492 else
1493 ADDOP(c, PRINT_NEWLINE)
1494 }
1495 else if (dest)
1496 ADDOP(c, POP_TOP);
1497 return 1;
1498}
1499
1500static int
1501compiler_if(struct compiler *c, stmt_ty s)
1502{
1503 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00001504 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 assert(s->kind == If_kind);
1506 end = compiler_new_block(c);
1507 if (end == NULL)
1508 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001509 next = compiler_new_block(c);
1510 if (next == NULL)
1511 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00001512
1513 constant = expr_constant(s->v.If.test);
1514 /* constant = 0: "if 0"
1515 * constant = 1: "if 1", "if 2", ...
1516 * constant = -1: rest */
1517 if (constant == 0) {
1518 if (s->v.If.orelse)
1519 VISIT_SEQ(c, stmt, s->v.If.orelse);
1520 } else if (constant == 1) {
1521 VISIT_SEQ(c, stmt, s->v.If.body);
1522 } else {
1523 VISIT(c, expr, s->v.If.test);
1524 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1525 ADDOP(c, POP_TOP);
1526 VISIT_SEQ(c, stmt, s->v.If.body);
1527 ADDOP_JREL(c, JUMP_FORWARD, end);
1528 compiler_use_next_block(c, next);
1529 ADDOP(c, POP_TOP);
1530 if (s->v.If.orelse)
1531 VISIT_SEQ(c, stmt, s->v.If.orelse);
1532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533 compiler_use_next_block(c, end);
1534 return 1;
1535}
1536
1537static int
1538compiler_for(struct compiler *c, stmt_ty s)
1539{
1540 basicblock *start, *cleanup, *end;
1541
1542 start = compiler_new_block(c);
1543 cleanup = compiler_new_block(c);
1544 end = compiler_new_block(c);
1545 if (start == NULL || end == NULL || cleanup == NULL)
1546 return 0;
1547 ADDOP_JREL(c, SETUP_LOOP, end);
1548 if (!compiler_push_fblock(c, LOOP, start))
1549 return 0;
1550 VISIT(c, expr, s->v.For.iter);
1551 ADDOP(c, GET_ITER);
1552 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001553 /* XXX(nnorwitz): is there a better way to handle this?
1554 for loops are special, we want to be able to trace them
1555 each time around, so we need to set an extra line number. */
1556 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557 ADDOP_JREL(c, FOR_ITER, cleanup);
1558 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001559 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001560 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1561 compiler_use_next_block(c, cleanup);
1562 ADDOP(c, POP_BLOCK);
1563 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001564 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565 compiler_use_next_block(c, end);
1566 return 1;
1567}
1568
1569static int
1570compiler_while(struct compiler *c, stmt_ty s)
1571{
1572 basicblock *loop, *orelse, *end, *anchor = NULL;
1573 int constant = expr_constant(s->v.While.test);
1574
1575 if (constant == 0)
1576 return 1;
1577 loop = compiler_new_block(c);
1578 end = compiler_new_block(c);
1579 if (constant == -1) {
1580 anchor = compiler_new_block(c);
1581 if (anchor == NULL)
1582 return 0;
1583 }
1584 if (loop == NULL || end == NULL)
1585 return 0;
1586 if (s->v.While.orelse) {
1587 orelse = compiler_new_block(c);
1588 if (orelse == NULL)
1589 return 0;
1590 }
1591 else
1592 orelse = NULL;
1593
1594 ADDOP_JREL(c, SETUP_LOOP, end);
1595 compiler_use_next_block(c, loop);
1596 if (!compiler_push_fblock(c, LOOP, loop))
1597 return 0;
1598 if (constant == -1) {
1599 VISIT(c, expr, s->v.While.test);
1600 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1601 ADDOP(c, POP_TOP);
1602 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001603 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1605
1606 /* XXX should the two POP instructions be in a separate block
1607 if there is no else clause ?
1608 */
1609
1610 if (constant == -1) {
1611 compiler_use_next_block(c, anchor);
1612 ADDOP(c, POP_TOP);
1613 ADDOP(c, POP_BLOCK);
1614 }
1615 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00001616 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001617 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 compiler_use_next_block(c, end);
1619
1620 return 1;
1621}
1622
1623static int
1624compiler_continue(struct compiler *c)
1625{
1626 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Neal Norwitz4f096d92006-08-21 19:47:08 +00001627 static const char IN_FINALLY_ERROR_MSG[] =
1628 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629 int i;
1630
1631 if (!c->u->u_nfblocks)
1632 return compiler_error(c, LOOP_ERROR_MSG);
1633 i = c->u->u_nfblocks - 1;
1634 switch (c->u->u_fblock[i].fb_type) {
1635 case LOOP:
1636 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1637 break;
1638 case EXCEPT:
1639 case FINALLY_TRY:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001640 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
1641 /* Prevent continue anywhere under a finally
1642 even if hidden in a sub-try or except. */
1643 if (c->u->u_fblock[i].fb_type == FINALLY_END)
1644 return compiler_error(c, IN_FINALLY_ERROR_MSG);
1645 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 if (i == -1)
1647 return compiler_error(c, LOOP_ERROR_MSG);
1648 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1649 break;
1650 case FINALLY_END:
Neal Norwitz4f096d92006-08-21 19:47:08 +00001651 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652 }
1653
1654 return 1;
1655}
1656
1657/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1658
1659 SETUP_FINALLY L
1660 <code for body>
1661 POP_BLOCK
1662 LOAD_CONST <None>
1663 L: <code for finalbody>
1664 END_FINALLY
1665
1666 The special instructions use the block stack. Each block
1667 stack entry contains the instruction that created it (here
1668 SETUP_FINALLY), the level of the value stack at the time the
1669 block stack entry was created, and a label (here L).
1670
1671 SETUP_FINALLY:
1672 Pushes the current value stack level and the label
1673 onto the block stack.
1674 POP_BLOCK:
1675 Pops en entry from the block stack, and pops the value
1676 stack until its level is the same as indicated on the
1677 block stack. (The label is ignored.)
1678 END_FINALLY:
1679 Pops a variable number of entries from the *value* stack
1680 and re-raises the exception they specify. The number of
1681 entries popped depends on the (pseudo) exception type.
1682
1683 The block stack is unwound when an exception is raised:
1684 when a SETUP_FINALLY entry is found, the exception is pushed
1685 onto the value stack (and the exception condition is cleared),
1686 and the interpreter jumps to the label gotten from the block
1687 stack.
1688*/
1689
1690static int
1691compiler_try_finally(struct compiler *c, stmt_ty s)
1692{
1693 basicblock *body, *end;
1694 body = compiler_new_block(c);
1695 end = compiler_new_block(c);
1696 if (body == NULL || end == NULL)
1697 return 0;
1698
1699 ADDOP_JREL(c, SETUP_FINALLY, end);
1700 compiler_use_next_block(c, body);
1701 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1702 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001703 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 ADDOP(c, POP_BLOCK);
1705 compiler_pop_fblock(c, FINALLY_TRY, body);
1706
1707 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1708 compiler_use_next_block(c, end);
1709 if (!compiler_push_fblock(c, FINALLY_END, end))
1710 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001711 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712 ADDOP(c, END_FINALLY);
1713 compiler_pop_fblock(c, FINALLY_END, end);
1714
1715 return 1;
1716}
1717
1718/*
1719 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1720 (The contents of the value stack is shown in [], with the top
1721 at the right; 'tb' is trace-back info, 'val' the exception's
1722 associated value, and 'exc' the exception.)
1723
1724 Value stack Label Instruction Argument
1725 [] SETUP_EXCEPT L1
1726 [] <code for S>
1727 [] POP_BLOCK
1728 [] JUMP_FORWARD L0
1729
1730 [tb, val, exc] L1: DUP )
1731 [tb, val, exc, exc] <evaluate E1> )
1732 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1733 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1734 [tb, val, exc, 1] POP )
1735 [tb, val, exc] POP
1736 [tb, val] <assign to V1> (or POP if no V1)
1737 [tb] POP
1738 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001739 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001740
1741 [tb, val, exc, 0] L2: POP
1742 [tb, val, exc] DUP
1743 .............................etc.......................
1744
1745 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001746 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747
1748 [] L0: <next statement>
1749
1750 Of course, parts are not generated if Vi or Ei is not present.
1751*/
1752static int
1753compiler_try_except(struct compiler *c, stmt_ty s)
1754{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001755 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001756 int i, n;
1757
1758 body = compiler_new_block(c);
1759 except = compiler_new_block(c);
1760 orelse = compiler_new_block(c);
1761 end = compiler_new_block(c);
1762 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1763 return 0;
1764 ADDOP_JREL(c, SETUP_EXCEPT, except);
1765 compiler_use_next_block(c, body);
1766 if (!compiler_push_fblock(c, EXCEPT, body))
1767 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001768 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769 ADDOP(c, POP_BLOCK);
1770 compiler_pop_fblock(c, EXCEPT, body);
1771 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1772 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1773 compiler_use_next_block(c, except);
1774 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001775 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 s->v.TryExcept.handlers, i);
1777 if (!handler->type && i < n-1)
1778 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00001779 c->u->u_lineno_set = false;
1780 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 except = compiler_new_block(c);
1782 if (except == NULL)
1783 return 0;
1784 if (handler->type) {
1785 ADDOP(c, DUP_TOP);
1786 VISIT(c, expr, handler->type);
1787 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1788 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1789 ADDOP(c, POP_TOP);
1790 }
1791 ADDOP(c, POP_TOP);
1792 if (handler->name) {
1793 VISIT(c, expr, handler->name);
1794 }
1795 else {
1796 ADDOP(c, POP_TOP);
1797 }
1798 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001799 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 ADDOP_JREL(c, JUMP_FORWARD, end);
1801 compiler_use_next_block(c, except);
1802 if (handler->type)
1803 ADDOP(c, POP_TOP);
1804 }
1805 ADDOP(c, END_FINALLY);
1806 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001807 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 compiler_use_next_block(c, end);
1809 return 1;
1810}
1811
1812static int
1813compiler_import_as(struct compiler *c, identifier name, identifier asname)
1814{
1815 /* The IMPORT_NAME opcode was already generated. This function
1816 merely needs to bind the result to a name.
1817
1818 If there is a dot in name, we need to split it and emit a
1819 LOAD_ATTR for each name.
1820 */
1821 const char *src = PyString_AS_STRING(name);
1822 const char *dot = strchr(src, '.');
1823 if (dot) {
1824 /* Consume the base module name to get the first attribute */
1825 src = dot + 1;
1826 while (dot) {
1827 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001828 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001830 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001832 if (!attr)
1833 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001835 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836 src = dot + 1;
1837 }
1838 }
1839 return compiler_nameop(c, asname, Store);
1840}
1841
1842static int
1843compiler_import(struct compiler *c, stmt_ty s)
1844{
1845 /* The Import node stores a module name like a.b.c as a single
1846 string. This is convenient for all cases except
1847 import a.b.c as d
1848 where we need to parse that string to extract the individual
1849 module names.
1850 XXX Perhaps change the representation to make this case simpler?
1851 */
1852 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001853
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001855 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001857 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858
Neal Norwitzcbce2802006-04-03 06:26:32 +00001859 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001860 level = PyInt_FromLong(0);
1861 else
1862 level = PyInt_FromLong(-1);
1863
1864 if (level == NULL)
1865 return 0;
1866
1867 ADDOP_O(c, LOAD_CONST, level, consts);
1868 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1870 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1871
1872 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001873 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001874 if (!r)
1875 return r;
1876 }
1877 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 identifier tmp = alias->name;
1879 const char *base = PyString_AS_STRING(alias->name);
1880 char *dot = strchr(base, '.');
1881 if (dot)
1882 tmp = PyString_FromStringAndSize(base,
1883 dot - base);
1884 r = compiler_nameop(c, tmp, Store);
1885 if (dot) {
1886 Py_DECREF(tmp);
1887 }
1888 if (!r)
1889 return r;
1890 }
1891 }
1892 return 1;
1893}
1894
1895static int
1896compiler_from_import(struct compiler *c, stmt_ty s)
1897{
1898 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899
1900 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001901 PyObject *level;
1902
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903 if (!names)
1904 return 0;
1905
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001906 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00001907 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001908 level = PyInt_FromLong(-1);
1909 else
1910 level = PyInt_FromLong(s->v.ImportFrom.level);
1911
1912 if (!level) {
1913 Py_DECREF(names);
1914 return 0;
1915 }
1916
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917 /* build up the names */
1918 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001919 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 Py_INCREF(alias->name);
1921 PyTuple_SET_ITEM(names, i, alias->name);
1922 }
1923
1924 if (s->lineno > c->c_future->ff_lineno) {
1925 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1926 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001927 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928 Py_DECREF(names);
1929 return compiler_error(c,
1930 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001931 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932
1933 }
1934 }
1935
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001936 ADDOP_O(c, LOAD_CONST, level, consts);
1937 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001939 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1941 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001942 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 identifier store_name;
1944
1945 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1946 assert(n == 1);
1947 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001948 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 }
1950
1951 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1952 store_name = alias->name;
1953 if (alias->asname)
1954 store_name = alias->asname;
1955
1956 if (!compiler_nameop(c, store_name, Store)) {
1957 Py_DECREF(names);
1958 return 0;
1959 }
1960 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001961 /* remove imported module */
1962 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 return 1;
1964}
1965
1966static int
1967compiler_assert(struct compiler *c, stmt_ty s)
1968{
1969 static PyObject *assertion_error = NULL;
1970 basicblock *end;
1971
1972 if (Py_OptimizeFlag)
1973 return 1;
1974 if (assertion_error == NULL) {
1975 assertion_error = PyString_FromString("AssertionError");
1976 if (assertion_error == NULL)
1977 return 0;
1978 }
1979 VISIT(c, expr, s->v.Assert.test);
1980 end = compiler_new_block(c);
1981 if (end == NULL)
1982 return 0;
1983 ADDOP_JREL(c, JUMP_IF_TRUE, end);
1984 ADDOP(c, POP_TOP);
1985 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
1986 if (s->v.Assert.msg) {
1987 VISIT(c, expr, s->v.Assert.msg);
1988 ADDOP_I(c, RAISE_VARARGS, 2);
1989 }
1990 else {
1991 ADDOP_I(c, RAISE_VARARGS, 1);
1992 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00001993 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 ADDOP(c, POP_TOP);
1995 return 1;
1996}
1997
1998static int
1999compiler_visit_stmt(struct compiler *c, stmt_ty s)
2000{
2001 int i, n;
2002
Neal Norwitzf733a012006-10-29 18:30:10 +00002003 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004 c->u->u_lineno = s->lineno;
2005 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002006
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002008 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002010 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002012 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 if (c->u->u_ste->ste_type != FunctionBlock)
2014 return compiler_error(c, "'return' outside function");
2015 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 VISIT(c, expr, s->v.Return.value);
2017 }
2018 else
2019 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2020 ADDOP(c, RETURN_VALUE);
2021 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002022 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002023 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002025 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 n = asdl_seq_LEN(s->v.Assign.targets);
2027 VISIT(c, expr, s->v.Assign.value);
2028 for (i = 0; i < n; i++) {
2029 if (i < n - 1)
2030 ADDOP(c, DUP_TOP);
2031 VISIT(c, expr,
2032 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2033 }
2034 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002035 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002037 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002039 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002041 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002043 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002045 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 n = 0;
2047 if (s->v.Raise.type) {
2048 VISIT(c, expr, s->v.Raise.type);
2049 n++;
2050 if (s->v.Raise.inst) {
2051 VISIT(c, expr, s->v.Raise.inst);
2052 n++;
2053 if (s->v.Raise.tback) {
2054 VISIT(c, expr, s->v.Raise.tback);
2055 n++;
2056 }
2057 }
2058 }
2059 ADDOP_I(c, RAISE_VARARGS, n);
2060 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002061 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002062 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002063 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002069 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 VISIT(c, expr, s->v.Exec.body);
2073 if (s->v.Exec.globals) {
2074 VISIT(c, expr, s->v.Exec.globals);
2075 if (s->v.Exec.locals) {
2076 VISIT(c, expr, s->v.Exec.locals);
2077 } else {
2078 ADDOP(c, DUP_TOP);
2079 }
2080 } else {
2081 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2082 ADDOP(c, DUP_TOP);
2083 }
2084 ADDOP(c, EXEC_STMT);
2085 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002086 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002090 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 ADDOP(c, PRINT_EXPR);
2092 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002093 else if (s->v.Expr.value->kind != Str_kind &&
2094 s->v.Expr.value->kind != Num_kind) {
2095 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 ADDOP(c, POP_TOP);
2097 }
2098 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002099 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002101 case Break_kind:
Jeremy Hylton82271f12006-10-04 02:24:52 +00002102 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103 return compiler_error(c, "'break' outside loop");
2104 ADDOP(c, BREAK_LOOP);
2105 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002106 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002108 case With_kind:
2109 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 }
2111 return 1;
2112}
2113
2114static int
2115unaryop(unaryop_ty op)
2116{
2117 switch (op) {
2118 case Invert:
2119 return UNARY_INVERT;
2120 case Not:
2121 return UNARY_NOT;
2122 case UAdd:
2123 return UNARY_POSITIVE;
2124 case USub:
2125 return UNARY_NEGATIVE;
2126 }
2127 return 0;
2128}
2129
2130static int
2131binop(struct compiler *c, operator_ty op)
2132{
2133 switch (op) {
2134 case Add:
2135 return BINARY_ADD;
2136 case Sub:
2137 return BINARY_SUBTRACT;
2138 case Mult:
2139 return BINARY_MULTIPLY;
2140 case Div:
2141 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2142 return BINARY_TRUE_DIVIDE;
2143 else
2144 return BINARY_DIVIDE;
2145 case Mod:
2146 return BINARY_MODULO;
2147 case Pow:
2148 return BINARY_POWER;
2149 case LShift:
2150 return BINARY_LSHIFT;
2151 case RShift:
2152 return BINARY_RSHIFT;
2153 case BitOr:
2154 return BINARY_OR;
2155 case BitXor:
2156 return BINARY_XOR;
2157 case BitAnd:
2158 return BINARY_AND;
2159 case FloorDiv:
2160 return BINARY_FLOOR_DIVIDE;
2161 }
2162 return 0;
2163}
2164
2165static int
2166cmpop(cmpop_ty op)
2167{
2168 switch (op) {
2169 case Eq:
2170 return PyCmp_EQ;
2171 case NotEq:
2172 return PyCmp_NE;
2173 case Lt:
2174 return PyCmp_LT;
2175 case LtE:
2176 return PyCmp_LE;
2177 case Gt:
2178 return PyCmp_GT;
2179 case GtE:
2180 return PyCmp_GE;
2181 case Is:
2182 return PyCmp_IS;
2183 case IsNot:
2184 return PyCmp_IS_NOT;
2185 case In:
2186 return PyCmp_IN;
2187 case NotIn:
2188 return PyCmp_NOT_IN;
2189 }
2190 return PyCmp_BAD;
2191}
2192
2193static int
2194inplace_binop(struct compiler *c, operator_ty op)
2195{
2196 switch (op) {
2197 case Add:
2198 return INPLACE_ADD;
2199 case Sub:
2200 return INPLACE_SUBTRACT;
2201 case Mult:
2202 return INPLACE_MULTIPLY;
2203 case Div:
2204 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2205 return INPLACE_TRUE_DIVIDE;
2206 else
2207 return INPLACE_DIVIDE;
2208 case Mod:
2209 return INPLACE_MODULO;
2210 case Pow:
2211 return INPLACE_POWER;
2212 case LShift:
2213 return INPLACE_LSHIFT;
2214 case RShift:
2215 return INPLACE_RSHIFT;
2216 case BitOr:
2217 return INPLACE_OR;
2218 case BitXor:
2219 return INPLACE_XOR;
2220 case BitAnd:
2221 return INPLACE_AND;
2222 case FloorDiv:
2223 return INPLACE_FLOOR_DIVIDE;
2224 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002225 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002226 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002227 return 0;
2228}
2229
2230static int
2231compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2232{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002233 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002234 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2235
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002236 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002237 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238 /* XXX AugStore isn't used anywhere! */
2239
2240 /* First check for assignment to __debug__. Param? */
2241 if ((ctx == Store || ctx == AugStore || ctx == Del)
2242 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2243 return compiler_error(c, "can not assign to __debug__");
2244 }
2245
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002246 mangled = _Py_Mangle(c->u->u_private, name);
2247 if (!mangled)
2248 return 0;
2249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002250 op = 0;
2251 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002252 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 switch (scope) {
2254 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002255 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002256 optype = OP_DEREF;
2257 break;
2258 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002259 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260 optype = OP_DEREF;
2261 break;
2262 case LOCAL:
2263 if (c->u->u_ste->ste_type == FunctionBlock)
2264 optype = OP_FAST;
2265 break;
2266 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002267 if (c->u->u_ste->ste_type == FunctionBlock &&
2268 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269 optype = OP_GLOBAL;
2270 break;
2271 case GLOBAL_EXPLICIT:
2272 optype = OP_GLOBAL;
2273 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002274 default:
2275 /* scope can be 0 */
2276 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 }
2278
2279 /* XXX Leave assert here, but handle __doc__ and the like better */
2280 assert(scope || PyString_AS_STRING(name)[0] == '_');
2281
2282 switch (optype) {
2283 case OP_DEREF:
2284 switch (ctx) {
2285 case Load: op = LOAD_DEREF; break;
2286 case Store: op = STORE_DEREF; break;
2287 case AugLoad:
2288 case AugStore:
2289 break;
2290 case Del:
2291 PyErr_Format(PyExc_SyntaxError,
2292 "can not delete variable '%s' referenced "
2293 "in nested scope",
2294 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002295 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002298 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002299 PyErr_SetString(PyExc_SystemError,
2300 "param invalid for deref variable");
2301 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302 }
2303 break;
2304 case OP_FAST:
2305 switch (ctx) {
2306 case Load: op = LOAD_FAST; break;
2307 case Store: op = STORE_FAST; break;
2308 case Del: op = DELETE_FAST; break;
2309 case AugLoad:
2310 case AugStore:
2311 break;
2312 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002313 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002314 PyErr_SetString(PyExc_SystemError,
2315 "param invalid for local variable");
2316 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002318 ADDOP_O(c, op, mangled, varnames);
2319 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002320 return 1;
2321 case OP_GLOBAL:
2322 switch (ctx) {
2323 case Load: op = LOAD_GLOBAL; break;
2324 case Store: op = STORE_GLOBAL; break;
2325 case Del: op = DELETE_GLOBAL; break;
2326 case AugLoad:
2327 case AugStore:
2328 break;
2329 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002330 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002331 PyErr_SetString(PyExc_SystemError,
2332 "param invalid for global variable");
2333 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 }
2335 break;
2336 case OP_NAME:
2337 switch (ctx) {
2338 case Load: op = LOAD_NAME; break;
2339 case Store: op = STORE_NAME; break;
2340 case Del: op = DELETE_NAME; break;
2341 case AugLoad:
2342 case AugStore:
2343 break;
2344 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002345 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002346 PyErr_SetString(PyExc_SystemError,
2347 "param invalid for name variable");
2348 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349 }
2350 break;
2351 }
2352
2353 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002354 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002355 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002356 if (arg < 0)
2357 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002358 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359}
2360
2361static int
2362compiler_boolop(struct compiler *c, expr_ty e)
2363{
2364 basicblock *end;
2365 int jumpi, i, n;
2366 asdl_seq *s;
2367
2368 assert(e->kind == BoolOp_kind);
2369 if (e->v.BoolOp.op == And)
2370 jumpi = JUMP_IF_FALSE;
2371 else
2372 jumpi = JUMP_IF_TRUE;
2373 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002374 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 return 0;
2376 s = e->v.BoolOp.values;
2377 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00002378 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002380 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381 ADDOP_JREL(c, jumpi, end);
2382 ADDOP(c, POP_TOP)
2383 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002384 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 compiler_use_next_block(c, end);
2386 return 1;
2387}
2388
2389static int
2390compiler_list(struct compiler *c, expr_ty e)
2391{
2392 int n = asdl_seq_LEN(e->v.List.elts);
2393 if (e->v.List.ctx == Store) {
2394 ADDOP_I(c, UNPACK_SEQUENCE, n);
2395 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002396 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397 if (e->v.List.ctx == Load) {
2398 ADDOP_I(c, BUILD_LIST, n);
2399 }
2400 return 1;
2401}
2402
2403static int
2404compiler_tuple(struct compiler *c, expr_ty e)
2405{
2406 int n = asdl_seq_LEN(e->v.Tuple.elts);
2407 if (e->v.Tuple.ctx == Store) {
2408 ADDOP_I(c, UNPACK_SEQUENCE, n);
2409 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002410 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 if (e->v.Tuple.ctx == Load) {
2412 ADDOP_I(c, BUILD_TUPLE, n);
2413 }
2414 return 1;
2415}
2416
2417static int
2418compiler_compare(struct compiler *c, expr_ty e)
2419{
2420 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002421 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422
2423 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2424 VISIT(c, expr, e->v.Compare.left);
2425 n = asdl_seq_LEN(e->v.Compare.ops);
2426 assert(n > 0);
2427 if (n > 1) {
2428 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002429 if (cleanup == NULL)
2430 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00002431 VISIT(c, expr,
2432 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 }
2434 for (i = 1; i < n; i++) {
2435 ADDOP(c, DUP_TOP);
2436 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002438 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00002439 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002440 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2441 NEXT_BLOCK(c);
2442 ADDOP(c, POP_TOP);
2443 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00002444 VISIT(c, expr,
2445 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00002447 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00002449 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 if (n > 1) {
2451 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002452 if (end == NULL)
2453 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 ADDOP_JREL(c, JUMP_FORWARD, end);
2455 compiler_use_next_block(c, cleanup);
2456 ADDOP(c, ROT_TWO);
2457 ADDOP(c, POP_TOP);
2458 compiler_use_next_block(c, end);
2459 }
2460 return 1;
2461}
2462
2463static int
2464compiler_call(struct compiler *c, expr_ty e)
2465{
2466 int n, code = 0;
2467
2468 VISIT(c, expr, e->v.Call.func);
2469 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002470 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002472 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2474 }
2475 if (e->v.Call.starargs) {
2476 VISIT(c, expr, e->v.Call.starargs);
2477 code |= 1;
2478 }
2479 if (e->v.Call.kwargs) {
2480 VISIT(c, expr, e->v.Call.kwargs);
2481 code |= 2;
2482 }
2483 switch (code) {
2484 case 0:
2485 ADDOP_I(c, CALL_FUNCTION, n);
2486 break;
2487 case 1:
2488 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2489 break;
2490 case 2:
2491 ADDOP_I(c, CALL_FUNCTION_KW, n);
2492 break;
2493 case 3:
2494 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2495 break;
2496 }
2497 return 1;
2498}
2499
2500static int
2501compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002502 asdl_seq *generators, int gen_index,
2503 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504{
2505 /* generate code for the iterator, then each of the ifs,
2506 and then write to the element */
2507
2508 comprehension_ty l;
2509 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002510 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511
2512 start = compiler_new_block(c);
2513 skip = compiler_new_block(c);
2514 if_cleanup = compiler_new_block(c);
2515 anchor = compiler_new_block(c);
2516
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002517 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2518 anchor == NULL)
2519 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520
Anthony Baxter7b782b62006-04-11 12:01:56 +00002521 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002522 VISIT(c, expr, l->iter);
2523 ADDOP(c, GET_ITER);
2524 compiler_use_next_block(c, start);
2525 ADDOP_JREL(c, FOR_ITER, anchor);
2526 NEXT_BLOCK(c);
2527 VISIT(c, expr, l->target);
2528
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002529 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 n = asdl_seq_LEN(l->ifs);
2531 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002532 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 VISIT(c, expr, e);
2534 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2535 NEXT_BLOCK(c);
2536 ADDOP(c, POP_TOP);
2537 }
2538
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 if (++gen_index < asdl_seq_LEN(generators))
2540 if (!compiler_listcomp_generator(c, tmpname,
2541 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002544 /* only append after the last for generator */
2545 if (gen_index >= asdl_seq_LEN(generators)) {
2546 if (!compiler_nameop(c, tmpname, Load))
2547 return 0;
2548 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002549 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002550
2551 compiler_use_next_block(c, skip);
2552 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 for (i = 0; i < n; i++) {
2554 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 if (i == 0)
2556 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557 ADDOP(c, POP_TOP);
2558 }
2559 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2560 compiler_use_next_block(c, anchor);
Georg Brandl2c4fb8d2006-10-29 08:47:08 +00002561 /* delete the temporary list name added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002563 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 return 0;
2565
2566 return 1;
2567}
2568
2569static int
2570compiler_listcomp(struct compiler *c, expr_ty e)
2571{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002573 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002574 asdl_seq *generators = e->v.ListComp.generators;
2575
2576 assert(e->kind == ListComp_kind);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002577 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002578 if (!tmp)
2579 return 0;
2580 ADDOP_I(c, BUILD_LIST, 0);
2581 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2584 e->v.ListComp.elt);
2585 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 return rc;
2587}
2588
2589static int
2590compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002591 asdl_seq *generators, int gen_index,
2592 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593{
2594 /* generate code for the iterator, then each of the ifs,
2595 and then write to the element */
2596
2597 comprehension_ty ge;
2598 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002599 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600
2601 start = compiler_new_block(c);
2602 skip = compiler_new_block(c);
2603 if_cleanup = compiler_new_block(c);
2604 anchor = compiler_new_block(c);
2605 end = compiler_new_block(c);
2606
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002607 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608 anchor == NULL || end == NULL)
2609 return 0;
2610
Anthony Baxter7b782b62006-04-11 12:01:56 +00002611 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 ADDOP_JREL(c, SETUP_LOOP, end);
2613 if (!compiler_push_fblock(c, LOOP, start))
2614 return 0;
2615
2616 if (gen_index == 0) {
2617 /* Receive outermost iter as an implicit argument */
2618 c->u->u_argcount = 1;
2619 ADDOP_I(c, LOAD_FAST, 0);
2620 }
2621 else {
2622 /* Sub-iter - calculate on the fly */
2623 VISIT(c, expr, ge->iter);
2624 ADDOP(c, GET_ITER);
2625 }
2626 compiler_use_next_block(c, start);
2627 ADDOP_JREL(c, FOR_ITER, anchor);
2628 NEXT_BLOCK(c);
2629 VISIT(c, expr, ge->target);
2630
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002631 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 n = asdl_seq_LEN(ge->ifs);
2633 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002634 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 VISIT(c, expr, e);
2636 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2637 NEXT_BLOCK(c);
2638 ADDOP(c, POP_TOP);
2639 }
2640
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002641 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2643 return 0;
2644
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002645 /* only append after the last 'for' generator */
2646 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 VISIT(c, expr, elt);
2648 ADDOP(c, YIELD_VALUE);
2649 ADDOP(c, POP_TOP);
2650
2651 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 for (i = 0; i < n; i++) {
2654 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 compiler_use_next_block(c, if_cleanup);
2657
2658 ADDOP(c, POP_TOP);
2659 }
2660 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2661 compiler_use_next_block(c, anchor);
2662 ADDOP(c, POP_BLOCK);
2663 compiler_pop_fblock(c, LOOP, start);
2664 compiler_use_next_block(c, end);
2665
2666 return 1;
2667}
2668
2669static int
2670compiler_genexp(struct compiler *c, expr_ty e)
2671{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002672 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 PyCodeObject *co;
2674 expr_ty outermost_iter = ((comprehension_ty)
2675 (asdl_seq_GET(e->v.GeneratorExp.generators,
2676 0)))->iter;
2677
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002678 if (!name) {
2679 name = PyString_FromString("<genexpr>");
2680 if (!name)
2681 return 0;
2682 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683
2684 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2685 return 0;
2686 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2687 e->v.GeneratorExp.elt);
2688 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002689 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 if (co == NULL)
2691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002694 Py_DECREF(co);
2695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 VISIT(c, expr, outermost_iter);
2697 ADDOP(c, GET_ITER);
2698 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699
2700 return 1;
2701}
2702
2703static int
2704compiler_visit_keyword(struct compiler *c, keyword_ty k)
2705{
2706 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2707 VISIT(c, expr, k->value);
2708 return 1;
2709}
2710
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 whether they are true or false.
2713
2714 Return values: 1 for true, 0 for false, -1 for non-constant.
2715 */
2716
2717static int
2718expr_constant(expr_ty e)
2719{
2720 switch (e->kind) {
2721 case Num_kind:
2722 return PyObject_IsTrue(e->v.Num.n);
2723 case Str_kind:
2724 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00002725 case Name_kind:
2726 /* __debug__ is not assignable, so we can optimize
2727 * it away in if and while statements */
2728 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2729 "__debug__") == 0)
2730 return ! Py_OptimizeFlag;
2731 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 default:
2733 return -1;
2734 }
2735}
2736
Guido van Rossumc2e20742006-02-27 22:32:47 +00002737/*
2738 Implements the with statement from PEP 343.
2739
2740 The semantics outlined in that PEP are as follows:
2741
2742 with EXPR as VAR:
2743 BLOCK
2744
2745 It is implemented roughly as:
2746
Guido van Rossumda5b7012006-05-02 19:47:52 +00002747 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002748 exit = context.__exit__ # not calling it
2749 value = context.__enter__()
2750 try:
2751 VAR = value # if VAR present in the syntax
2752 BLOCK
2753 finally:
2754 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002755 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002756 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002757 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002758 exit(*exc)
2759 */
2760static int
2761compiler_with(struct compiler *c, stmt_ty s)
2762{
Guido van Rossumda5b7012006-05-02 19:47:52 +00002763 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002764 basicblock *block, *finally;
2765 identifier tmpexit, tmpvalue = NULL;
2766
2767 assert(s->kind == With_kind);
2768
Guido van Rossumc2e20742006-02-27 22:32:47 +00002769 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002770 enter_attr = PyString_InternFromString("__enter__");
2771 if (!enter_attr)
2772 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002773 }
2774 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002775 exit_attr = PyString_InternFromString("__exit__");
2776 if (!exit_attr)
2777 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002778 }
2779
2780 block = compiler_new_block(c);
2781 finally = compiler_new_block(c);
2782 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002783 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002784
2785 /* Create a temporary variable to hold context.__exit__ */
2786 tmpexit = compiler_new_tmpname(c);
2787 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002788 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002789 PyArena_AddPyObject(c->c_arena, tmpexit);
2790
2791 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002792 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002793 We need to do this rather than preserving it on the stack
2794 because SETUP_FINALLY remembers the stack level.
2795 We need to do the assignment *inside* the try/finally
2796 so that context.__exit__() is called when the assignment
2797 fails. But we need to call context.__enter__() *before*
2798 the try/finally so that if it fails we won't call
2799 context.__exit__().
2800 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002802 if (tmpvalue == NULL)
2803 return 0;
2804 PyArena_AddPyObject(c->c_arena, tmpvalue);
2805 }
2806
Guido van Rossumda5b7012006-05-02 19:47:52 +00002807 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002808 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809
2810 /* Squirrel away context.__exit__ */
2811 ADDOP(c, DUP_TOP);
2812 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2813 if (!compiler_nameop(c, tmpexit, Store))
2814 return 0;
2815
2816 /* Call context.__enter__() */
2817 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2818 ADDOP_I(c, CALL_FUNCTION, 0);
2819
2820 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002821 /* Store it in tmpvalue */
2822 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 return 0;
2824 }
2825 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002826 /* Discard result from context.__enter__() */
2827 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828 }
2829
2830 /* Start the try block */
2831 ADDOP_JREL(c, SETUP_FINALLY, finally);
2832
2833 compiler_use_next_block(c, block);
2834 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002835 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 }
2837
2838 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002839 /* Bind saved result of context.__enter__() to VAR */
2840 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002841 !compiler_nameop(c, tmpvalue, Del))
2842 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002844 }
2845
2846 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002847 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002848
2849 /* End of try block; start the finally block */
2850 ADDOP(c, POP_BLOCK);
2851 compiler_pop_fblock(c, FINALLY_TRY, block);
2852
2853 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2854 compiler_use_next_block(c, finally);
2855 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002856 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002857
2858 /* Finally block starts; push tmpexit and issue our magic opcode. */
2859 if (!compiler_nameop(c, tmpexit, Load) ||
2860 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002862 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002863
2864 /* Finally block ends. */
2865 ADDOP(c, END_FINALLY);
2866 compiler_pop_fblock(c, FINALLY_END, finally);
2867 return 1;
2868}
2869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870static int
2871compiler_visit_expr(struct compiler *c, expr_ty e)
2872{
2873 int i, n;
2874
Neal Norwitzf733a012006-10-29 18:30:10 +00002875 /* If expr e has a different line number than the last expr/stmt,
2876 set a new line number for the next instruction.
2877 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878 if (e->lineno > c->u->u_lineno) {
2879 c->u->u_lineno = e->lineno;
2880 c->u->u_lineno_set = false;
2881 }
2882 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002883 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002885 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886 VISIT(c, expr, e->v.BinOp.left);
2887 VISIT(c, expr, e->v.BinOp.right);
2888 ADDOP(c, binop(c, e->v.BinOp.op));
2889 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002890 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891 VISIT(c, expr, e->v.UnaryOp.operand);
2892 ADDOP(c, unaryop(e->v.UnaryOp.op));
2893 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002894 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002895 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002896 case IfExp_kind:
2897 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002898 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899 /* XXX get rid of arg? */
2900 ADDOP_I(c, BUILD_MAP, 0);
2901 n = asdl_seq_LEN(e->v.Dict.values);
2902 /* We must arrange things just right for STORE_SUBSCR.
2903 It wants the stack to look like (value) (dict) (key) */
2904 for (i = 0; i < n; i++) {
2905 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002906 VISIT(c, expr,
2907 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00002909 VISIT(c, expr,
2910 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911 ADDOP(c, STORE_SUBSCR);
2912 }
2913 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002914 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002916 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 return compiler_genexp(c, e);
2918 case Yield_kind:
2919 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 if (e->v.Yield.value) {
2922 VISIT(c, expr, e->v.Yield.value);
2923 }
2924 else {
2925 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2926 }
2927 ADDOP(c, YIELD_VALUE);
2928 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002929 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002931 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002932 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002933 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 VISIT(c, expr, e->v.Repr.value);
2935 ADDOP(c, UNARY_CONVERT);
2936 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2939 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002940 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2942 break;
2943 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 if (e->v.Attribute.ctx != AugStore)
2946 VISIT(c, expr, e->v.Attribute.value);
2947 switch (e->v.Attribute.ctx) {
2948 case AugLoad:
2949 ADDOP(c, DUP_TOP);
2950 /* Fall through to load */
2951 case Load:
2952 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2953 break;
2954 case AugStore:
2955 ADDOP(c, ROT_TWO);
2956 /* Fall through to save */
2957 case Store:
2958 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2959 break;
2960 case Del:
2961 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2962 break;
2963 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002964 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002965 PyErr_SetString(PyExc_SystemError,
2966 "param invalid in attribute expression");
2967 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968 }
2969 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002970 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 switch (e->v.Subscript.ctx) {
2972 case AugLoad:
2973 VISIT(c, expr, e->v.Subscript.value);
2974 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
2975 break;
2976 case Load:
2977 VISIT(c, expr, e->v.Subscript.value);
2978 VISIT_SLICE(c, e->v.Subscript.slice, Load);
2979 break;
2980 case AugStore:
2981 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
2982 break;
2983 case Store:
2984 VISIT(c, expr, e->v.Subscript.value);
2985 VISIT_SLICE(c, e->v.Subscript.slice, Store);
2986 break;
2987 case Del:
2988 VISIT(c, expr, e->v.Subscript.value);
2989 VISIT_SLICE(c, e->v.Subscript.slice, Del);
2990 break;
2991 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002992 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002993 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002994 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00002995 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 }
2997 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002998 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3000 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003001 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003002 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003003 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004 return compiler_tuple(c, e);
3005 }
3006 return 1;
3007}
3008
3009static int
3010compiler_augassign(struct compiler *c, stmt_ty s)
3011{
3012 expr_ty e = s->v.AugAssign.target;
3013 expr_ty auge;
3014
3015 assert(s->kind == AugAssign_kind);
3016
3017 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003018 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003020 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003021 if (auge == NULL)
3022 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023 VISIT(c, expr, auge);
3024 VISIT(c, expr, s->v.AugAssign.value);
3025 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3026 auge->v.Attribute.ctx = AugStore;
3027 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028 break;
3029 case Subscript_kind:
3030 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003031 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032 if (auge == NULL)
3033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 VISIT(c, expr, auge);
3035 VISIT(c, expr, s->v.AugAssign.value);
3036 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003039 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003041 if (!compiler_nameop(c, e->v.Name.id, Load))
3042 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043 VISIT(c, expr, s->v.AugAssign.value);
3044 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3045 return compiler_nameop(c, e->v.Name.id, Store);
3046 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003047 PyErr_Format(PyExc_SystemError,
3048 "invalid node type (%d) for augmented assignment",
3049 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003050 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 }
3052 return 1;
3053}
3054
3055static int
3056compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3057{
3058 struct fblockinfo *f;
Neal Norwitz21997af2006-10-28 21:19:07 +00003059 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3060 PyErr_SetString(PyExc_SystemError,
3061 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 return 0;
Neal Norwitz21997af2006-10-28 21:19:07 +00003063 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064 f = &c->u->u_fblock[c->u->u_nfblocks++];
3065 f->fb_type = t;
3066 f->fb_block = b;
3067 return 1;
3068}
3069
3070static void
3071compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3072{
3073 struct compiler_unit *u = c->u;
3074 assert(u->u_nfblocks > 0);
3075 u->u_nfblocks--;
3076 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3077 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3078}
3079
Jeremy Hylton82271f12006-10-04 02:24:52 +00003080static int
3081compiler_in_loop(struct compiler *c) {
3082 int i;
3083 struct compiler_unit *u = c->u;
3084 for (i = 0; i < u->u_nfblocks; ++i) {
3085 if (u->u_fblock[i].fb_type == LOOP)
3086 return 1;
3087 }
3088 return 0;
3089}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090/* Raises a SyntaxError and returns 0.
3091 If something goes wrong, a different exception may be raised.
3092*/
3093
3094static int
3095compiler_error(struct compiler *c, const char *errstr)
3096{
3097 PyObject *loc;
3098 PyObject *u = NULL, *v = NULL;
3099
3100 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3101 if (!loc) {
3102 Py_INCREF(Py_None);
3103 loc = Py_None;
3104 }
3105 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3106 Py_None, loc);
3107 if (!u)
3108 goto exit;
3109 v = Py_BuildValue("(zO)", errstr, u);
3110 if (!v)
3111 goto exit;
3112 PyErr_SetObject(PyExc_SyntaxError, v);
3113 exit:
3114 Py_DECREF(loc);
3115 Py_XDECREF(u);
3116 Py_XDECREF(v);
3117 return 0;
3118}
3119
3120static int
3121compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003122 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003124 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003126 /* XXX this code is duplicated */
3127 switch (ctx) {
3128 case AugLoad: /* fall through to Load */
3129 case Load: op = BINARY_SUBSCR; break;
3130 case AugStore:/* fall through to Store */
3131 case Store: op = STORE_SUBSCR; break;
3132 case Del: op = DELETE_SUBSCR; break;
3133 case Param:
3134 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003135 "invalid %s kind %d in subscript\n",
3136 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 return 0;
3138 }
3139 if (ctx == AugLoad) {
3140 ADDOP_I(c, DUP_TOPX, 2);
3141 }
3142 else if (ctx == AugStore) {
3143 ADDOP(c, ROT_THREE);
3144 }
3145 ADDOP(c, op);
3146 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147}
3148
3149static int
3150compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3151{
3152 int n = 2;
3153 assert(s->kind == Slice_kind);
3154
3155 /* only handles the cases where BUILD_SLICE is emitted */
3156 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 }
3159 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 }
3166 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 }
3169
3170 if (s->v.Slice.step) {
3171 n++;
3172 VISIT(c, expr, s->v.Slice.step);
3173 }
3174 ADDOP_I(c, BUILD_SLICE, n);
3175 return 1;
3176}
3177
3178static int
3179compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3180{
3181 int op = 0, slice_offset = 0, stack_count = 0;
3182
3183 assert(s->v.Slice.step == NULL);
3184 if (s->v.Slice.lower) {
3185 slice_offset++;
3186 stack_count++;
3187 if (ctx != AugStore)
3188 VISIT(c, expr, s->v.Slice.lower);
3189 }
3190 if (s->v.Slice.upper) {
3191 slice_offset += 2;
3192 stack_count++;
3193 if (ctx != AugStore)
3194 VISIT(c, expr, s->v.Slice.upper);
3195 }
3196
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 if (ctx == AugLoad) {
3198 switch (stack_count) {
3199 case 0: ADDOP(c, DUP_TOP); break;
3200 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3201 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3202 }
3203 }
3204 else if (ctx == AugStore) {
3205 switch (stack_count) {
3206 case 0: ADDOP(c, ROT_TWO); break;
3207 case 1: ADDOP(c, ROT_THREE); break;
3208 case 2: ADDOP(c, ROT_FOUR); break;
3209 }
3210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211
3212 switch (ctx) {
3213 case AugLoad: /* fall through to Load */
3214 case Load: op = SLICE; break;
3215 case AugStore:/* fall through to Store */
3216 case Store: op = STORE_SLICE; break;
3217 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003218 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003219 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003220 PyErr_SetString(PyExc_SystemError,
3221 "param invalid in simple slice");
3222 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 }
3224
3225 ADDOP(c, op + slice_offset);
3226 return 1;
3227}
3228
3229static int
3230compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3231 expr_context_ty ctx)
3232{
3233 switch (s->kind) {
3234 case Ellipsis_kind:
3235 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3236 break;
3237 case Slice_kind:
3238 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239 case Index_kind:
3240 VISIT(c, expr, s->v.Index.value);
3241 break;
3242 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003243 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003244 PyErr_SetString(PyExc_SystemError,
3245 "extended slice invalid in nested slice");
3246 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 }
3248 return 1;
3249}
3250
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251static int
3252compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3253{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003254 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003256 case Index_kind:
3257 kindname = "index";
3258 if (ctx != AugStore) {
3259 VISIT(c, expr, s->v.Index.value);
3260 }
3261 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003263 kindname = "ellipsis";
3264 if (ctx != AugStore) {
3265 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 break;
3268 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003269 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 if (!s->v.Slice.step)
3271 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003272 if (ctx != AugStore) {
3273 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274 return 0;
3275 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003276 break;
3277 case ExtSlice_kind:
3278 kindname = "extended slice";
3279 if (ctx != AugStore) {
3280 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3281 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003282 slice_ty sub = (slice_ty)asdl_seq_GET(
3283 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003284 if (!compiler_visit_nested_slice(c, sub, ctx))
3285 return 0;
3286 }
3287 ADDOP_I(c, BUILD_TUPLE, n);
3288 }
3289 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003290 default:
3291 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003292 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003293 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003295 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296}
3297
Neal Norwitzf733a012006-10-29 18:30:10 +00003298
3299/* End of the compiler section, beginning of the assembler section */
3300
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301/* do depth-first search of basic block graph, starting with block.
3302 post records the block indices in post-order.
3303
3304 XXX must handle implicit jumps from one block to next
3305*/
3306
Neal Norwitzf733a012006-10-29 18:30:10 +00003307struct assembler {
3308 PyObject *a_bytecode; /* string containing bytecode */
3309 int a_offset; /* offset into bytecode */
3310 int a_nblocks; /* number of reachable blocks */
3311 basicblock **a_postorder; /* list of blocks in dfs postorder */
3312 PyObject *a_lnotab; /* string containing lnotab */
3313 int a_lnotab_off; /* offset into lnotab */
3314 int a_lineno; /* last lineno of emitted instruction */
3315 int a_lineno_off; /* bytecode offset of last lineno */
3316};
3317
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318static void
3319dfs(struct compiler *c, basicblock *b, struct assembler *a)
3320{
3321 int i;
3322 struct instr *instr = NULL;
3323
3324 if (b->b_seen)
3325 return;
3326 b->b_seen = 1;
3327 if (b->b_next != NULL)
3328 dfs(c, b->b_next, a);
3329 for (i = 0; i < b->b_iused; i++) {
3330 instr = &b->b_instr[i];
3331 if (instr->i_jrel || instr->i_jabs)
3332 dfs(c, instr->i_target, a);
3333 }
3334 a->a_postorder[a->a_nblocks++] = b;
3335}
3336
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003337static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3339{
3340 int i;
3341 struct instr *instr;
3342 if (b->b_seen || b->b_startdepth >= depth)
3343 return maxdepth;
3344 b->b_seen = 1;
3345 b->b_startdepth = depth;
3346 for (i = 0; i < b->b_iused; i++) {
3347 instr = &b->b_instr[i];
3348 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3349 if (depth > maxdepth)
3350 maxdepth = depth;
3351 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3352 if (instr->i_jrel || instr->i_jabs) {
3353 maxdepth = stackdepth_walk(c, instr->i_target,
3354 depth, maxdepth);
3355 if (instr->i_opcode == JUMP_ABSOLUTE ||
3356 instr->i_opcode == JUMP_FORWARD) {
3357 goto out; /* remaining code is dead */
3358 }
3359 }
3360 }
3361 if (b->b_next)
3362 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3363out:
3364 b->b_seen = 0;
3365 return maxdepth;
3366}
3367
3368/* Find the flow path that needs the largest stack. We assume that
3369 * cycles in the flow graph have no net effect on the stack depth.
3370 */
3371static int
3372stackdepth(struct compiler *c)
3373{
3374 basicblock *b, *entryblock;
3375 entryblock = NULL;
3376 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3377 b->b_seen = 0;
3378 b->b_startdepth = INT_MIN;
3379 entryblock = b;
3380 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00003381 if (!entryblock)
3382 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383 return stackdepth_walk(c, entryblock, 0, 0);
3384}
3385
3386static int
3387assemble_init(struct assembler *a, int nblocks, int firstlineno)
3388{
3389 memset(a, 0, sizeof(struct assembler));
3390 a->a_lineno = firstlineno;
3391 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3392 if (!a->a_bytecode)
3393 return 0;
3394 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3395 if (!a->a_lnotab)
3396 return 0;
3397 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003398 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003399 if (!a->a_postorder) {
3400 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003402 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403 return 1;
3404}
3405
3406static void
3407assemble_free(struct assembler *a)
3408{
3409 Py_XDECREF(a->a_bytecode);
3410 Py_XDECREF(a->a_lnotab);
3411 if (a->a_postorder)
3412 PyObject_Free(a->a_postorder);
3413}
3414
3415/* Return the size of a basic block in bytes. */
3416
3417static int
3418instrsize(struct instr *instr)
3419{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003420 if (!instr->i_hasarg)
3421 return 1;
3422 if (instr->i_oparg > 0xffff)
3423 return 6;
3424 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425}
3426
3427static int
3428blocksize(basicblock *b)
3429{
3430 int i;
3431 int size = 0;
3432
3433 for (i = 0; i < b->b_iused; i++)
3434 size += instrsize(&b->b_instr[i]);
3435 return size;
3436}
3437
3438/* All about a_lnotab.
3439
3440c_lnotab is an array of unsigned bytes disguised as a Python string.
3441It is used to map bytecode offsets to source code line #s (when needed
3442for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003443
Tim Peters2a7f3842001-06-09 09:26:21 +00003444The array is conceptually a list of
3445 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003446pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003447
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003448 byte code offset source code line number
3449 0 1
3450 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003451 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003452 350 307
3453 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003454
3455The first trick is that these numbers aren't stored, only the increments
3456from one row to the next (this doesn't really work, but it's a start):
3457
3458 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3459
3460The second trick is that an unsigned byte can't hold negative values, or
3461values larger than 255, so (a) there's a deep assumption that byte code
3462offsets and their corresponding line #s both increase monotonically, and (b)
3463if at least one column jumps by more than 255 from one row to the next, more
3464than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003465from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003466part. A user of c_lnotab desiring to find the source line number
3467corresponding to a bytecode address A should do something like this
3468
3469 lineno = addr = 0
3470 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 addr += addr_incr
3472 if addr > A:
3473 return lineno
3474 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003475
3476In order for this to work, when the addr field increments by more than 255,
3477the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00003478increment is < 256. So, in the example above, assemble_lnotab (it used
3479to be called com_set_lineno) should not (as was actually done until 2.2)
3480expand 300, 300 to 255, 255, 45, 45,
3481 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003482*/
3483
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003484static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003486{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487 int d_bytecode, d_lineno;
3488 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00003489 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490
3491 d_bytecode = a->a_offset - a->a_lineno_off;
3492 d_lineno = i->i_lineno - a->a_lineno;
3493
3494 assert(d_bytecode >= 0);
3495 assert(d_lineno >= 0);
3496
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003497 /* XXX(nnorwitz): is there a better way to handle this?
3498 for loops are special, we want to be able to trace them
3499 each time around, so we need to set an extra line number. */
3500 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003501 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003504 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 nbytes = a->a_lnotab_off + 2 * ncodes;
3506 len = PyString_GET_SIZE(a->a_lnotab);
3507 if (nbytes >= len) {
3508 if (len * 2 < nbytes)
3509 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003510 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 len *= 2;
3512 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3513 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003514 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003515 lnotab = (unsigned char *)
3516 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003517 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518 *lnotab++ = 255;
3519 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003520 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 d_bytecode -= ncodes * 255;
3522 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003523 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 assert(d_bytecode <= 255);
3525 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003526 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 nbytes = a->a_lnotab_off + 2 * ncodes;
3528 len = PyString_GET_SIZE(a->a_lnotab);
3529 if (nbytes >= len) {
3530 if (len * 2 < nbytes)
3531 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003532 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 len *= 2;
3534 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3535 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003536 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003537 lnotab = (unsigned char *)
3538 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003540 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003542 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00003544 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003545 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 d_lineno -= ncodes * 255;
3547 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003548 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003549
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 len = PyString_GET_SIZE(a->a_lnotab);
3551 if (a->a_lnotab_off + 2 >= len) {
3552 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003553 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003554 }
Neal Norwitzb183a252006-04-10 01:03:32 +00003555 lnotab = (unsigned char *)
3556 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003557
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 a->a_lnotab_off += 2;
3559 if (d_bytecode) {
3560 *lnotab++ = d_bytecode;
3561 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003562 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 *lnotab++ = 0;
3565 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003566 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 a->a_lineno = i->i_lineno;
3568 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003569 return 1;
3570}
3571
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572/* assemble_emit()
3573 Extend the bytecode with a new instruction.
3574 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003575*/
3576
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003577static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003579{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003580 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00003581 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 char *code;
3583
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003584 size = instrsize(i);
3585 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003587 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003590 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 if (a->a_offset + size >= len) {
3592 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003593 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3596 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003597 if (size == 6) {
3598 assert(i->i_hasarg);
3599 *code++ = (char)EXTENDED_ARG;
3600 *code++ = ext & 0xff;
3601 *code++ = ext >> 8;
3602 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003605 if (i->i_hasarg) {
3606 assert(size == 3 || size == 6);
3607 *code++ = arg & 0xff;
3608 *code++ = arg >> 8;
3609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003611}
3612
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003613static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003615{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003617 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003618 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003619
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 /* Compute the size of each block and fixup jump args.
3621 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003622start:
3623 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003625 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 bsize = blocksize(b);
3627 b->b_offset = totsize;
3628 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003629 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003630 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3632 bsize = b->b_offset;
3633 for (i = 0; i < b->b_iused; i++) {
3634 struct instr *instr = &b->b_instr[i];
3635 /* Relative jumps are computed relative to
3636 the instruction pointer after fetching
3637 the jump instruction.
3638 */
3639 bsize += instrsize(instr);
3640 if (instr->i_jabs)
3641 instr->i_oparg = instr->i_target->b_offset;
3642 else if (instr->i_jrel) {
3643 int delta = instr->i_target->b_offset - bsize;
3644 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003645 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003646 else
3647 continue;
3648 if (instr->i_oparg > 0xffff)
3649 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003650 }
3651 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003652
3653 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003655 with a better solution.
3656
3657 In the meantime, should the goto be dropped in favor
3658 of a loop?
3659
3660 The issue is that in the first loop blocksize() is called
3661 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003662 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003663 i_oparg is calculated in the second loop above.
3664
3665 So we loop until we stop seeing new EXTENDED_ARGs.
3666 The only EXTENDED_ARGs that could be popping up are
3667 ones in jump instructions. So this should converge
3668 fairly quickly.
3669 */
3670 if (last_extended_arg_count != extended_arg_count) {
3671 last_extended_arg_count = extended_arg_count;
3672 goto start;
3673 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003674}
3675
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003676static PyObject *
3677dict_keys_inorder(PyObject *dict, int offset)
3678{
3679 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003680 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003681
3682 tuple = PyTuple_New(size);
3683 if (tuple == NULL)
3684 return NULL;
3685 while (PyDict_Next(dict, &pos, &k, &v)) {
3686 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003687 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003688 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003689 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003690 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003691 PyTuple_SET_ITEM(tuple, i - offset, k);
3692 }
3693 return tuple;
3694}
3695
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003696static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003697compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003698{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699 PySTEntryObject *ste = c->u->u_ste;
3700 int flags = 0, n;
3701 if (ste->ste_type != ModuleBlock)
3702 flags |= CO_NEWLOCALS;
3703 if (ste->ste_type == FunctionBlock) {
3704 if (!ste->ste_unoptimized)
3705 flags |= CO_OPTIMIZED;
3706 if (ste->ste_nested)
3707 flags |= CO_NESTED;
3708 if (ste->ste_generator)
3709 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003710 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711 if (ste->ste_varargs)
3712 flags |= CO_VARARGS;
3713 if (ste->ste_varkeywords)
3714 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003715 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003716 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003717
3718 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003719 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003720
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 n = PyDict_Size(c->u->u_freevars);
3722 if (n < 0)
3723 return -1;
3724 if (n == 0) {
3725 n = PyDict_Size(c->u->u_cellvars);
3726 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003727 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728 if (n == 0) {
3729 flags |= CO_NOFREE;
3730 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003731 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003732
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003733 return flags;
3734}
3735
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736static PyCodeObject *
3737makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003738{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 PyObject *tmp;
3740 PyCodeObject *co = NULL;
3741 PyObject *consts = NULL;
3742 PyObject *names = NULL;
3743 PyObject *varnames = NULL;
3744 PyObject *filename = NULL;
3745 PyObject *name = NULL;
3746 PyObject *freevars = NULL;
3747 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003748 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003750
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 tmp = dict_keys_inorder(c->u->u_consts, 0);
3752 if (!tmp)
3753 goto error;
3754 consts = PySequence_List(tmp); /* optimize_code requires a list */
3755 Py_DECREF(tmp);
3756
3757 names = dict_keys_inorder(c->u->u_names, 0);
3758 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3759 if (!consts || !names || !varnames)
3760 goto error;
3761
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003762 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3763 if (!cellvars)
3764 goto error;
3765 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3766 if (!freevars)
3767 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 filename = PyString_FromString(c->c_filename);
3769 if (!filename)
3770 goto error;
3771
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003772 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 flags = compute_code_flags(c);
3774 if (flags < 0)
3775 goto error;
3776
Jeremy Hylton644dddc2006-08-21 16:19:37 +00003777 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 if (!bytecode)
3779 goto error;
3780
3781 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3782 if (!tmp)
3783 goto error;
3784 Py_DECREF(consts);
3785 consts = tmp;
3786
3787 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3788 bytecode, consts, names, varnames,
3789 freevars, cellvars,
3790 filename, c->u->u_name,
3791 c->u->u_firstlineno,
3792 a->a_lnotab);
3793 error:
3794 Py_XDECREF(consts);
3795 Py_XDECREF(names);
3796 Py_XDECREF(varnames);
3797 Py_XDECREF(filename);
3798 Py_XDECREF(name);
3799 Py_XDECREF(freevars);
3800 Py_XDECREF(cellvars);
3801 Py_XDECREF(bytecode);
3802 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003803}
3804
Neal Norwitz4ffedad2006-08-04 04:58:47 +00003805
3806/* For debugging purposes only */
3807#if 0
3808static void
3809dump_instr(const struct instr *i)
3810{
3811 const char *jrel = i->i_jrel ? "jrel " : "";
3812 const char *jabs = i->i_jabs ? "jabs " : "";
3813 char arg[128];
3814
3815 *arg = '\0';
3816 if (i->i_hasarg)
3817 sprintf(arg, "arg: %d ", i->i_oparg);
3818
3819 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3820 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3821}
3822
3823static void
3824dump_basicblock(const basicblock *b)
3825{
3826 const char *seen = b->b_seen ? "seen " : "";
3827 const char *b_return = b->b_return ? "return " : "";
3828 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3829 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3830 if (b->b_instr) {
3831 int i;
3832 for (i = 0; i < b->b_iused; i++) {
3833 fprintf(stderr, " [%02d] ", i);
3834 dump_instr(b->b_instr + i);
3835 }
3836 }
3837}
3838#endif
3839
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840static PyCodeObject *
3841assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003842{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 basicblock *b, *entryblock;
3844 struct assembler a;
3845 int i, j, nblocks;
3846 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 /* Make sure every block that falls off the end returns None.
3849 XXX NEXT_BLOCK() isn't quite right, because if the last
3850 block ends with a jump or return b_next shouldn't set.
3851 */
3852 if (!c->u->u_curblock->b_return) {
3853 NEXT_BLOCK(c);
3854 if (addNone)
3855 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3856 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003857 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 nblocks = 0;
3860 entryblock = NULL;
3861 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3862 nblocks++;
3863 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003864 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003865
Neal Norwitzed657552006-07-10 00:04:44 +00003866 /* Set firstlineno if it wasn't explicitly set. */
3867 if (!c->u->u_firstlineno) {
3868 if (entryblock && entryblock->b_instr)
3869 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3870 else
3871 c->u->u_firstlineno = 1;
3872 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3874 goto error;
3875 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003878 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003879
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003880 /* Emit code in reverse postorder from dfs. */
3881 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003882 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 for (j = 0; j < b->b_iused; j++)
3884 if (!assemble_emit(&a, &b->b_instr[j]))
3885 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003886 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3889 goto error;
3890 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3891 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 co = makecode(c, &a);
3894 error:
3895 assemble_free(&a);
3896 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003897}