blob: 464c953b2255673f09c4fe86fa2a06b7760f460f [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.
9 * 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
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
190
191static int inplace_binop(struct compiler *, operator_ty);
192static int expr_constant(expr_ty e);
193
Guido van Rossumc2e20742006-02-27 22:32:47 +0000194static int compiler_with(struct compiler *, stmt_ty);
195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static PyCodeObject *assemble(struct compiler *, int addNone);
197static PyObject *__doc__;
198
199PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 if (privateobj == NULL || !PyString_Check(privateobj) ||
208 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000305 if (!arena)
306 return NULL;
307 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000308 if (mod)
309 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000310 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000311 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000312}
313
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 if (c->c_st)
318 PySymtable_Free(c->c_st);
319 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322}
323
Guido van Rossum79f25d91997-04-29 20:08:16 +0000324static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000326{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 PyObject *v, *k;
329 PyObject *dict = PyDict_New();
330 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 n = PyList_Size(list);
333 for (i = 0; i < n; i++) {
334 v = PyInt_FromLong(i);
335 if (!v) {
336 Py_DECREF(dict);
337 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000338 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
342 Py_XDECREF(k);
343 Py_DECREF(v);
344 Py_DECREF(dict);
345 return NULL;
346 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000347 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 return dict;
351}
352
353/* Return new dict containing names from src that match scope(s).
354
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355src is a symbol table dictionary. If the scope of a name matches
356either scope_type or flag is set, insert it into the new dict. The
357values are integers, starting at offset and increasing by one for
358each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359*/
360
361static PyObject *
362dictbytype(PyObject *src, int scope_type, int flag, int offset)
363{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365 PyObject *k, *v, *dest = PyDict_New();
366
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 assert(offset >= 0);
368 if (dest == NULL)
369 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
371 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 /* XXX this should probably be a macro in symtable.h */
373 assert(PyInt_Check(v));
374 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
377 PyObject *tuple, *item = PyInt_FromLong(i);
378 if (item == NULL) {
379 Py_DECREF(dest);
380 return NULL;
381 }
382 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
385 Py_DECREF(item);
386 Py_DECREF(dest);
387 Py_XDECREF(tuple);
388 return NULL;
389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 }
394 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000395}
396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000397/*
398
399Leave this debugging code for just a little longer.
400
401static void
402compiler_display_symbols(PyObject *name, PyObject *symbols)
403{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000404PyObject *key, *value;
405int flags;
406Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
409while (PyDict_Next(symbols, &pos, &key, &value)) {
410flags = PyInt_AsLong(value);
411fprintf(stderr, "var %s:", PyString_AS_STRING(key));
412if (flags & DEF_GLOBAL)
413fprintf(stderr, " declared_global");
414if (flags & DEF_LOCAL)
415fprintf(stderr, " local");
416if (flags & DEF_PARAM)
417fprintf(stderr, " param");
418if (flags & DEF_STAR)
419fprintf(stderr, " stararg");
420if (flags & DEF_DOUBLESTAR)
421fprintf(stderr, " starstar");
422if (flags & DEF_INTUPLE)
423fprintf(stderr, " tuple");
424if (flags & DEF_FREE)
425fprintf(stderr, " free");
426if (flags & DEF_FREE_GLOBAL)
427fprintf(stderr, " global");
428if (flags & DEF_FREE_CLASS)
429fprintf(stderr, " free/class");
430if (flags & DEF_IMPORT)
431fprintf(stderr, " import");
432fprintf(stderr, "\n");
433}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000434 fprintf(stderr, "\n");
435}
436*/
437
438static void
439compiler_unit_check(struct compiler_unit *u)
440{
441 basicblock *block;
442 for (block = u->u_blocks; block != NULL; block = block->b_list) {
443 assert(block != (void *)0xcbcbcbcb);
444 assert(block != (void *)0xfbfbfbfb);
445 assert(block != (void *)0xdbdbdbdb);
446 if (block->b_instr != NULL) {
447 assert(block->b_ialloc > 0);
448 assert(block->b_iused > 0);
449 assert(block->b_ialloc >= block->b_iused);
450 }
451 else {
452 assert (block->b_iused == 0);
453 assert (block->b_ialloc == 0);
454 }
455 }
456}
457
458static void
459compiler_unit_free(struct compiler_unit *u)
460{
461 basicblock *b, *next;
462
463 compiler_unit_check(u);
464 b = u->u_blocks;
465 while (b != NULL) {
466 if (b->b_instr)
467 PyObject_Free((void *)b->b_instr);
468 next = b->b_list;
469 PyObject_Free((void *)b);
470 b = next;
471 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 Py_CLEAR(u->u_ste);
473 Py_CLEAR(u->u_name);
474 Py_CLEAR(u->u_consts);
475 Py_CLEAR(u->u_names);
476 Py_CLEAR(u->u_varnames);
477 Py_CLEAR(u->u_freevars);
478 Py_CLEAR(u->u_cellvars);
479 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480 PyObject_Free(u);
481}
482
483static int
484compiler_enter_scope(struct compiler *c, identifier name, void *key,
485 int lineno)
486{
487 struct compiler_unit *u;
488
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
490 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000491 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 PyErr_NoMemory();
493 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000494 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496 u->u_argcount = 0;
497 u->u_ste = PySymtable_Lookup(c->c_st, key);
498 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000499 compiler_unit_free(u);
500 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501 }
502 Py_INCREF(name);
503 u->u_name = name;
504 u->u_varnames = list2dict(u->u_ste->ste_varnames);
505 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 if (!u->u_varnames || !u->u_cellvars) {
507 compiler_unit_free(u);
508 return 0;
509 }
510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000513 if (!u->u_freevars) {
514 compiler_unit_free(u);
515 return 0;
516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
518 u->u_blocks = NULL;
519 u->u_tmpname = 0;
520 u->u_nfblocks = 0;
521 u->u_firstlineno = lineno;
522 u->u_lineno = 0;
523 u->u_lineno_set = false;
524 u->u_consts = PyDict_New();
525 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000526 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 return 0;
528 }
529 u->u_names = PyDict_New();
530 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000531 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532 return 0;
533 }
534
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000535 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
537 /* Push the old compiler_unit on the stack. */
538 if (c->u) {
539 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
541 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000542 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543 return 0;
544 }
545 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000546 u->u_private = c->u->u_private;
547 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548 }
549 c->u = u;
550
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000551 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000552 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553 return 0;
554
555 return 1;
556}
557
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000558static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559compiler_exit_scope(struct compiler *c)
560{
561 int n;
562 PyObject *wrapper;
563
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000564 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565 compiler_unit_free(c->u);
566 /* Restore c->u to the parent unit. */
567 n = PyList_GET_SIZE(c->c_stack) - 1;
568 if (n >= 0) {
569 wrapper = PyList_GET_ITEM(c->c_stack, n);
570 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000571 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000572 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000574 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 compiler_unit_check(c->u);
576 }
577 else
578 c->u = NULL;
579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580}
581
Guido van Rossumc2e20742006-02-27 22:32:47 +0000582/* Allocate a new "anonymous" local variable.
583 Used by list comprehensions and with statements.
584*/
585
586static PyObject *
587compiler_new_tmpname(struct compiler *c)
588{
589 char tmpname[256];
590 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
591 return PyString_FromString(tmpname);
592}
593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594/* Allocate a new block and return a pointer to it.
595 Returns NULL on error.
596*/
597
598static basicblock *
599compiler_new_block(struct compiler *c)
600{
601 basicblock *b;
602 struct compiler_unit *u;
603
604 u = c->u;
605 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000606 if (b == NULL) {
607 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612 b->b_list = u->u_blocks;
613 u->u_blocks = b;
614 return b;
615}
616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617static basicblock *
618compiler_use_new_block(struct compiler *c)
619{
620 basicblock *block = compiler_new_block(c);
621 if (block == NULL)
622 return NULL;
623 c->u->u_curblock = block;
624 return block;
625}
626
627static basicblock *
628compiler_next_block(struct compiler *c)
629{
630 basicblock *block = compiler_new_block(c);
631 if (block == NULL)
632 return NULL;
633 c->u->u_curblock->b_next = block;
634 c->u->u_curblock = block;
635 return block;
636}
637
638static basicblock *
639compiler_use_next_block(struct compiler *c, basicblock *block)
640{
641 assert(block != NULL);
642 c->u->u_curblock->b_next = block;
643 c->u->u_curblock = block;
644 return block;
645}
646
647/* Returns the offset of the next instruction in the current block's
648 b_instr array. Resizes the b_instr as necessary.
649 Returns -1 on failure.
650 */
651
652static int
653compiler_next_instr(struct compiler *c, basicblock *b)
654{
655 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 b->b_instr = (struct instr *)PyObject_Malloc(
658 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659 if (b->b_instr == NULL) {
660 PyErr_NoMemory();
661 return -1;
662 }
663 b->b_ialloc = DEFAULT_BLOCK_SIZE;
664 memset((char *)b->b_instr, 0,
665 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 size_t oldsize, newsize;
670 oldsize = b->b_ialloc * sizeof(struct instr);
671 newsize = oldsize << 1;
672 if (newsize == 0) {
673 PyErr_NoMemory();
674 return -1;
675 }
676 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 if (tmp == NULL) {
680 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682 }
683 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
685 }
686 return b->b_iused++;
687}
688
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689/* Set the i_lineno member of the instruction at offse off if the
690 line number for the current expression/statement (?) has not
691 already been set. If it has been set, the call has no effect.
692
693 Every time a new node is b
694 */
695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696static void
697compiler_set_lineno(struct compiler *c, int off)
698{
699 basicblock *b;
700 if (c->u->u_lineno_set)
701 return;
702 c->u->u_lineno_set = true;
703 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000704 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705}
706
707static int
708opcode_stack_effect(int opcode, int oparg)
709{
710 switch (opcode) {
711 case POP_TOP:
712 return -1;
713 case ROT_TWO:
714 case ROT_THREE:
715 return 0;
716 case DUP_TOP:
717 return 1;
718 case ROT_FOUR:
719 return 0;
720
721 case UNARY_POSITIVE:
722 case UNARY_NEGATIVE:
723 case UNARY_NOT:
724 case UNARY_CONVERT:
725 case UNARY_INVERT:
726 return 0;
727
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000728 case LIST_APPEND:
729 return -2;
730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000731 case BINARY_POWER:
732 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733 case BINARY_MODULO:
734 case BINARY_ADD:
735 case BINARY_SUBTRACT:
736 case BINARY_SUBSCR:
737 case BINARY_FLOOR_DIVIDE:
738 case BINARY_TRUE_DIVIDE:
739 return -1;
740 case INPLACE_FLOOR_DIVIDE:
741 case INPLACE_TRUE_DIVIDE:
742 return -1;
743
744 case SLICE+0:
745 return 1;
746 case SLICE+1:
747 return 0;
748 case SLICE+2:
749 return 0;
750 case SLICE+3:
751 return -1;
752
753 case STORE_SLICE+0:
754 return -2;
755 case STORE_SLICE+1:
756 return -3;
757 case STORE_SLICE+2:
758 return -3;
759 case STORE_SLICE+3:
760 return -4;
761
762 case DELETE_SLICE+0:
763 return -1;
764 case DELETE_SLICE+1:
765 return -2;
766 case DELETE_SLICE+2:
767 return -2;
768 case DELETE_SLICE+3:
769 return -3;
770
771 case INPLACE_ADD:
772 case INPLACE_SUBTRACT:
773 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case INPLACE_MODULO:
775 return -1;
776 case STORE_SUBSCR:
777 return -3;
778 case DELETE_SUBSCR:
779 return -2;
780
781 case BINARY_LSHIFT:
782 case BINARY_RSHIFT:
783 case BINARY_AND:
784 case BINARY_XOR:
785 case BINARY_OR:
786 return -1;
787 case INPLACE_POWER:
788 return -1;
789 case GET_ITER:
790 return 0;
791
792 case PRINT_EXPR:
793 return -1;
794 case PRINT_ITEM:
795 return -1;
796 case PRINT_NEWLINE:
797 return 0;
798 case PRINT_ITEM_TO:
799 return -2;
800 case PRINT_NEWLINE_TO:
801 return -1;
802 case INPLACE_LSHIFT:
803 case INPLACE_RSHIFT:
804 case INPLACE_AND:
805 case INPLACE_XOR:
806 case INPLACE_OR:
807 return -1;
808 case BREAK_LOOP:
809 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000810 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000811 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812 case LOAD_LOCALS:
813 return 1;
814 case RETURN_VALUE:
815 return -1;
816 case IMPORT_STAR:
817 return -1;
818 case EXEC_STMT:
819 return -3;
820 case YIELD_VALUE:
821 return 0;
822
823 case POP_BLOCK:
824 return 0;
825 case END_FINALLY:
826 return -1; /* or -2 or -3 if exception occurred */
827 case BUILD_CLASS:
828 return -2;
829
830 case STORE_NAME:
831 return -1;
832 case DELETE_NAME:
833 return 0;
834 case UNPACK_SEQUENCE:
835 return oparg-1;
836 case FOR_ITER:
837 return 1;
838
839 case STORE_ATTR:
840 return -2;
841 case DELETE_ATTR:
842 return -1;
843 case STORE_GLOBAL:
844 return -1;
845 case DELETE_GLOBAL:
846 return 0;
847 case DUP_TOPX:
848 return oparg;
849 case LOAD_CONST:
850 return 1;
851 case LOAD_NAME:
852 return 1;
853 case BUILD_TUPLE:
854 case BUILD_LIST:
855 return 1-oparg;
856 case BUILD_MAP:
857 return 1;
858 case LOAD_ATTR:
859 return 0;
860 case COMPARE_OP:
861 return -1;
862 case IMPORT_NAME:
863 return 0;
864 case IMPORT_FROM:
865 return 1;
866
867 case JUMP_FORWARD:
868 case JUMP_IF_FALSE:
869 case JUMP_IF_TRUE:
870 case JUMP_ABSOLUTE:
871 return 0;
872
873 case LOAD_GLOBAL:
874 return 1;
875
876 case CONTINUE_LOOP:
877 return 0;
878 case SETUP_LOOP:
879 return 0;
880 case SETUP_EXCEPT:
881 case SETUP_FINALLY:
882 return 3; /* actually pushed by an exception */
883
884 case LOAD_FAST:
885 return 1;
886 case STORE_FAST:
887 return -1;
888 case DELETE_FAST:
889 return 0;
890
891 case RAISE_VARARGS:
892 return -oparg;
893#define NARGS(o) (((o) % 256) + 2*((o) / 256))
894 case CALL_FUNCTION:
895 return -NARGS(oparg);
896 case CALL_FUNCTION_VAR:
897 case CALL_FUNCTION_KW:
898 return -NARGS(oparg)-1;
899 case CALL_FUNCTION_VAR_KW:
900 return -NARGS(oparg)-2;
901#undef NARGS
902 case MAKE_FUNCTION:
903 return -oparg;
904 case BUILD_SLICE:
905 if (oparg == 3)
906 return -2;
907 else
908 return -1;
909
910 case MAKE_CLOSURE:
911 return -oparg;
912 case LOAD_CLOSURE:
913 return 1;
914 case LOAD_DEREF:
915 return 1;
916 case STORE_DEREF:
917 return -1;
918 default:
919 fprintf(stderr, "opcode = %d\n", opcode);
920 Py_FatalError("opcode_stack_effect()");
921
922 }
923 return 0; /* not reachable */
924}
925
926/* Add an opcode with no argument.
927 Returns 0 on failure, 1 on success.
928*/
929
930static int
931compiler_addop(struct compiler *c, int opcode)
932{
933 basicblock *b;
934 struct instr *i;
935 int off;
936 off = compiler_next_instr(c, c->u->u_curblock);
937 if (off < 0)
938 return 0;
939 b = c->u->u_curblock;
940 i = &b->b_instr[off];
941 i->i_opcode = opcode;
942 i->i_hasarg = 0;
943 if (opcode == RETURN_VALUE)
944 b->b_return = 1;
945 compiler_set_lineno(c, off);
946 return 1;
947}
948
949static int
950compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
951{
952 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000953 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 /* necessary to make sure types aren't coerced (e.g., int and long) */
956 t = PyTuple_Pack(2, o, o->ob_type);
957 if (t == NULL)
958 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
960 v = PyDict_GetItem(dict, t);
961 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000962 if (PyErr_Occurred())
963 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000964 arg = PyDict_Size(dict);
965 v = PyInt_FromLong(arg);
966 if (!v) {
967 Py_DECREF(t);
968 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000969 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 if (PyDict_SetItem(dict, t, v) < 0) {
971 Py_DECREF(t);
972 Py_DECREF(v);
973 return -1;
974 }
975 Py_DECREF(v);
976 }
977 else
978 arg = PyInt_AsLong(v);
979 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981}
982
983static int
984compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
985 PyObject *o)
986{
987 int arg = compiler_add_o(c, dict, o);
988 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000989 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000990 return compiler_addop_i(c, opcode, arg);
991}
992
993static int
994compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996{
997 int arg;
998 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
999 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001 arg = compiler_add_o(c, dict, mangled);
1002 Py_DECREF(mangled);
1003 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005 return compiler_addop_i(c, opcode, arg);
1006}
1007
1008/* Add an opcode with an integer argument.
1009 Returns 0 on failure, 1 on success.
1010*/
1011
1012static int
1013compiler_addop_i(struct compiler *c, int opcode, int oparg)
1014{
1015 struct instr *i;
1016 int off;
1017 off = compiler_next_instr(c, c->u->u_curblock);
1018 if (off < 0)
1019 return 0;
1020 i = &c->u->u_curblock->b_instr[off];
1021 i->i_opcode = opcode;
1022 i->i_oparg = oparg;
1023 i->i_hasarg = 1;
1024 compiler_set_lineno(c, off);
1025 return 1;
1026}
1027
1028static int
1029compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1030{
1031 struct instr *i;
1032 int off;
1033
1034 assert(b != NULL);
1035 off = compiler_next_instr(c, c->u->u_curblock);
1036 if (off < 0)
1037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001038 i = &c->u->u_curblock->b_instr[off];
1039 i->i_opcode = opcode;
1040 i->i_target = b;
1041 i->i_hasarg = 1;
1042 if (absolute)
1043 i->i_jabs = 1;
1044 else
1045 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001046 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 return 1;
1048}
1049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001050/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1051 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052 it as the current block. NEXT_BLOCK() also creates an implicit jump
1053 from the current block to the new block.
1054*/
1055
1056/* XXX The returns inside these macros make it impossible to decref
1057 objects created in the local function.
1058*/
1059
1060
1061#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001062 if (compiler_use_new_block((C)) == NULL) \
1063 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001064}
1065
1066#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001067 if (compiler_next_block((C)) == NULL) \
1068 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069}
1070
1071#define ADDOP(C, OP) { \
1072 if (!compiler_addop((C), (OP))) \
1073 return 0; \
1074}
1075
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001076#define ADDOP_IN_SCOPE(C, OP) { \
1077 if (!compiler_addop((C), (OP))) { \
1078 compiler_exit_scope(c); \
1079 return 0; \
1080 } \
1081}
1082
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083#define ADDOP_O(C, OP, O, TYPE) { \
1084 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1085 return 0; \
1086}
1087
1088#define ADDOP_NAME(C, OP, O, TYPE) { \
1089 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1090 return 0; \
1091}
1092
1093#define ADDOP_I(C, OP, O) { \
1094 if (!compiler_addop_i((C), (OP), (O))) \
1095 return 0; \
1096}
1097
1098#define ADDOP_JABS(C, OP, O) { \
1099 if (!compiler_addop_j((C), (OP), (O), 1)) \
1100 return 0; \
1101}
1102
1103#define ADDOP_JREL(C, OP, O) { \
1104 if (!compiler_addop_j((C), (OP), (O), 0)) \
1105 return 0; \
1106}
1107
1108/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1109 the ASDL name to synthesize the name of the C type and the visit function.
1110*/
1111
1112#define VISIT(C, TYPE, V) {\
1113 if (!compiler_visit_ ## TYPE((C), (V))) \
1114 return 0; \
1115}
1116
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001117#define VISIT_IN_SCOPE(C, TYPE, V) {\
1118 if (!compiler_visit_ ## TYPE((C), (V))) { \
1119 compiler_exit_scope(c); \
1120 return 0; \
1121 } \
1122}
1123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124#define VISIT_SLICE(C, V, CTX) {\
1125 if (!compiler_visit_slice((C), (V), (CTX))) \
1126 return 0; \
1127}
1128
1129#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001132 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001133 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134 if (!compiler_visit_ ## TYPE((C), elt)) \
1135 return 0; \
1136 } \
1137}
1138
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001141 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001142 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001144 if (!compiler_visit_ ## TYPE((C), elt)) { \
1145 compiler_exit_scope(c); \
1146 return 0; \
1147 } \
1148 } \
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151static int
1152compiler_isdocstring(stmt_ty s)
1153{
1154 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return s->v.Expr.value->kind == Str_kind;
1157}
1158
1159/* Compile a sequence of statements, checking for a docstring. */
1160
1161static int
1162compiler_body(struct compiler *c, asdl_seq *stmts)
1163{
1164 int i = 0;
1165 stmt_ty st;
1166
1167 if (!asdl_seq_LEN(stmts))
1168 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001169 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001170 if (compiler_isdocstring(st)) {
1171 i = 1;
1172 VISIT(c, expr, st->v.Expr.value);
1173 if (!compiler_nameop(c, __doc__, Store))
1174 return 0;
1175 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001176 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 return 1;
1179}
1180
1181static PyCodeObject *
1182compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001183{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001184 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001185 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186 static PyObject *module;
1187 if (!module) {
1188 module = PyString_FromString("<module>");
1189 if (!module)
1190 return NULL;
1191 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001192 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1193 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001194 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 switch (mod->kind) {
1196 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001197 if (!compiler_body(c, mod->v.Module.body)) {
1198 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 break;
1202 case Interactive_kind:
1203 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 VISIT_SEQ_IN_SCOPE(c, stmt,
1205 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206 break;
1207 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001208 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001209 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 break;
1211 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001212 PyErr_SetString(PyExc_SystemError,
1213 "suite should not be possible");
1214 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001215 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001216 PyErr_Format(PyExc_SystemError,
1217 "module kind %d should not be possible",
1218 mod->kind);
1219 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221 co = assemble(c, addNone);
1222 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001223 return co;
1224}
1225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226/* The test for LOCAL must come before the test for FREE in order to
1227 handle classes where name is both local and free. The local var is
1228 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001229*/
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231static int
1232get_ref_type(struct compiler *c, PyObject *name)
1233{
1234 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 if (scope == 0) {
1236 char buf[350];
1237 PyOS_snprintf(buf, sizeof(buf),
1238 "unknown scope for %.100s in %.100s(%s) in %s\n"
1239 "symbols: %s\nlocals: %s\nglobals: %s\n",
1240 PyString_AS_STRING(name),
1241 PyString_AS_STRING(c->u->u_name),
1242 PyObject_REPR(c->u->u_ste->ste_id),
1243 c->c_filename,
1244 PyObject_REPR(c->u->u_ste->ste_symbols),
1245 PyObject_REPR(c->u->u_varnames),
1246 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001247 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001248 Py_FatalError(buf);
1249 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001251 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001252}
1253
1254static int
1255compiler_lookup_arg(PyObject *dict, PyObject *name)
1256{
1257 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001260 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001262 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001264 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 return PyInt_AS_LONG(v);
1266}
1267
1268static int
1269compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1270{
1271 int i, free = PyCode_GetNumFree(co);
1272 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001273 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1274 ADDOP_I(c, MAKE_FUNCTION, args);
1275 return 1;
1276 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 for (i = 0; i < free; ++i) {
1278 /* Bypass com_addop_varname because it will generate
1279 LOAD_DEREF but LOAD_CLOSURE is needed.
1280 */
1281 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1282 int arg, reftype;
1283
1284 /* Special case: If a class contains a method with a
1285 free variable that has the same name as a method,
1286 the name will be considered free *and* local in the
1287 class. It should be handled by the closure, as
1288 well as by the normal name loookup logic.
1289 */
1290 reftype = get_ref_type(c, name);
1291 if (reftype == CELL)
1292 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1293 else /* (reftype == FREE) */
1294 arg = compiler_lookup_arg(c->u->u_freevars, name);
1295 if (arg == -1) {
1296 printf("lookup %s in %s %d %d\n"
1297 "freevars of %s: %s\n",
1298 PyObject_REPR(name),
1299 PyString_AS_STRING(c->u->u_name),
1300 reftype, arg,
1301 PyString_AS_STRING(co->co_name),
1302 PyObject_REPR(co->co_freevars));
1303 Py_FatalError("compiler_make_closure()");
1304 }
1305 ADDOP_I(c, LOAD_CLOSURE, arg);
1306 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001309 ADDOP_I(c, MAKE_CLOSURE, args);
1310 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314compiler_decorators(struct compiler *c, asdl_seq* decos)
1315{
1316 int i;
1317
1318 if (!decos)
1319 return 1;
1320
1321 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001323 }
1324 return 1;
1325}
1326
1327static int
1328compiler_arguments(struct compiler *c, arguments_ty args)
1329{
1330 int i;
1331 int n = asdl_seq_LEN(args->args);
1332 /* Correctly handle nested argument lists */
1333 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001335 if (arg->kind == Tuple_kind) {
1336 PyObject *id = PyString_FromFormat(".%d", i);
1337 if (id == NULL) {
1338 return 0;
1339 }
1340 if (!compiler_nameop(c, id, Load)) {
1341 Py_DECREF(id);
1342 return 0;
1343 }
1344 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001345 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346 }
1347 }
1348 return 1;
1349}
1350
1351static int
1352compiler_function(struct compiler *c, stmt_ty s)
1353{
1354 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001355 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 arguments_ty args = s->v.FunctionDef.args;
1357 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001358 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001359 int i, n, docstring;
1360
1361 assert(s->kind == FunctionDef_kind);
1362
1363 if (!compiler_decorators(c, decos))
1364 return 0;
1365 if (args->defaults)
1366 VISIT_SEQ(c, expr, args->defaults);
1367 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1368 s->lineno))
1369 return 0;
1370
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001371 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001372 docstring = compiler_isdocstring(st);
1373 if (docstring)
1374 first_const = st->v.Expr.value->v.Str.s;
1375 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001377 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001378 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001380 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 compiler_arguments(c, args);
1382
1383 c->u->u_argcount = asdl_seq_LEN(args->args);
1384 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001385 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1388 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001389 }
1390 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001391 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392 if (co == NULL)
1393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001395 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001396 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397
1398 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1399 ADDOP_I(c, CALL_FUNCTION, 1);
1400 }
1401
1402 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1403}
1404
1405static int
1406compiler_class(struct compiler *c, stmt_ty s)
1407{
1408 int n;
1409 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001410 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411 /* push class name on stack, needed by BUILD_CLASS */
1412 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1413 /* push the tuple of base classes on the stack */
1414 n = asdl_seq_LEN(s->v.ClassDef.bases);
1415 if (n > 0)
1416 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1417 ADDOP_I(c, BUILD_TUPLE, n);
1418 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1419 s->lineno))
1420 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001421 c->u->u_private = s->v.ClassDef.name;
1422 Py_INCREF(c->u->u_private);
1423 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001424 if (!str || !compiler_nameop(c, str, Load)) {
1425 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001426 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001428 }
1429
1430 Py_DECREF(str);
1431 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (!str || !compiler_nameop(c, str, Store)) {
1433 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001434 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001435 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001436 }
1437 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001439 if (!compiler_body(c, s->v.ClassDef.body)) {
1440 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001442 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001444 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1445 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001447 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448 if (co == NULL)
1449 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001451 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001452 Py_DECREF(co);
1453
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454 ADDOP_I(c, CALL_FUNCTION, 0);
1455 ADDOP(c, BUILD_CLASS);
1456 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1457 return 0;
1458 return 1;
1459}
1460
1461static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001462compiler_ifexp(struct compiler *c, expr_ty e)
1463{
1464 basicblock *end, *next;
1465
1466 assert(e->kind == IfExp_kind);
1467 end = compiler_new_block(c);
1468 if (end == NULL)
1469 return 0;
1470 next = compiler_new_block(c);
1471 if (next == NULL)
1472 return 0;
1473 VISIT(c, expr, e->v.IfExp.test);
1474 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1475 ADDOP(c, POP_TOP);
1476 VISIT(c, expr, e->v.IfExp.body);
1477 ADDOP_JREL(c, JUMP_FORWARD, end);
1478 compiler_use_next_block(c, next);
1479 ADDOP(c, POP_TOP);
1480 VISIT(c, expr, e->v.IfExp.orelse);
1481 compiler_use_next_block(c, end);
1482 return 1;
1483}
1484
1485static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001486compiler_lambda(struct compiler *c, expr_ty e)
1487{
1488 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001489 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490 arguments_ty args = e->v.Lambda.args;
1491 assert(e->kind == Lambda_kind);
1492
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001493 if (!name) {
1494 name = PyString_InternFromString("<lambda>");
1495 if (!name)
1496 return 0;
1497 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498
1499 if (args->defaults)
1500 VISIT_SEQ(c, expr, args->defaults);
1501 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1502 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001503
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001504 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505 compiler_arguments(c, args);
1506
1507 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001508 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1509 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001511 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 if (co == NULL)
1513 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001515 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001516 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517
1518 return 1;
1519}
1520
1521static int
1522compiler_print(struct compiler *c, stmt_ty s)
1523{
1524 int i, n;
1525 bool dest;
1526
1527 assert(s->kind == Print_kind);
1528 n = asdl_seq_LEN(s->v.Print.values);
1529 dest = false;
1530 if (s->v.Print.dest) {
1531 VISIT(c, expr, s->v.Print.dest);
1532 dest = true;
1533 }
1534 for (i = 0; i < n; i++) {
1535 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1536 if (dest) {
1537 ADDOP(c, DUP_TOP);
1538 VISIT(c, expr, e);
1539 ADDOP(c, ROT_TWO);
1540 ADDOP(c, PRINT_ITEM_TO);
1541 }
1542 else {
1543 VISIT(c, expr, e);
1544 ADDOP(c, PRINT_ITEM);
1545 }
1546 }
1547 if (s->v.Print.nl) {
1548 if (dest)
1549 ADDOP(c, PRINT_NEWLINE_TO)
1550 else
1551 ADDOP(c, PRINT_NEWLINE)
1552 }
1553 else if (dest)
1554 ADDOP(c, POP_TOP);
1555 return 1;
1556}
1557
1558static int
1559compiler_if(struct compiler *c, stmt_ty s)
1560{
1561 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001562 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563 assert(s->kind == If_kind);
1564 end = compiler_new_block(c);
1565 if (end == NULL)
1566 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 next = compiler_new_block(c);
1568 if (next == NULL)
1569 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001570
1571 constant = expr_constant(s->v.If.test);
1572 /* constant = 0: "if 0"
1573 * constant = 1: "if 1", "if 2", ...
1574 * constant = -1: rest */
1575 if (constant == 0) {
1576 if (s->v.If.orelse)
1577 VISIT_SEQ(c, stmt, s->v.If.orelse);
1578 } else if (constant == 1) {
1579 VISIT_SEQ(c, stmt, s->v.If.body);
1580 } else {
1581 VISIT(c, expr, s->v.If.test);
1582 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1583 ADDOP(c, POP_TOP);
1584 VISIT_SEQ(c, stmt, s->v.If.body);
1585 ADDOP_JREL(c, JUMP_FORWARD, end);
1586 compiler_use_next_block(c, next);
1587 ADDOP(c, POP_TOP);
1588 if (s->v.If.orelse)
1589 VISIT_SEQ(c, stmt, s->v.If.orelse);
1590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591 compiler_use_next_block(c, end);
1592 return 1;
1593}
1594
1595static int
1596compiler_for(struct compiler *c, stmt_ty s)
1597{
1598 basicblock *start, *cleanup, *end;
1599
1600 start = compiler_new_block(c);
1601 cleanup = compiler_new_block(c);
1602 end = compiler_new_block(c);
1603 if (start == NULL || end == NULL || cleanup == NULL)
1604 return 0;
1605 ADDOP_JREL(c, SETUP_LOOP, end);
1606 if (!compiler_push_fblock(c, LOOP, start))
1607 return 0;
1608 VISIT(c, expr, s->v.For.iter);
1609 ADDOP(c, GET_ITER);
1610 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001611 /* XXX(nnorwitz): is there a better way to handle this?
1612 for loops are special, we want to be able to trace them
1613 each time around, so we need to set an extra line number. */
1614 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001615 ADDOP_JREL(c, FOR_ITER, cleanup);
1616 VISIT(c, expr, s->v.For.target);
1617 VISIT_SEQ(c, stmt, s->v.For.body);
1618 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1619 compiler_use_next_block(c, cleanup);
1620 ADDOP(c, POP_BLOCK);
1621 compiler_pop_fblock(c, LOOP, start);
1622 VISIT_SEQ(c, stmt, s->v.For.orelse);
1623 compiler_use_next_block(c, end);
1624 return 1;
1625}
1626
1627static int
1628compiler_while(struct compiler *c, stmt_ty s)
1629{
1630 basicblock *loop, *orelse, *end, *anchor = NULL;
1631 int constant = expr_constant(s->v.While.test);
1632
1633 if (constant == 0)
1634 return 1;
1635 loop = compiler_new_block(c);
1636 end = compiler_new_block(c);
1637 if (constant == -1) {
1638 anchor = compiler_new_block(c);
1639 if (anchor == NULL)
1640 return 0;
1641 }
1642 if (loop == NULL || end == NULL)
1643 return 0;
1644 if (s->v.While.orelse) {
1645 orelse = compiler_new_block(c);
1646 if (orelse == NULL)
1647 return 0;
1648 }
1649 else
1650 orelse = NULL;
1651
1652 ADDOP_JREL(c, SETUP_LOOP, end);
1653 compiler_use_next_block(c, loop);
1654 if (!compiler_push_fblock(c, LOOP, loop))
1655 return 0;
1656 if (constant == -1) {
1657 VISIT(c, expr, s->v.While.test);
1658 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1659 ADDOP(c, POP_TOP);
1660 }
1661 VISIT_SEQ(c, stmt, s->v.While.body);
1662 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1663
1664 /* XXX should the two POP instructions be in a separate block
1665 if there is no else clause ?
1666 */
1667
1668 if (constant == -1) {
1669 compiler_use_next_block(c, anchor);
1670 ADDOP(c, POP_TOP);
1671 ADDOP(c, POP_BLOCK);
1672 }
1673 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001674 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 VISIT_SEQ(c, stmt, s->v.While.orelse);
1676 compiler_use_next_block(c, end);
1677
1678 return 1;
1679}
1680
1681static int
1682compiler_continue(struct compiler *c)
1683{
1684 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1685 int i;
1686
1687 if (!c->u->u_nfblocks)
1688 return compiler_error(c, LOOP_ERROR_MSG);
1689 i = c->u->u_nfblocks - 1;
1690 switch (c->u->u_fblock[i].fb_type) {
1691 case LOOP:
1692 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1693 break;
1694 case EXCEPT:
1695 case FINALLY_TRY:
1696 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1697 ;
1698 if (i == -1)
1699 return compiler_error(c, LOOP_ERROR_MSG);
1700 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1701 break;
1702 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001703 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 "'continue' not supported inside 'finally' clause");
1705 }
1706
1707 return 1;
1708}
1709
1710/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1711
1712 SETUP_FINALLY L
1713 <code for body>
1714 POP_BLOCK
1715 LOAD_CONST <None>
1716 L: <code for finalbody>
1717 END_FINALLY
1718
1719 The special instructions use the block stack. Each block
1720 stack entry contains the instruction that created it (here
1721 SETUP_FINALLY), the level of the value stack at the time the
1722 block stack entry was created, and a label (here L).
1723
1724 SETUP_FINALLY:
1725 Pushes the current value stack level and the label
1726 onto the block stack.
1727 POP_BLOCK:
1728 Pops en entry from the block stack, and pops the value
1729 stack until its level is the same as indicated on the
1730 block stack. (The label is ignored.)
1731 END_FINALLY:
1732 Pops a variable number of entries from the *value* stack
1733 and re-raises the exception they specify. The number of
1734 entries popped depends on the (pseudo) exception type.
1735
1736 The block stack is unwound when an exception is raised:
1737 when a SETUP_FINALLY entry is found, the exception is pushed
1738 onto the value stack (and the exception condition is cleared),
1739 and the interpreter jumps to the label gotten from the block
1740 stack.
1741*/
1742
1743static int
1744compiler_try_finally(struct compiler *c, stmt_ty s)
1745{
1746 basicblock *body, *end;
1747 body = compiler_new_block(c);
1748 end = compiler_new_block(c);
1749 if (body == NULL || end == NULL)
1750 return 0;
1751
1752 ADDOP_JREL(c, SETUP_FINALLY, end);
1753 compiler_use_next_block(c, body);
1754 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1755 return 0;
1756 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1757 ADDOP(c, POP_BLOCK);
1758 compiler_pop_fblock(c, FINALLY_TRY, body);
1759
1760 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1761 compiler_use_next_block(c, end);
1762 if (!compiler_push_fblock(c, FINALLY_END, end))
1763 return 0;
1764 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1765 ADDOP(c, END_FINALLY);
1766 compiler_pop_fblock(c, FINALLY_END, end);
1767
1768 return 1;
1769}
1770
1771/*
1772 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1773 (The contents of the value stack is shown in [], with the top
1774 at the right; 'tb' is trace-back info, 'val' the exception's
1775 associated value, and 'exc' the exception.)
1776
1777 Value stack Label Instruction Argument
1778 [] SETUP_EXCEPT L1
1779 [] <code for S>
1780 [] POP_BLOCK
1781 [] JUMP_FORWARD L0
1782
1783 [tb, val, exc] L1: DUP )
1784 [tb, val, exc, exc] <evaluate E1> )
1785 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1786 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1787 [tb, val, exc, 1] POP )
1788 [tb, val, exc] POP
1789 [tb, val] <assign to V1> (or POP if no V1)
1790 [tb] POP
1791 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001792 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793
1794 [tb, val, exc, 0] L2: POP
1795 [tb, val, exc] DUP
1796 .............................etc.......................
1797
1798 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001799 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800
1801 [] L0: <next statement>
1802
1803 Of course, parts are not generated if Vi or Ei is not present.
1804*/
1805static int
1806compiler_try_except(struct compiler *c, stmt_ty s)
1807{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001808 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 int i, n;
1810
1811 body = compiler_new_block(c);
1812 except = compiler_new_block(c);
1813 orelse = compiler_new_block(c);
1814 end = compiler_new_block(c);
1815 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1816 return 0;
1817 ADDOP_JREL(c, SETUP_EXCEPT, except);
1818 compiler_use_next_block(c, body);
1819 if (!compiler_push_fblock(c, EXCEPT, body))
1820 return 0;
1821 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1822 ADDOP(c, POP_BLOCK);
1823 compiler_pop_fblock(c, EXCEPT, body);
1824 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1825 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1826 compiler_use_next_block(c, except);
1827 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001828 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 s->v.TryExcept.handlers, i);
1830 if (!handler->type && i < n-1)
1831 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001832 c->u->u_lineno_set = false;
1833 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 except = compiler_new_block(c);
1835 if (except == NULL)
1836 return 0;
1837 if (handler->type) {
1838 ADDOP(c, DUP_TOP);
1839 VISIT(c, expr, handler->type);
1840 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1841 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1842 ADDOP(c, POP_TOP);
1843 }
1844 ADDOP(c, POP_TOP);
1845 if (handler->name) {
1846 VISIT(c, expr, handler->name);
1847 }
1848 else {
1849 ADDOP(c, POP_TOP);
1850 }
1851 ADDOP(c, POP_TOP);
1852 VISIT_SEQ(c, stmt, handler->body);
1853 ADDOP_JREL(c, JUMP_FORWARD, end);
1854 compiler_use_next_block(c, except);
1855 if (handler->type)
1856 ADDOP(c, POP_TOP);
1857 }
1858 ADDOP(c, END_FINALLY);
1859 compiler_use_next_block(c, orelse);
1860 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1861 compiler_use_next_block(c, end);
1862 return 1;
1863}
1864
1865static int
1866compiler_import_as(struct compiler *c, identifier name, identifier asname)
1867{
1868 /* The IMPORT_NAME opcode was already generated. This function
1869 merely needs to bind the result to a name.
1870
1871 If there is a dot in name, we need to split it and emit a
1872 LOAD_ATTR for each name.
1873 */
1874 const char *src = PyString_AS_STRING(name);
1875 const char *dot = strchr(src, '.');
1876 if (dot) {
1877 /* Consume the base module name to get the first attribute */
1878 src = dot + 1;
1879 while (dot) {
1880 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001881 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001883 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001885 if (!attr)
1886 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001888 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889 src = dot + 1;
1890 }
1891 }
1892 return compiler_nameop(c, asname, Store);
1893}
1894
1895static int
1896compiler_import(struct compiler *c, stmt_ty s)
1897{
1898 /* The Import node stores a module name like a.b.c as a single
1899 string. This is convenient for all cases except
1900 import a.b.c as d
1901 where we need to parse that string to extract the individual
1902 module names.
1903 XXX Perhaps change the representation to make this case simpler?
1904 */
1905 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001908 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001910 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911
Guido van Rossum45aecf42006-03-15 04:58:47 +00001912 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001913 if (level == NULL)
1914 return 0;
1915
1916 ADDOP_O(c, LOAD_CONST, level, consts);
1917 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1919 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1920
1921 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001922 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001923 if (!r)
1924 return r;
1925 }
1926 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927 identifier tmp = alias->name;
1928 const char *base = PyString_AS_STRING(alias->name);
1929 char *dot = strchr(base, '.');
1930 if (dot)
1931 tmp = PyString_FromStringAndSize(base,
1932 dot - base);
1933 r = compiler_nameop(c, tmp, Store);
1934 if (dot) {
1935 Py_DECREF(tmp);
1936 }
1937 if (!r)
1938 return r;
1939 }
1940 }
1941 return 1;
1942}
1943
1944static int
1945compiler_from_import(struct compiler *c, stmt_ty s)
1946{
1947 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948
1949 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001950 PyObject *level;
1951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 if (!names)
1953 return 0;
1954
Guido van Rossum45aecf42006-03-15 04:58:47 +00001955 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001956 if (!level) {
1957 Py_DECREF(names);
1958 return 0;
1959 }
1960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961 /* build up the names */
1962 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001963 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964 Py_INCREF(alias->name);
1965 PyTuple_SET_ITEM(names, i, alias->name);
1966 }
1967
1968 if (s->lineno > c->c_future->ff_lineno) {
1969 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1970 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001971 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972 Py_DECREF(names);
1973 return compiler_error(c,
1974 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001975 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
1977 }
1978 }
1979
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001980 ADDOP_O(c, LOAD_CONST, level, consts);
1981 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001983 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1985 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001986 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 identifier store_name;
1988
1989 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1990 assert(n == 1);
1991 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001992 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 }
1994
1995 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1996 store_name = alias->name;
1997 if (alias->asname)
1998 store_name = alias->asname;
1999
2000 if (!compiler_nameop(c, store_name, Store)) {
2001 Py_DECREF(names);
2002 return 0;
2003 }
2004 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002005 /* remove imported module */
2006 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 return 1;
2008}
2009
2010static int
2011compiler_assert(struct compiler *c, stmt_ty s)
2012{
2013 static PyObject *assertion_error = NULL;
2014 basicblock *end;
2015
2016 if (Py_OptimizeFlag)
2017 return 1;
2018 if (assertion_error == NULL) {
2019 assertion_error = PyString_FromString("AssertionError");
2020 if (assertion_error == NULL)
2021 return 0;
2022 }
2023 VISIT(c, expr, s->v.Assert.test);
2024 end = compiler_new_block(c);
2025 if (end == NULL)
2026 return 0;
2027 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2028 ADDOP(c, POP_TOP);
2029 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2030 if (s->v.Assert.msg) {
2031 VISIT(c, expr, s->v.Assert.msg);
2032 ADDOP_I(c, RAISE_VARARGS, 2);
2033 }
2034 else {
2035 ADDOP_I(c, RAISE_VARARGS, 1);
2036 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002037 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 ADDOP(c, POP_TOP);
2039 return 1;
2040}
2041
2042static int
2043compiler_visit_stmt(struct compiler *c, stmt_ty s)
2044{
2045 int i, n;
2046
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002047 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 c->u->u_lineno = s->lineno;
2049 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002050
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002054 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002056 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 if (c->u->u_ste->ste_type != FunctionBlock)
2058 return compiler_error(c, "'return' outside function");
2059 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 VISIT(c, expr, s->v.Return.value);
2061 }
2062 else
2063 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2064 ADDOP(c, RETURN_VALUE);
2065 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002066 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067 VISIT_SEQ(c, expr, s->v.Delete.targets)
2068 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002069 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070 n = asdl_seq_LEN(s->v.Assign.targets);
2071 VISIT(c, expr, s->v.Assign.value);
2072 for (i = 0; i < n; i++) {
2073 if (i < n - 1)
2074 ADDOP(c, DUP_TOP);
2075 VISIT(c, expr,
2076 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2077 }
2078 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002083 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 n = 0;
2091 if (s->v.Raise.type) {
2092 VISIT(c, expr, s->v.Raise.type);
2093 n++;
2094 if (s->v.Raise.inst) {
2095 VISIT(c, expr, s->v.Raise.inst);
2096 n++;
2097 if (s->v.Raise.tback) {
2098 VISIT(c, expr, s->v.Raise.tback);
2099 n++;
2100 }
2101 }
2102 }
2103 ADDOP_I(c, RAISE_VARARGS, n);
2104 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 VISIT(c, expr, s->v.Exec.body);
2117 if (s->v.Exec.globals) {
2118 VISIT(c, expr, s->v.Exec.globals);
2119 if (s->v.Exec.locals) {
2120 VISIT(c, expr, s->v.Exec.locals);
2121 } else {
2122 ADDOP(c, DUP_TOP);
2123 }
2124 } else {
2125 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2126 ADDOP(c, DUP_TOP);
2127 }
2128 ADDOP(c, EXEC_STMT);
2129 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002132 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002134 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135 ADDOP(c, PRINT_EXPR);
2136 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002137 else if (s->v.Expr.value->kind != Str_kind &&
2138 s->v.Expr.value->kind != Num_kind) {
2139 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140 ADDOP(c, POP_TOP);
2141 }
2142 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002143 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002145 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 if (!c->u->u_nfblocks)
2147 return compiler_error(c, "'break' outside loop");
2148 ADDOP(c, BREAK_LOOP);
2149 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002150 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 case With_kind:
2153 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 }
2155 return 1;
2156}
2157
2158static int
2159unaryop(unaryop_ty op)
2160{
2161 switch (op) {
2162 case Invert:
2163 return UNARY_INVERT;
2164 case Not:
2165 return UNARY_NOT;
2166 case UAdd:
2167 return UNARY_POSITIVE;
2168 case USub:
2169 return UNARY_NEGATIVE;
2170 }
2171 return 0;
2172}
2173
2174static int
2175binop(struct compiler *c, operator_ty op)
2176{
2177 switch (op) {
2178 case Add:
2179 return BINARY_ADD;
2180 case Sub:
2181 return BINARY_SUBTRACT;
2182 case Mult:
2183 return BINARY_MULTIPLY;
2184 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002185 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002186 case Mod:
2187 return BINARY_MODULO;
2188 case Pow:
2189 return BINARY_POWER;
2190 case LShift:
2191 return BINARY_LSHIFT;
2192 case RShift:
2193 return BINARY_RSHIFT;
2194 case BitOr:
2195 return BINARY_OR;
2196 case BitXor:
2197 return BINARY_XOR;
2198 case BitAnd:
2199 return BINARY_AND;
2200 case FloorDiv:
2201 return BINARY_FLOOR_DIVIDE;
2202 }
2203 return 0;
2204}
2205
2206static int
2207cmpop(cmpop_ty op)
2208{
2209 switch (op) {
2210 case Eq:
2211 return PyCmp_EQ;
2212 case NotEq:
2213 return PyCmp_NE;
2214 case Lt:
2215 return PyCmp_LT;
2216 case LtE:
2217 return PyCmp_LE;
2218 case Gt:
2219 return PyCmp_GT;
2220 case GtE:
2221 return PyCmp_GE;
2222 case Is:
2223 return PyCmp_IS;
2224 case IsNot:
2225 return PyCmp_IS_NOT;
2226 case In:
2227 return PyCmp_IN;
2228 case NotIn:
2229 return PyCmp_NOT_IN;
2230 }
2231 return PyCmp_BAD;
2232}
2233
2234static int
2235inplace_binop(struct compiler *c, operator_ty op)
2236{
2237 switch (op) {
2238 case Add:
2239 return INPLACE_ADD;
2240 case Sub:
2241 return INPLACE_SUBTRACT;
2242 case Mult:
2243 return INPLACE_MULTIPLY;
2244 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002245 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002246 case Mod:
2247 return INPLACE_MODULO;
2248 case Pow:
2249 return INPLACE_POWER;
2250 case LShift:
2251 return INPLACE_LSHIFT;
2252 case RShift:
2253 return INPLACE_RSHIFT;
2254 case BitOr:
2255 return INPLACE_OR;
2256 case BitXor:
2257 return INPLACE_XOR;
2258 case BitAnd:
2259 return INPLACE_AND;
2260 case FloorDiv:
2261 return INPLACE_FLOOR_DIVIDE;
2262 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002263 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002264 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265 return 0;
2266}
2267
2268static int
2269compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2270{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002271 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2273
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002274 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002275 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276 /* XXX AugStore isn't used anywhere! */
2277
2278 /* First check for assignment to __debug__. Param? */
2279 if ((ctx == Store || ctx == AugStore || ctx == Del)
2280 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2281 return compiler_error(c, "can not assign to __debug__");
2282 }
2283
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002284 mangled = _Py_Mangle(c->u->u_private, name);
2285 if (!mangled)
2286 return 0;
2287
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288 op = 0;
2289 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002290 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002291 switch (scope) {
2292 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002293 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294 optype = OP_DEREF;
2295 break;
2296 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002297 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 optype = OP_DEREF;
2299 break;
2300 case LOCAL:
2301 if (c->u->u_ste->ste_type == FunctionBlock)
2302 optype = OP_FAST;
2303 break;
2304 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002305 if (c->u->u_ste->ste_type == FunctionBlock &&
2306 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307 optype = OP_GLOBAL;
2308 break;
2309 case GLOBAL_EXPLICIT:
2310 optype = OP_GLOBAL;
2311 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002312 default:
2313 /* scope can be 0 */
2314 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315 }
2316
2317 /* XXX Leave assert here, but handle __doc__ and the like better */
2318 assert(scope || PyString_AS_STRING(name)[0] == '_');
2319
2320 switch (optype) {
2321 case OP_DEREF:
2322 switch (ctx) {
2323 case Load: op = LOAD_DEREF; break;
2324 case Store: op = STORE_DEREF; break;
2325 case AugLoad:
2326 case AugStore:
2327 break;
2328 case Del:
2329 PyErr_Format(PyExc_SyntaxError,
2330 "can not delete variable '%s' referenced "
2331 "in nested scope",
2332 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002333 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002336 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002337 PyErr_SetString(PyExc_SystemError,
2338 "param invalid for deref variable");
2339 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340 }
2341 break;
2342 case OP_FAST:
2343 switch (ctx) {
2344 case Load: op = LOAD_FAST; break;
2345 case Store: op = STORE_FAST; break;
2346 case Del: op = DELETE_FAST; break;
2347 case AugLoad:
2348 case AugStore:
2349 break;
2350 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002351 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002352 PyErr_SetString(PyExc_SystemError,
2353 "param invalid for local variable");
2354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002356 ADDOP_O(c, op, mangled, varnames);
2357 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002358 return 1;
2359 case OP_GLOBAL:
2360 switch (ctx) {
2361 case Load: op = LOAD_GLOBAL; break;
2362 case Store: op = STORE_GLOBAL; break;
2363 case Del: op = DELETE_GLOBAL; break;
2364 case AugLoad:
2365 case AugStore:
2366 break;
2367 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002368 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002369 PyErr_SetString(PyExc_SystemError,
2370 "param invalid for global variable");
2371 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372 }
2373 break;
2374 case OP_NAME:
2375 switch (ctx) {
2376 case Load: op = LOAD_NAME; break;
2377 case Store: op = STORE_NAME; break;
2378 case Del: op = DELETE_NAME; break;
2379 case AugLoad:
2380 case AugStore:
2381 break;
2382 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002383 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002384 PyErr_SetString(PyExc_SystemError,
2385 "param invalid for name variable");
2386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 }
2388 break;
2389 }
2390
2391 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002392 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002393 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002394 if (arg < 0)
2395 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002396 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397}
2398
2399static int
2400compiler_boolop(struct compiler *c, expr_ty e)
2401{
2402 basicblock *end;
2403 int jumpi, i, n;
2404 asdl_seq *s;
2405
2406 assert(e->kind == BoolOp_kind);
2407 if (e->v.BoolOp.op == And)
2408 jumpi = JUMP_IF_FALSE;
2409 else
2410 jumpi = JUMP_IF_TRUE;
2411 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002412 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413 return 0;
2414 s = e->v.BoolOp.values;
2415 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002416 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419 ADDOP_JREL(c, jumpi, end);
2420 ADDOP(c, POP_TOP)
2421 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002422 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423 compiler_use_next_block(c, end);
2424 return 1;
2425}
2426
2427static int
2428compiler_list(struct compiler *c, expr_ty e)
2429{
2430 int n = asdl_seq_LEN(e->v.List.elts);
2431 if (e->v.List.ctx == Store) {
2432 ADDOP_I(c, UNPACK_SEQUENCE, n);
2433 }
2434 VISIT_SEQ(c, expr, e->v.List.elts);
2435 if (e->v.List.ctx == Load) {
2436 ADDOP_I(c, BUILD_LIST, n);
2437 }
2438 return 1;
2439}
2440
2441static int
2442compiler_tuple(struct compiler *c, expr_ty e)
2443{
2444 int n = asdl_seq_LEN(e->v.Tuple.elts);
2445 if (e->v.Tuple.ctx == Store) {
2446 ADDOP_I(c, UNPACK_SEQUENCE, n);
2447 }
2448 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2449 if (e->v.Tuple.ctx == Load) {
2450 ADDOP_I(c, BUILD_TUPLE, n);
2451 }
2452 return 1;
2453}
2454
2455static int
2456compiler_compare(struct compiler *c, expr_ty e)
2457{
2458 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002459 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460
2461 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2462 VISIT(c, expr, e->v.Compare.left);
2463 n = asdl_seq_LEN(e->v.Compare.ops);
2464 assert(n > 0);
2465 if (n > 1) {
2466 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002467 if (cleanup == NULL)
2468 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002469 VISIT(c, expr,
2470 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 }
2472 for (i = 1; i < n; i++) {
2473 ADDOP(c, DUP_TOP);
2474 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002476 cmpop((cmpop_ty)(asdl_seq_GET(
2477 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2479 NEXT_BLOCK(c);
2480 ADDOP(c, POP_TOP);
2481 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002482 VISIT(c, expr,
2483 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002485 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 if (n > 1) {
2489 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002490 if (end == NULL)
2491 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002492 ADDOP_JREL(c, JUMP_FORWARD, end);
2493 compiler_use_next_block(c, cleanup);
2494 ADDOP(c, ROT_TWO);
2495 ADDOP(c, POP_TOP);
2496 compiler_use_next_block(c, end);
2497 }
2498 return 1;
2499}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501
2502static int
2503compiler_call(struct compiler *c, expr_ty e)
2504{
2505 int n, code = 0;
2506
2507 VISIT(c, expr, e->v.Call.func);
2508 n = asdl_seq_LEN(e->v.Call.args);
2509 VISIT_SEQ(c, expr, e->v.Call.args);
2510 if (e->v.Call.keywords) {
2511 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2512 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2513 }
2514 if (e->v.Call.starargs) {
2515 VISIT(c, expr, e->v.Call.starargs);
2516 code |= 1;
2517 }
2518 if (e->v.Call.kwargs) {
2519 VISIT(c, expr, e->v.Call.kwargs);
2520 code |= 2;
2521 }
2522 switch (code) {
2523 case 0:
2524 ADDOP_I(c, CALL_FUNCTION, n);
2525 break;
2526 case 1:
2527 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2528 break;
2529 case 2:
2530 ADDOP_I(c, CALL_FUNCTION_KW, n);
2531 break;
2532 case 3:
2533 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2534 break;
2535 }
2536 return 1;
2537}
2538
2539static int
2540compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002541 asdl_seq *generators, int gen_index,
2542 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543{
2544 /* generate code for the iterator, then each of the ifs,
2545 and then write to the element */
2546
2547 comprehension_ty l;
2548 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002549 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550
2551 start = compiler_new_block(c);
2552 skip = compiler_new_block(c);
2553 if_cleanup = compiler_new_block(c);
2554 anchor = compiler_new_block(c);
2555
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002556 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2557 anchor == NULL)
2558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002560 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002561 VISIT(c, expr, l->iter);
2562 ADDOP(c, GET_ITER);
2563 compiler_use_next_block(c, start);
2564 ADDOP_JREL(c, FOR_ITER, anchor);
2565 NEXT_BLOCK(c);
2566 VISIT(c, expr, l->target);
2567
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002568 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 n = asdl_seq_LEN(l->ifs);
2570 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002571 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002572 VISIT(c, expr, e);
2573 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2574 NEXT_BLOCK(c);
2575 ADDOP(c, POP_TOP);
2576 }
2577
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002578 if (++gen_index < asdl_seq_LEN(generators))
2579 if (!compiler_listcomp_generator(c, tmpname,
2580 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 /* only append after the last for generator */
2584 if (gen_index >= asdl_seq_LEN(generators)) {
2585 if (!compiler_nameop(c, tmpname, Load))
2586 return 0;
2587 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002588 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002589
2590 compiler_use_next_block(c, skip);
2591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 for (i = 0; i < n; i++) {
2593 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002594 if (i == 0)
2595 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 ADDOP(c, POP_TOP);
2597 }
2598 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2599 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 return 0;
2604
2605 return 1;
2606}
2607
2608static int
2609compiler_listcomp(struct compiler *c, expr_ty e)
2610{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002612 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 static identifier append;
2614 asdl_seq *generators = e->v.ListComp.generators;
2615
2616 assert(e->kind == ListComp_kind);
2617 if (!append) {
2618 append = PyString_InternFromString("append");
2619 if (!append)
2620 return 0;
2621 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002622 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 if (!tmp)
2624 return 0;
2625 ADDOP_I(c, BUILD_LIST, 0);
2626 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2629 e->v.ListComp.elt);
2630 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return rc;
2632}
2633
2634static int
2635compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 asdl_seq *generators, int gen_index,
2637 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638{
2639 /* generate code for the iterator, then each of the ifs,
2640 and then write to the element */
2641
2642 comprehension_ty ge;
2643 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645
2646 start = compiler_new_block(c);
2647 skip = compiler_new_block(c);
2648 if_cleanup = compiler_new_block(c);
2649 anchor = compiler_new_block(c);
2650 end = compiler_new_block(c);
2651
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 anchor == NULL || end == NULL)
2654 return 0;
2655
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002656 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 ADDOP_JREL(c, SETUP_LOOP, end);
2658 if (!compiler_push_fblock(c, LOOP, start))
2659 return 0;
2660
2661 if (gen_index == 0) {
2662 /* Receive outermost iter as an implicit argument */
2663 c->u->u_argcount = 1;
2664 ADDOP_I(c, LOAD_FAST, 0);
2665 }
2666 else {
2667 /* Sub-iter - calculate on the fly */
2668 VISIT(c, expr, ge->iter);
2669 ADDOP(c, GET_ITER);
2670 }
2671 compiler_use_next_block(c, start);
2672 ADDOP_JREL(c, FOR_ITER, anchor);
2673 NEXT_BLOCK(c);
2674 VISIT(c, expr, ge->target);
2675
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002676 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 n = asdl_seq_LEN(ge->ifs);
2678 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002679 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 VISIT(c, expr, e);
2681 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2682 NEXT_BLOCK(c);
2683 ADDOP(c, POP_TOP);
2684 }
2685
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002686 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2688 return 0;
2689
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002690 /* only append after the last 'for' generator */
2691 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 VISIT(c, expr, elt);
2693 ADDOP(c, YIELD_VALUE);
2694 ADDOP(c, POP_TOP);
2695
2696 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 for (i = 0; i < n; i++) {
2699 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 compiler_use_next_block(c, if_cleanup);
2702
2703 ADDOP(c, POP_TOP);
2704 }
2705 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2706 compiler_use_next_block(c, anchor);
2707 ADDOP(c, POP_BLOCK);
2708 compiler_pop_fblock(c, LOOP, start);
2709 compiler_use_next_block(c, end);
2710
2711 return 1;
2712}
2713
2714static int
2715compiler_genexp(struct compiler *c, expr_ty e)
2716{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002717 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 PyCodeObject *co;
2719 expr_ty outermost_iter = ((comprehension_ty)
2720 (asdl_seq_GET(e->v.GeneratorExp.generators,
2721 0)))->iter;
2722
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002723 if (!name) {
2724 name = PyString_FromString("<genexpr>");
2725 if (!name)
2726 return 0;
2727 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728
2729 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2730 return 0;
2731 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2732 e->v.GeneratorExp.elt);
2733 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002734 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 if (co == NULL)
2736 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002738 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002739 Py_DECREF(co);
2740
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 VISIT(c, expr, outermost_iter);
2742 ADDOP(c, GET_ITER);
2743 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744
2745 return 1;
2746}
2747
2748static int
2749compiler_visit_keyword(struct compiler *c, keyword_ty k)
2750{
2751 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2752 VISIT(c, expr, k->value);
2753 return 1;
2754}
2755
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 whether they are true or false.
2758
2759 Return values: 1 for true, 0 for false, -1 for non-constant.
2760 */
2761
2762static int
2763expr_constant(expr_ty e)
2764{
2765 switch (e->kind) {
2766 case Num_kind:
2767 return PyObject_IsTrue(e->v.Num.n);
2768 case Str_kind:
2769 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002770 case Name_kind:
2771 /* __debug__ is not assignable, so we can optimize
2772 * it away in if and while statements */
2773 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2774 "__debug__") == 0)
2775 return ! Py_OptimizeFlag;
2776 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777 default:
2778 return -1;
2779 }
2780}
2781
Guido van Rossumc2e20742006-02-27 22:32:47 +00002782/*
2783 Implements the with statement from PEP 343.
2784
2785 The semantics outlined in that PEP are as follows:
2786
2787 with EXPR as VAR:
2788 BLOCK
2789
2790 It is implemented roughly as:
2791
Thomas Wouters477c8d52006-05-27 19:21:47 +00002792 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002793 exit = context.__exit__ # not calling it
2794 value = context.__enter__()
2795 try:
2796 VAR = value # if VAR present in the syntax
2797 BLOCK
2798 finally:
2799 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002800 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002802 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002803 exit(*exc)
2804 */
2805static int
2806compiler_with(struct compiler *c, stmt_ty s)
2807{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002808 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002809 basicblock *block, *finally;
2810 identifier tmpexit, tmpvalue = NULL;
2811
2812 assert(s->kind == With_kind);
2813
Guido van Rossumc2e20742006-02-27 22:32:47 +00002814 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002815 enter_attr = PyString_InternFromString("__enter__");
2816 if (!enter_attr)
2817 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002818 }
2819 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 exit_attr = PyString_InternFromString("__exit__");
2821 if (!exit_attr)
2822 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002823 }
2824
2825 block = compiler_new_block(c);
2826 finally = compiler_new_block(c);
2827 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002828 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002829
2830 /* Create a temporary variable to hold context.__exit__ */
2831 tmpexit = compiler_new_tmpname(c);
2832 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002833 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002834 PyArena_AddPyObject(c->c_arena, tmpexit);
2835
2836 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002837 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002838 We need to do this rather than preserving it on the stack
2839 because SETUP_FINALLY remembers the stack level.
2840 We need to do the assignment *inside* the try/finally
2841 so that context.__exit__() is called when the assignment
2842 fails. But we need to call context.__enter__() *before*
2843 the try/finally so that if it fails we won't call
2844 context.__exit__().
2845 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002846 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002847 if (tmpvalue == NULL)
2848 return 0;
2849 PyArena_AddPyObject(c->c_arena, tmpvalue);
2850 }
2851
Thomas Wouters477c8d52006-05-27 19:21:47 +00002852 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002854
2855 /* Squirrel away context.__exit__ */
2856 ADDOP(c, DUP_TOP);
2857 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2858 if (!compiler_nameop(c, tmpexit, Store))
2859 return 0;
2860
2861 /* Call context.__enter__() */
2862 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2863 ADDOP_I(c, CALL_FUNCTION, 0);
2864
2865 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 /* Store it in tmpvalue */
2867 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002868 return 0;
2869 }
2870 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 /* Discard result from context.__enter__() */
2872 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002873 }
2874
2875 /* Start the try block */
2876 ADDOP_JREL(c, SETUP_FINALLY, finally);
2877
2878 compiler_use_next_block(c, block);
2879 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002880 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002881 }
2882
2883 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002884 /* Bind saved result of context.__enter__() to VAR */
2885 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002886 !compiler_nameop(c, tmpvalue, Del))
2887 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002888 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002889 }
2890
2891 /* BLOCK code */
2892 VISIT_SEQ(c, stmt, s->v.With.body);
2893
2894 /* End of try block; start the finally block */
2895 ADDOP(c, POP_BLOCK);
2896 compiler_pop_fblock(c, FINALLY_TRY, block);
2897
2898 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2899 compiler_use_next_block(c, finally);
2900 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002901 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002902
2903 /* Finally block starts; push tmpexit and issue our magic opcode. */
2904 if (!compiler_nameop(c, tmpexit, Load) ||
2905 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002906 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002908
2909 /* Finally block ends. */
2910 ADDOP(c, END_FINALLY);
2911 compiler_pop_fblock(c, FINALLY_END, finally);
2912 return 1;
2913}
2914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915static int
2916compiler_visit_expr(struct compiler *c, expr_ty e)
2917{
2918 int i, n;
2919
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002920 /* If expr e has a different line number than the last expr/stmt,
2921 set a new line number for the next instruction.
2922 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 if (e->lineno > c->u->u_lineno) {
2924 c->u->u_lineno = e->lineno;
2925 c->u->u_lineno_set = false;
2926 }
2927 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002930 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 VISIT(c, expr, e->v.BinOp.left);
2932 VISIT(c, expr, e->v.BinOp.right);
2933 ADDOP(c, binop(c, e->v.BinOp.op));
2934 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002935 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 VISIT(c, expr, e->v.UnaryOp.operand);
2937 ADDOP(c, unaryop(e->v.UnaryOp.op));
2938 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002939 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002941 case IfExp_kind:
2942 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002943 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 /* XXX get rid of arg? */
2945 ADDOP_I(c, BUILD_MAP, 0);
2946 n = asdl_seq_LEN(e->v.Dict.values);
2947 /* We must arrange things just right for STORE_SUBSCR.
2948 It wants the stack to look like (value) (dict) (key) */
2949 for (i = 0; i < n; i++) {
2950 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002951 VISIT(c, expr,
2952 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002954 VISIT(c, expr,
2955 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 ADDOP(c, STORE_SUBSCR);
2957 }
2958 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002961 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 return compiler_genexp(c, e);
2963 case Yield_kind:
2964 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002965 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 /*
2967 for (i = 0; i < c->u->u_nfblocks; i++) {
2968 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2969 return compiler_error(
2970 c, "'yield' not allowed in a 'try' "
2971 "block with a 'finally' clause");
2972 }
2973 */
2974 if (e->v.Yield.value) {
2975 VISIT(c, expr, e->v.Yield.value);
2976 }
2977 else {
2978 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2979 }
2980 ADDOP(c, YIELD_VALUE);
2981 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002982 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002984 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002986 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987 VISIT(c, expr, e->v.Repr.value);
2988 ADDOP(c, UNARY_CONVERT);
2989 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002990 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2992 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002993 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2995 break;
2996 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002997 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998 if (e->v.Attribute.ctx != AugStore)
2999 VISIT(c, expr, e->v.Attribute.value);
3000 switch (e->v.Attribute.ctx) {
3001 case AugLoad:
3002 ADDOP(c, DUP_TOP);
3003 /* Fall through to load */
3004 case Load:
3005 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3006 break;
3007 case AugStore:
3008 ADDOP(c, ROT_TWO);
3009 /* Fall through to save */
3010 case Store:
3011 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3012 break;
3013 case Del:
3014 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3015 break;
3016 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003017 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003018 PyErr_SetString(PyExc_SystemError,
3019 "param invalid in attribute expression");
3020 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 }
3022 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003023 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 switch (e->v.Subscript.ctx) {
3025 case AugLoad:
3026 VISIT(c, expr, e->v.Subscript.value);
3027 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3028 break;
3029 case Load:
3030 VISIT(c, expr, e->v.Subscript.value);
3031 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3032 break;
3033 case AugStore:
3034 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3035 break;
3036 case Store:
3037 VISIT(c, expr, e->v.Subscript.value);
3038 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3039 break;
3040 case Del:
3041 VISIT(c, expr, e->v.Subscript.value);
3042 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3043 break;
3044 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003045 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003046 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003047 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003048 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049 }
3050 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003051 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3053 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003054 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003056 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 return compiler_tuple(c, e);
3058 }
3059 return 1;
3060}
3061
3062static int
3063compiler_augassign(struct compiler *c, stmt_ty s)
3064{
3065 expr_ty e = s->v.AugAssign.target;
3066 expr_ty auge;
3067
3068 assert(s->kind == AugAssign_kind);
3069
3070 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003071 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003073 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 if (auge == NULL)
3075 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 VISIT(c, expr, auge);
3077 VISIT(c, expr, s->v.AugAssign.value);
3078 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3079 auge->v.Attribute.ctx = AugStore;
3080 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003081 break;
3082 case Subscript_kind:
3083 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003084 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 if (auge == NULL)
3086 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 VISIT(c, expr, auge);
3088 VISIT(c, expr, s->v.AugAssign.value);
3089 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003090 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003092 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003094 if (!compiler_nameop(c, e->v.Name.id, Load))
3095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096 VISIT(c, expr, s->v.AugAssign.value);
3097 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3098 return compiler_nameop(c, e->v.Name.id, Store);
3099 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003100 PyErr_Format(PyExc_SystemError,
3101 "invalid node type (%d) for augmented assignment",
3102 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104 }
3105 return 1;
3106}
3107
3108static int
3109compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3110{
3111 struct fblockinfo *f;
3112 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3113 return 0;
3114 f = &c->u->u_fblock[c->u->u_nfblocks++];
3115 f->fb_type = t;
3116 f->fb_block = b;
3117 return 1;
3118}
3119
3120static void
3121compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3122{
3123 struct compiler_unit *u = c->u;
3124 assert(u->u_nfblocks > 0);
3125 u->u_nfblocks--;
3126 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3127 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3128}
3129
3130/* Raises a SyntaxError and returns 0.
3131 If something goes wrong, a different exception may be raised.
3132*/
3133
3134static int
3135compiler_error(struct compiler *c, const char *errstr)
3136{
3137 PyObject *loc;
3138 PyObject *u = NULL, *v = NULL;
3139
3140 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3141 if (!loc) {
3142 Py_INCREF(Py_None);
3143 loc = Py_None;
3144 }
3145 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3146 Py_None, loc);
3147 if (!u)
3148 goto exit;
3149 v = Py_BuildValue("(zO)", errstr, u);
3150 if (!v)
3151 goto exit;
3152 PyErr_SetObject(PyExc_SyntaxError, v);
3153 exit:
3154 Py_DECREF(loc);
3155 Py_XDECREF(u);
3156 Py_XDECREF(v);
3157 return 0;
3158}
3159
3160static int
3161compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003162 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003166 /* XXX this code is duplicated */
3167 switch (ctx) {
3168 case AugLoad: /* fall through to Load */
3169 case Load: op = BINARY_SUBSCR; break;
3170 case AugStore:/* fall through to Store */
3171 case Store: op = STORE_SUBSCR; break;
3172 case Del: op = DELETE_SUBSCR; break;
3173 case Param:
3174 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003175 "invalid %s kind %d in subscript\n",
3176 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 return 0;
3178 }
3179 if (ctx == AugLoad) {
3180 ADDOP_I(c, DUP_TOPX, 2);
3181 }
3182 else if (ctx == AugStore) {
3183 ADDOP(c, ROT_THREE);
3184 }
3185 ADDOP(c, op);
3186 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187}
3188
3189static int
3190compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3191{
3192 int n = 2;
3193 assert(s->kind == Slice_kind);
3194
3195 /* only handles the cases where BUILD_SLICE is emitted */
3196 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 }
3199 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003200 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003204 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003205 }
3206 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 }
3209
3210 if (s->v.Slice.step) {
3211 n++;
3212 VISIT(c, expr, s->v.Slice.step);
3213 }
3214 ADDOP_I(c, BUILD_SLICE, n);
3215 return 1;
3216}
3217
3218static int
3219compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3220{
3221 int op = 0, slice_offset = 0, stack_count = 0;
3222
3223 assert(s->v.Slice.step == NULL);
3224 if (s->v.Slice.lower) {
3225 slice_offset++;
3226 stack_count++;
3227 if (ctx != AugStore)
3228 VISIT(c, expr, s->v.Slice.lower);
3229 }
3230 if (s->v.Slice.upper) {
3231 slice_offset += 2;
3232 stack_count++;
3233 if (ctx != AugStore)
3234 VISIT(c, expr, s->v.Slice.upper);
3235 }
3236
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003237 if (ctx == AugLoad) {
3238 switch (stack_count) {
3239 case 0: ADDOP(c, DUP_TOP); break;
3240 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3241 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3242 }
3243 }
3244 else if (ctx == AugStore) {
3245 switch (stack_count) {
3246 case 0: ADDOP(c, ROT_TWO); break;
3247 case 1: ADDOP(c, ROT_THREE); break;
3248 case 2: ADDOP(c, ROT_FOUR); break;
3249 }
3250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251
3252 switch (ctx) {
3253 case AugLoad: /* fall through to Load */
3254 case Load: op = SLICE; break;
3255 case AugStore:/* fall through to Store */
3256 case Store: op = STORE_SLICE; break;
3257 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003258 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003259 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003260 PyErr_SetString(PyExc_SystemError,
3261 "param invalid in simple slice");
3262 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 }
3264
3265 ADDOP(c, op + slice_offset);
3266 return 1;
3267}
3268
3269static int
3270compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3271 expr_context_ty ctx)
3272{
3273 switch (s->kind) {
3274 case Ellipsis_kind:
3275 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3276 break;
3277 case Slice_kind:
3278 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 case Index_kind:
3280 VISIT(c, expr, s->v.Index.value);
3281 break;
3282 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003283 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003284 PyErr_SetString(PyExc_SystemError,
3285 "extended slice invalid in nested slice");
3286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 }
3288 return 1;
3289}
3290
3291
3292static int
3293compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3294{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003295 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003297 case Index_kind:
3298 kindname = "index";
3299 if (ctx != AugStore) {
3300 VISIT(c, expr, s->v.Index.value);
3301 }
3302 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003304 kindname = "ellipsis";
3305 if (ctx != AugStore) {
3306 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3307 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 break;
3309 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003310 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311 if (!s->v.Slice.step)
3312 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003313 if (ctx != AugStore) {
3314 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315 return 0;
3316 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003317 break;
3318 case ExtSlice_kind:
3319 kindname = "extended slice";
3320 if (ctx != AugStore) {
3321 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3322 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003323 slice_ty sub = (slice_ty)asdl_seq_GET(
3324 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003325 if (!compiler_visit_nested_slice(c, sub, ctx))
3326 return 0;
3327 }
3328 ADDOP_I(c, BUILD_TUPLE, n);
3329 }
3330 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003331 default:
3332 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003333 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003334 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003336 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337}
3338
3339/* do depth-first search of basic block graph, starting with block.
3340 post records the block indices in post-order.
3341
3342 XXX must handle implicit jumps from one block to next
3343*/
3344
3345static void
3346dfs(struct compiler *c, basicblock *b, struct assembler *a)
3347{
3348 int i;
3349 struct instr *instr = NULL;
3350
3351 if (b->b_seen)
3352 return;
3353 b->b_seen = 1;
3354 if (b->b_next != NULL)
3355 dfs(c, b->b_next, a);
3356 for (i = 0; i < b->b_iused; i++) {
3357 instr = &b->b_instr[i];
3358 if (instr->i_jrel || instr->i_jabs)
3359 dfs(c, instr->i_target, a);
3360 }
3361 a->a_postorder[a->a_nblocks++] = b;
3362}
3363
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003364static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3366{
3367 int i;
3368 struct instr *instr;
3369 if (b->b_seen || b->b_startdepth >= depth)
3370 return maxdepth;
3371 b->b_seen = 1;
3372 b->b_startdepth = depth;
3373 for (i = 0; i < b->b_iused; i++) {
3374 instr = &b->b_instr[i];
3375 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3376 if (depth > maxdepth)
3377 maxdepth = depth;
3378 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3379 if (instr->i_jrel || instr->i_jabs) {
3380 maxdepth = stackdepth_walk(c, instr->i_target,
3381 depth, maxdepth);
3382 if (instr->i_opcode == JUMP_ABSOLUTE ||
3383 instr->i_opcode == JUMP_FORWARD) {
3384 goto out; /* remaining code is dead */
3385 }
3386 }
3387 }
3388 if (b->b_next)
3389 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3390out:
3391 b->b_seen = 0;
3392 return maxdepth;
3393}
3394
3395/* Find the flow path that needs the largest stack. We assume that
3396 * cycles in the flow graph have no net effect on the stack depth.
3397 */
3398static int
3399stackdepth(struct compiler *c)
3400{
3401 basicblock *b, *entryblock;
3402 entryblock = NULL;
3403 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3404 b->b_seen = 0;
3405 b->b_startdepth = INT_MIN;
3406 entryblock = b;
3407 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003408 if (!entryblock)
3409 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003410 return stackdepth_walk(c, entryblock, 0, 0);
3411}
3412
3413static int
3414assemble_init(struct assembler *a, int nblocks, int firstlineno)
3415{
3416 memset(a, 0, sizeof(struct assembler));
3417 a->a_lineno = firstlineno;
3418 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3419 if (!a->a_bytecode)
3420 return 0;
3421 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3422 if (!a->a_lnotab)
3423 return 0;
3424 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003425 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003426 if (!a->a_postorder) {
3427 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003429 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003430 return 1;
3431}
3432
3433static void
3434assemble_free(struct assembler *a)
3435{
3436 Py_XDECREF(a->a_bytecode);
3437 Py_XDECREF(a->a_lnotab);
3438 if (a->a_postorder)
3439 PyObject_Free(a->a_postorder);
3440}
3441
3442/* Return the size of a basic block in bytes. */
3443
3444static int
3445instrsize(struct instr *instr)
3446{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003447 if (!instr->i_hasarg)
3448 return 1;
3449 if (instr->i_oparg > 0xffff)
3450 return 6;
3451 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452}
3453
3454static int
3455blocksize(basicblock *b)
3456{
3457 int i;
3458 int size = 0;
3459
3460 for (i = 0; i < b->b_iused; i++)
3461 size += instrsize(&b->b_instr[i]);
3462 return size;
3463}
3464
3465/* All about a_lnotab.
3466
3467c_lnotab is an array of unsigned bytes disguised as a Python string.
3468It is used to map bytecode offsets to source code line #s (when needed
3469for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003470
Tim Peters2a7f3842001-06-09 09:26:21 +00003471The array is conceptually a list of
3472 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003474
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003475 byte code offset source code line number
3476 0 1
3477 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003478 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003479 350 307
3480 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003481
3482The first trick is that these numbers aren't stored, only the increments
3483from one row to the next (this doesn't really work, but it's a start):
3484
3485 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3486
3487The second trick is that an unsigned byte can't hold negative values, or
3488values larger than 255, so (a) there's a deep assumption that byte code
3489offsets and their corresponding line #s both increase monotonically, and (b)
3490if at least one column jumps by more than 255 from one row to the next, more
3491than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003492from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003493part. A user of c_lnotab desiring to find the source line number
3494corresponding to a bytecode address A should do something like this
3495
3496 lineno = addr = 0
3497 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 addr += addr_incr
3499 if addr > A:
3500 return lineno
3501 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003502
3503In order for this to work, when the addr field increments by more than 255,
3504the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003505increment is < 256. So, in the example above, assemble_lnotab (it used
3506to be called com_set_lineno) should not (as was actually done until 2.2)
3507expand 300, 300 to 255, 255, 45, 45,
3508 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003509*/
3510
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003511static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003513{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 int d_bytecode, d_lineno;
3515 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003516 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517
3518 d_bytecode = a->a_offset - a->a_lineno_off;
3519 d_lineno = i->i_lineno - a->a_lineno;
3520
3521 assert(d_bytecode >= 0);
3522 assert(d_lineno >= 0);
3523
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003524 /* XXX(nnorwitz): is there a better way to handle this?
3525 for loops are special, we want to be able to trace them
3526 each time around, so we need to set an extra line number. */
3527 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003528 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003531 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 nbytes = a->a_lnotab_off + 2 * ncodes;
3533 len = PyString_GET_SIZE(a->a_lnotab);
3534 if (nbytes >= len) {
3535 if (len * 2 < nbytes)
3536 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003537 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 len *= 2;
3539 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3540 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003541 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003542 lnotab = (unsigned char *)
3543 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003544 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 *lnotab++ = 255;
3546 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003547 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 d_bytecode -= ncodes * 255;
3549 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003550 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 assert(d_bytecode <= 255);
3552 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003553 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 nbytes = a->a_lnotab_off + 2 * ncodes;
3555 len = PyString_GET_SIZE(a->a_lnotab);
3556 if (nbytes >= len) {
3557 if (len * 2 < nbytes)
3558 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003559 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 len *= 2;
3561 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3562 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003563 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003564 lnotab = (unsigned char *)
3565 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003567 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003569 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003571 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003572 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 d_lineno -= ncodes * 255;
3574 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003575 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003576
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 len = PyString_GET_SIZE(a->a_lnotab);
3578 if (a->a_lnotab_off + 2 >= len) {
3579 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003580 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003581 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003582 lnotab = (unsigned char *)
3583 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003584
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585 a->a_lnotab_off += 2;
3586 if (d_bytecode) {
3587 *lnotab++ = d_bytecode;
3588 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003589 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003590 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 *lnotab++ = 0;
3592 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594 a->a_lineno = i->i_lineno;
3595 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003596 return 1;
3597}
3598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599/* assemble_emit()
3600 Extend the bytecode with a new instruction.
3601 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003602*/
3603
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003604static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003606{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003607 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003608 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003609 char *code;
3610
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003611 size = instrsize(i);
3612 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003614 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003615 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003617 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 if (a->a_offset + size >= len) {
3619 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003620 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003621 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3623 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003624 if (size == 6) {
3625 assert(i->i_hasarg);
3626 *code++ = (char)EXTENDED_ARG;
3627 *code++ = ext & 0xff;
3628 *code++ = ext >> 8;
3629 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003630 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003632 if (i->i_hasarg) {
3633 assert(size == 3 || size == 6);
3634 *code++ = arg & 0xff;
3635 *code++ = arg >> 8;
3636 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003638}
3639
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003640static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003642{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003644 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003645 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003646
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 /* Compute the size of each block and fixup jump args.
3648 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003649start:
3650 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003652 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 bsize = blocksize(b);
3654 b->b_offset = totsize;
3655 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003656 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003657 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3659 bsize = b->b_offset;
3660 for (i = 0; i < b->b_iused; i++) {
3661 struct instr *instr = &b->b_instr[i];
3662 /* Relative jumps are computed relative to
3663 the instruction pointer after fetching
3664 the jump instruction.
3665 */
3666 bsize += instrsize(instr);
3667 if (instr->i_jabs)
3668 instr->i_oparg = instr->i_target->b_offset;
3669 else if (instr->i_jrel) {
3670 int delta = instr->i_target->b_offset - bsize;
3671 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003672 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003673 else
3674 continue;
3675 if (instr->i_oparg > 0xffff)
3676 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003677 }
3678 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003679
3680 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003682 with a better solution.
3683
3684 In the meantime, should the goto be dropped in favor
3685 of a loop?
3686
3687 The issue is that in the first loop blocksize() is called
3688 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003689 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003690 i_oparg is calculated in the second loop above.
3691
3692 So we loop until we stop seeing new EXTENDED_ARGs.
3693 The only EXTENDED_ARGs that could be popping up are
3694 ones in jump instructions. So this should converge
3695 fairly quickly.
3696 */
3697 if (last_extended_arg_count != extended_arg_count) {
3698 last_extended_arg_count = extended_arg_count;
3699 goto start;
3700 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003701}
3702
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003703static PyObject *
3704dict_keys_inorder(PyObject *dict, int offset)
3705{
3706 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003707 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003708
3709 tuple = PyTuple_New(size);
3710 if (tuple == NULL)
3711 return NULL;
3712 while (PyDict_Next(dict, &pos, &k, &v)) {
3713 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003714 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003715 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003716 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003717 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003718 PyTuple_SET_ITEM(tuple, i - offset, k);
3719 }
3720 return tuple;
3721}
3722
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003723static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003725{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726 PySTEntryObject *ste = c->u->u_ste;
3727 int flags = 0, n;
3728 if (ste->ste_type != ModuleBlock)
3729 flags |= CO_NEWLOCALS;
3730 if (ste->ste_type == FunctionBlock) {
3731 if (!ste->ste_unoptimized)
3732 flags |= CO_OPTIMIZED;
3733 if (ste->ste_nested)
3734 flags |= CO_NESTED;
3735 if (ste->ste_generator)
3736 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003737 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 if (ste->ste_varargs)
3739 flags |= CO_VARARGS;
3740 if (ste->ste_varkeywords)
3741 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003742 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003744
3745 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003747
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 n = PyDict_Size(c->u->u_freevars);
3749 if (n < 0)
3750 return -1;
3751 if (n == 0) {
3752 n = PyDict_Size(c->u->u_cellvars);
3753 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003754 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003755 if (n == 0) {
3756 flags |= CO_NOFREE;
3757 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003758 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003759
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003760 return flags;
3761}
3762
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763static PyCodeObject *
3764makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003765{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 PyObject *tmp;
3767 PyCodeObject *co = NULL;
3768 PyObject *consts = NULL;
3769 PyObject *names = NULL;
3770 PyObject *varnames = NULL;
3771 PyObject *filename = NULL;
3772 PyObject *name = NULL;
3773 PyObject *freevars = NULL;
3774 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003775 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003777
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 tmp = dict_keys_inorder(c->u->u_consts, 0);
3779 if (!tmp)
3780 goto error;
3781 consts = PySequence_List(tmp); /* optimize_code requires a list */
3782 Py_DECREF(tmp);
3783
3784 names = dict_keys_inorder(c->u->u_names, 0);
3785 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3786 if (!consts || !names || !varnames)
3787 goto error;
3788
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003789 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3790 if (!cellvars)
3791 goto error;
3792 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3793 if (!freevars)
3794 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 filename = PyString_FromString(c->c_filename);
3796 if (!filename)
3797 goto error;
3798
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003799 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 flags = compute_code_flags(c);
3801 if (flags < 0)
3802 goto error;
3803
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003804 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805 if (!bytecode)
3806 goto error;
3807
3808 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3809 if (!tmp)
3810 goto error;
3811 Py_DECREF(consts);
3812 consts = tmp;
3813
3814 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3815 bytecode, consts, names, varnames,
3816 freevars, cellvars,
3817 filename, c->u->u_name,
3818 c->u->u_firstlineno,
3819 a->a_lnotab);
3820 error:
3821 Py_XDECREF(consts);
3822 Py_XDECREF(names);
3823 Py_XDECREF(varnames);
3824 Py_XDECREF(filename);
3825 Py_XDECREF(name);
3826 Py_XDECREF(freevars);
3827 Py_XDECREF(cellvars);
3828 Py_XDECREF(bytecode);
3829 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003830}
3831
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003832
3833/* For debugging purposes only */
3834#if 0
3835static void
3836dump_instr(const struct instr *i)
3837{
3838 const char *jrel = i->i_jrel ? "jrel " : "";
3839 const char *jabs = i->i_jabs ? "jabs " : "";
3840 char arg[128];
3841
3842 *arg = '\0';
3843 if (i->i_hasarg)
3844 sprintf(arg, "arg: %d ", i->i_oparg);
3845
3846 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3847 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3848}
3849
3850static void
3851dump_basicblock(const basicblock *b)
3852{
3853 const char *seen = b->b_seen ? "seen " : "";
3854 const char *b_return = b->b_return ? "return " : "";
3855 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3856 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3857 if (b->b_instr) {
3858 int i;
3859 for (i = 0; i < b->b_iused; i++) {
3860 fprintf(stderr, " [%02d] ", i);
3861 dump_instr(b->b_instr + i);
3862 }
3863 }
3864}
3865#endif
3866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867static PyCodeObject *
3868assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003869{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 basicblock *b, *entryblock;
3871 struct assembler a;
3872 int i, j, nblocks;
3873 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003874
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875 /* Make sure every block that falls off the end returns None.
3876 XXX NEXT_BLOCK() isn't quite right, because if the last
3877 block ends with a jump or return b_next shouldn't set.
3878 */
3879 if (!c->u->u_curblock->b_return) {
3880 NEXT_BLOCK(c);
3881 if (addNone)
3882 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3883 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003884 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 nblocks = 0;
3887 entryblock = NULL;
3888 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3889 nblocks++;
3890 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003891 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003892
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003893 /* Set firstlineno if it wasn't explicitly set. */
3894 if (!c->u->u_firstlineno) {
3895 if (entryblock && entryblock->b_instr)
3896 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3897 else
3898 c->u->u_firstlineno = 1;
3899 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003900 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3901 goto error;
3902 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003905 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003906
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907 /* Emit code in reverse postorder from dfs. */
3908 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003909 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 for (j = 0; j < b->b_iused; j++)
3911 if (!assemble_emit(&a, &b->b_instr[j]))
3912 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003913 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3916 goto error;
3917 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3918 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920 co = makecode(c, &a);
3921 error:
3922 assemble_free(&a);
3923 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003924}