blob: ac82b84b893a087cde616590a22d1ce515bb7e73 [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:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 case UNARY_INVERT:
725 return 0;
726
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000727 case LIST_APPEND:
728 return -2;
729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000730 case BINARY_POWER:
731 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000732 case BINARY_MODULO:
733 case BINARY_ADD:
734 case BINARY_SUBTRACT:
735 case BINARY_SUBSCR:
736 case BINARY_FLOOR_DIVIDE:
737 case BINARY_TRUE_DIVIDE:
738 return -1;
739 case INPLACE_FLOOR_DIVIDE:
740 case INPLACE_TRUE_DIVIDE:
741 return -1;
742
743 case SLICE+0:
744 return 1;
745 case SLICE+1:
746 return 0;
747 case SLICE+2:
748 return 0;
749 case SLICE+3:
750 return -1;
751
752 case STORE_SLICE+0:
753 return -2;
754 case STORE_SLICE+1:
755 return -3;
756 case STORE_SLICE+2:
757 return -3;
758 case STORE_SLICE+3:
759 return -4;
760
761 case DELETE_SLICE+0:
762 return -1;
763 case DELETE_SLICE+1:
764 return -2;
765 case DELETE_SLICE+2:
766 return -2;
767 case DELETE_SLICE+3:
768 return -3;
769
770 case INPLACE_ADD:
771 case INPLACE_SUBTRACT:
772 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773 case INPLACE_MODULO:
774 return -1;
775 case STORE_SUBSCR:
776 return -3;
777 case DELETE_SUBSCR:
778 return -2;
779
780 case BINARY_LSHIFT:
781 case BINARY_RSHIFT:
782 case BINARY_AND:
783 case BINARY_XOR:
784 case BINARY_OR:
785 return -1;
786 case INPLACE_POWER:
787 return -1;
788 case GET_ITER:
789 return 0;
790
791 case PRINT_EXPR:
792 return -1;
793 case PRINT_ITEM:
794 return -1;
795 case PRINT_NEWLINE:
796 return 0;
797 case PRINT_ITEM_TO:
798 return -2;
799 case PRINT_NEWLINE_TO:
800 return -1;
801 case INPLACE_LSHIFT:
802 case INPLACE_RSHIFT:
803 case INPLACE_AND:
804 case INPLACE_XOR:
805 case INPLACE_OR:
806 return -1;
807 case BREAK_LOOP:
808 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000809 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000810 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811 case LOAD_LOCALS:
812 return 1;
813 case RETURN_VALUE:
814 return -1;
815 case IMPORT_STAR:
816 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000817 case YIELD_VALUE:
818 return 0;
819
820 case POP_BLOCK:
821 return 0;
822 case END_FINALLY:
823 return -1; /* or -2 or -3 if exception occurred */
824 case BUILD_CLASS:
825 return -2;
826
827 case STORE_NAME:
828 return -1;
829 case DELETE_NAME:
830 return 0;
831 case UNPACK_SEQUENCE:
832 return oparg-1;
833 case FOR_ITER:
834 return 1;
835
836 case STORE_ATTR:
837 return -2;
838 case DELETE_ATTR:
839 return -1;
840 case STORE_GLOBAL:
841 return -1;
842 case DELETE_GLOBAL:
843 return 0;
844 case DUP_TOPX:
845 return oparg;
846 case LOAD_CONST:
847 return 1;
848 case LOAD_NAME:
849 return 1;
850 case BUILD_TUPLE:
851 case BUILD_LIST:
Guido van Rossum86e58e22006-08-28 15:27:34 +0000852 case BUILD_SET:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000853 return 1-oparg;
854 case BUILD_MAP:
855 return 1;
856 case LOAD_ATTR:
857 return 0;
858 case COMPARE_OP:
859 return -1;
860 case IMPORT_NAME:
861 return 0;
862 case IMPORT_FROM:
863 return 1;
864
865 case JUMP_FORWARD:
866 case JUMP_IF_FALSE:
867 case JUMP_IF_TRUE:
868 case JUMP_ABSOLUTE:
869 return 0;
870
871 case LOAD_GLOBAL:
872 return 1;
873
874 case CONTINUE_LOOP:
875 return 0;
876 case SETUP_LOOP:
877 return 0;
878 case SETUP_EXCEPT:
879 case SETUP_FINALLY:
880 return 3; /* actually pushed by an exception */
881
882 case LOAD_FAST:
883 return 1;
884 case STORE_FAST:
885 return -1;
886 case DELETE_FAST:
887 return 0;
888
889 case RAISE_VARARGS:
890 return -oparg;
891#define NARGS(o) (((o) % 256) + 2*((o) / 256))
892 case CALL_FUNCTION:
893 return -NARGS(oparg);
894 case CALL_FUNCTION_VAR:
895 case CALL_FUNCTION_KW:
896 return -NARGS(oparg)-1;
897 case CALL_FUNCTION_VAR_KW:
898 return -NARGS(oparg)-2;
899#undef NARGS
900 case MAKE_FUNCTION:
901 return -oparg;
902 case BUILD_SLICE:
903 if (oparg == 3)
904 return -2;
905 else
906 return -1;
907
908 case MAKE_CLOSURE:
909 return -oparg;
910 case LOAD_CLOSURE:
911 return 1;
912 case LOAD_DEREF:
913 return 1;
914 case STORE_DEREF:
915 return -1;
916 default:
917 fprintf(stderr, "opcode = %d\n", opcode);
918 Py_FatalError("opcode_stack_effect()");
919
920 }
921 return 0; /* not reachable */
922}
923
924/* Add an opcode with no argument.
925 Returns 0 on failure, 1 on success.
926*/
927
928static int
929compiler_addop(struct compiler *c, int opcode)
930{
931 basicblock *b;
932 struct instr *i;
933 int off;
934 off = compiler_next_instr(c, c->u->u_curblock);
935 if (off < 0)
936 return 0;
937 b = c->u->u_curblock;
938 i = &b->b_instr[off];
939 i->i_opcode = opcode;
940 i->i_hasarg = 0;
941 if (opcode == RETURN_VALUE)
942 b->b_return = 1;
943 compiler_set_lineno(c, off);
944 return 1;
945}
946
947static int
948compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
949{
950 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000951 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000953 /* necessary to make sure types aren't coerced (e.g., int and long) */
954 t = PyTuple_Pack(2, o, o->ob_type);
955 if (t == NULL)
956 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000957
958 v = PyDict_GetItem(dict, t);
959 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000960 if (PyErr_Occurred())
961 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000962 arg = PyDict_Size(dict);
963 v = PyInt_FromLong(arg);
964 if (!v) {
965 Py_DECREF(t);
966 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (PyDict_SetItem(dict, t, v) < 0) {
969 Py_DECREF(t);
970 Py_DECREF(v);
971 return -1;
972 }
973 Py_DECREF(v);
974 }
975 else
976 arg = PyInt_AsLong(v);
977 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979}
980
981static int
982compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
983 PyObject *o)
984{
985 int arg = compiler_add_o(c, dict, o);
986 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 return compiler_addop_i(c, opcode, arg);
989}
990
991static int
992compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000993 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994{
995 int arg;
996 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
997 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 arg = compiler_add_o(c, dict, mangled);
1000 Py_DECREF(mangled);
1001 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 return compiler_addop_i(c, opcode, arg);
1004}
1005
1006/* Add an opcode with an integer argument.
1007 Returns 0 on failure, 1 on success.
1008*/
1009
1010static int
1011compiler_addop_i(struct compiler *c, int opcode, int oparg)
1012{
1013 struct instr *i;
1014 int off;
1015 off = compiler_next_instr(c, c->u->u_curblock);
1016 if (off < 0)
1017 return 0;
1018 i = &c->u->u_curblock->b_instr[off];
1019 i->i_opcode = opcode;
1020 i->i_oparg = oparg;
1021 i->i_hasarg = 1;
1022 compiler_set_lineno(c, off);
1023 return 1;
1024}
1025
1026static int
1027compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1028{
1029 struct instr *i;
1030 int off;
1031
1032 assert(b != NULL);
1033 off = compiler_next_instr(c, c->u->u_curblock);
1034 if (off < 0)
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 i = &c->u->u_curblock->b_instr[off];
1037 i->i_opcode = opcode;
1038 i->i_target = b;
1039 i->i_hasarg = 1;
1040 if (absolute)
1041 i->i_jabs = 1;
1042 else
1043 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 return 1;
1046}
1047
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001048/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1049 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050 it as the current block. NEXT_BLOCK() also creates an implicit jump
1051 from the current block to the new block.
1052*/
1053
1054/* XXX The returns inside these macros make it impossible to decref
1055 objects created in the local function.
1056*/
1057
1058
1059#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060 if (compiler_use_new_block((C)) == NULL) \
1061 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062}
1063
1064#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001065 if (compiler_next_block((C)) == NULL) \
1066 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067}
1068
1069#define ADDOP(C, OP) { \
1070 if (!compiler_addop((C), (OP))) \
1071 return 0; \
1072}
1073
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001074#define ADDOP_IN_SCOPE(C, OP) { \
1075 if (!compiler_addop((C), (OP))) { \
1076 compiler_exit_scope(c); \
1077 return 0; \
1078 } \
1079}
1080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081#define ADDOP_O(C, OP, O, TYPE) { \
1082 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1083 return 0; \
1084}
1085
1086#define ADDOP_NAME(C, OP, O, TYPE) { \
1087 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1088 return 0; \
1089}
1090
1091#define ADDOP_I(C, OP, O) { \
1092 if (!compiler_addop_i((C), (OP), (O))) \
1093 return 0; \
1094}
1095
1096#define ADDOP_JABS(C, OP, O) { \
1097 if (!compiler_addop_j((C), (OP), (O), 1)) \
1098 return 0; \
1099}
1100
1101#define ADDOP_JREL(C, OP, O) { \
1102 if (!compiler_addop_j((C), (OP), (O), 0)) \
1103 return 0; \
1104}
1105
1106/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1107 the ASDL name to synthesize the name of the C type and the visit function.
1108*/
1109
1110#define VISIT(C, TYPE, V) {\
1111 if (!compiler_visit_ ## TYPE((C), (V))) \
1112 return 0; \
1113}
1114
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001115#define VISIT_IN_SCOPE(C, TYPE, V) {\
1116 if (!compiler_visit_ ## TYPE((C), (V))) { \
1117 compiler_exit_scope(c); \
1118 return 0; \
1119 } \
1120}
1121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122#define VISIT_SLICE(C, V, CTX) {\
1123 if (!compiler_visit_slice((C), (V), (CTX))) \
1124 return 0; \
1125}
1126
1127#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001128 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132 if (!compiler_visit_ ## TYPE((C), elt)) \
1133 return 0; \
1134 } \
1135}
1136
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001141 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001142 if (!compiler_visit_ ## TYPE((C), elt)) { \
1143 compiler_exit_scope(c); \
1144 return 0; \
1145 } \
1146 } \
1147}
1148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149static int
1150compiler_isdocstring(stmt_ty s)
1151{
1152 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return s->v.Expr.value->kind == Str_kind;
1155}
1156
1157/* Compile a sequence of statements, checking for a docstring. */
1158
1159static int
1160compiler_body(struct compiler *c, asdl_seq *stmts)
1161{
1162 int i = 0;
1163 stmt_ty st;
1164
1165 if (!asdl_seq_LEN(stmts))
1166 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 if (compiler_isdocstring(st)) {
1169 i = 1;
1170 VISIT(c, expr, st->v.Expr.value);
1171 if (!compiler_nameop(c, __doc__, Store))
1172 return 0;
1173 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001174 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 return 1;
1177}
1178
1179static PyCodeObject *
1180compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001181{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 static PyObject *module;
1185 if (!module) {
1186 module = PyString_FromString("<module>");
1187 if (!module)
1188 return NULL;
1189 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1191 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001192 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 switch (mod->kind) {
1194 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001195 if (!compiler_body(c, mod->v.Module.body)) {
1196 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 break;
1200 case Interactive_kind:
1201 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001202 VISIT_SEQ_IN_SCOPE(c, stmt,
1203 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001206 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001207 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 break;
1209 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001210 PyErr_SetString(PyExc_SystemError,
1211 "suite should not be possible");
1212 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001213 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001214 PyErr_Format(PyExc_SystemError,
1215 "module kind %d should not be possible",
1216 mod->kind);
1217 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 co = assemble(c, addNone);
1220 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001221 return co;
1222}
1223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224/* The test for LOCAL must come before the test for FREE in order to
1225 handle classes where name is both local and free. The local var is
1226 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001227*/
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229static int
1230get_ref_type(struct compiler *c, PyObject *name)
1231{
1232 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001233 if (scope == 0) {
1234 char buf[350];
1235 PyOS_snprintf(buf, sizeof(buf),
1236 "unknown scope for %.100s in %.100s(%s) in %s\n"
1237 "symbols: %s\nlocals: %s\nglobals: %s\n",
1238 PyString_AS_STRING(name),
1239 PyString_AS_STRING(c->u->u_name),
1240 PyObject_REPR(c->u->u_ste->ste_id),
1241 c->c_filename,
1242 PyObject_REPR(c->u->u_ste->ste_symbols),
1243 PyObject_REPR(c->u->u_varnames),
1244 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001246 Py_FatalError(buf);
1247 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001248
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static int
1253compiler_lookup_arg(PyObject *dict, PyObject *name)
1254{
1255 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001260 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 return PyInt_AS_LONG(v);
1264}
1265
1266static int
1267compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1268{
1269 int i, free = PyCode_GetNumFree(co);
1270 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1272 ADDOP_I(c, MAKE_FUNCTION, args);
1273 return 1;
1274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 for (i = 0; i < free; ++i) {
1276 /* Bypass com_addop_varname because it will generate
1277 LOAD_DEREF but LOAD_CLOSURE is needed.
1278 */
1279 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1280 int arg, reftype;
1281
1282 /* Special case: If a class contains a method with a
1283 free variable that has the same name as a method,
1284 the name will be considered free *and* local in the
1285 class. It should be handled by the closure, as
1286 well as by the normal name loookup logic.
1287 */
1288 reftype = get_ref_type(c, name);
1289 if (reftype == CELL)
1290 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1291 else /* (reftype == FREE) */
1292 arg = compiler_lookup_arg(c->u->u_freevars, name);
1293 if (arg == -1) {
1294 printf("lookup %s in %s %d %d\n"
1295 "freevars of %s: %s\n",
1296 PyObject_REPR(name),
1297 PyString_AS_STRING(c->u->u_name),
1298 reftype, arg,
1299 PyString_AS_STRING(co->co_name),
1300 PyObject_REPR(co->co_freevars));
1301 Py_FatalError("compiler_make_closure()");
1302 }
1303 ADDOP_I(c, LOAD_CLOSURE, arg);
1304 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001305 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, MAKE_CLOSURE, args);
1308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311static int
1312compiler_decorators(struct compiler *c, asdl_seq* decos)
1313{
1314 int i;
1315
1316 if (!decos)
1317 return 1;
1318
1319 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001320 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321 }
1322 return 1;
1323}
1324
1325static int
1326compiler_arguments(struct compiler *c, arguments_ty args)
1327{
1328 int i;
1329 int n = asdl_seq_LEN(args->args);
1330 /* Correctly handle nested argument lists */
1331 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001332 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (arg->kind == Tuple_kind) {
1334 PyObject *id = PyString_FromFormat(".%d", i);
1335 if (id == NULL) {
1336 return 0;
1337 }
1338 if (!compiler_nameop(c, id, Load)) {
1339 Py_DECREF(id);
1340 return 0;
1341 }
1342 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001343 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 }
1345 }
1346 return 1;
1347}
1348
1349static int
1350compiler_function(struct compiler *c, stmt_ty s)
1351{
1352 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001353 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 arguments_ty args = s->v.FunctionDef.args;
1355 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001356 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 int i, n, docstring;
1358
1359 assert(s->kind == FunctionDef_kind);
1360
1361 if (!compiler_decorators(c, decos))
1362 return 0;
1363 if (args->defaults)
1364 VISIT_SEQ(c, expr, args->defaults);
1365 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1366 s->lineno))
1367 return 0;
1368
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001369 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001370 docstring = compiler_isdocstring(st);
1371 if (docstring)
1372 first_const = st->v.Expr.value->v.Str.s;
1373 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001374 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001375 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001378 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 compiler_arguments(c, args);
1380
1381 c->u->u_argcount = asdl_seq_LEN(args->args);
1382 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001383 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001385 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1386 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387 }
1388 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001389 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 if (co == NULL)
1391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001394 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395
1396 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1397 ADDOP_I(c, CALL_FUNCTION, 1);
1398 }
1399
1400 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1401}
1402
1403static int
1404compiler_class(struct compiler *c, stmt_ty s)
1405{
1406 int n;
1407 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001408 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409 /* push class name on stack, needed by BUILD_CLASS */
1410 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1411 /* push the tuple of base classes on the stack */
1412 n = asdl_seq_LEN(s->v.ClassDef.bases);
1413 if (n > 0)
1414 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1415 ADDOP_I(c, BUILD_TUPLE, n);
1416 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1417 s->lineno))
1418 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001419 c->u->u_private = s->v.ClassDef.name;
1420 Py_INCREF(c->u->u_private);
1421 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422 if (!str || !compiler_nameop(c, str, Load)) {
1423 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001424 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001426 }
1427
1428 Py_DECREF(str);
1429 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430 if (!str || !compiler_nameop(c, str, Store)) {
1431 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001432 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 }
1435 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001437 if (!compiler_body(c, s->v.ClassDef.body)) {
1438 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001442 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1443 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001445 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 if (co == NULL)
1447 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001450 Py_DECREF(co);
1451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 ADDOP_I(c, CALL_FUNCTION, 0);
1453 ADDOP(c, BUILD_CLASS);
1454 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1455 return 0;
1456 return 1;
1457}
1458
1459static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001460compiler_ifexp(struct compiler *c, expr_ty e)
1461{
1462 basicblock *end, *next;
1463
1464 assert(e->kind == IfExp_kind);
1465 end = compiler_new_block(c);
1466 if (end == NULL)
1467 return 0;
1468 next = compiler_new_block(c);
1469 if (next == NULL)
1470 return 0;
1471 VISIT(c, expr, e->v.IfExp.test);
1472 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1473 ADDOP(c, POP_TOP);
1474 VISIT(c, expr, e->v.IfExp.body);
1475 ADDOP_JREL(c, JUMP_FORWARD, end);
1476 compiler_use_next_block(c, next);
1477 ADDOP(c, POP_TOP);
1478 VISIT(c, expr, e->v.IfExp.orelse);
1479 compiler_use_next_block(c, end);
1480 return 1;
1481}
1482
1483static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484compiler_lambda(struct compiler *c, expr_ty e)
1485{
1486 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001487 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 arguments_ty args = e->v.Lambda.args;
1489 assert(e->kind == Lambda_kind);
1490
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001491 if (!name) {
1492 name = PyString_InternFromString("<lambda>");
1493 if (!name)
1494 return 0;
1495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
1497 if (args->defaults)
1498 VISIT_SEQ(c, expr, args->defaults);
1499 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1500 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001501
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001502 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 compiler_arguments(c, args);
1504
1505 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001506 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1507 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001509 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 if (co == NULL)
1511 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001513 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001514 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515
1516 return 1;
1517}
1518
1519static int
1520compiler_print(struct compiler *c, stmt_ty s)
1521{
1522 int i, n;
1523 bool dest;
1524
1525 assert(s->kind == Print_kind);
1526 n = asdl_seq_LEN(s->v.Print.values);
1527 dest = false;
1528 if (s->v.Print.dest) {
1529 VISIT(c, expr, s->v.Print.dest);
1530 dest = true;
1531 }
1532 for (i = 0; i < n; i++) {
1533 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1534 if (dest) {
1535 ADDOP(c, DUP_TOP);
1536 VISIT(c, expr, e);
1537 ADDOP(c, ROT_TWO);
1538 ADDOP(c, PRINT_ITEM_TO);
1539 }
1540 else {
1541 VISIT(c, expr, e);
1542 ADDOP(c, PRINT_ITEM);
1543 }
1544 }
1545 if (s->v.Print.nl) {
1546 if (dest)
1547 ADDOP(c, PRINT_NEWLINE_TO)
1548 else
1549 ADDOP(c, PRINT_NEWLINE)
1550 }
1551 else if (dest)
1552 ADDOP(c, POP_TOP);
1553 return 1;
1554}
1555
1556static int
1557compiler_if(struct compiler *c, stmt_ty s)
1558{
1559 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001560 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561 assert(s->kind == If_kind);
1562 end = compiler_new_block(c);
1563 if (end == NULL)
1564 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001565 next = compiler_new_block(c);
1566 if (next == NULL)
1567 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001568
1569 constant = expr_constant(s->v.If.test);
1570 /* constant = 0: "if 0"
1571 * constant = 1: "if 1", "if 2", ...
1572 * constant = -1: rest */
1573 if (constant == 0) {
1574 if (s->v.If.orelse)
1575 VISIT_SEQ(c, stmt, s->v.If.orelse);
1576 } else if (constant == 1) {
1577 VISIT_SEQ(c, stmt, s->v.If.body);
1578 } else {
1579 VISIT(c, expr, s->v.If.test);
1580 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1581 ADDOP(c, POP_TOP);
1582 VISIT_SEQ(c, stmt, s->v.If.body);
1583 ADDOP_JREL(c, JUMP_FORWARD, end);
1584 compiler_use_next_block(c, next);
1585 ADDOP(c, POP_TOP);
1586 if (s->v.If.orelse)
1587 VISIT_SEQ(c, stmt, s->v.If.orelse);
1588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589 compiler_use_next_block(c, end);
1590 return 1;
1591}
1592
1593static int
1594compiler_for(struct compiler *c, stmt_ty s)
1595{
1596 basicblock *start, *cleanup, *end;
1597
1598 start = compiler_new_block(c);
1599 cleanup = compiler_new_block(c);
1600 end = compiler_new_block(c);
1601 if (start == NULL || end == NULL || cleanup == NULL)
1602 return 0;
1603 ADDOP_JREL(c, SETUP_LOOP, end);
1604 if (!compiler_push_fblock(c, LOOP, start))
1605 return 0;
1606 VISIT(c, expr, s->v.For.iter);
1607 ADDOP(c, GET_ITER);
1608 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001609 /* XXX(nnorwitz): is there a better way to handle this?
1610 for loops are special, we want to be able to trace them
1611 each time around, so we need to set an extra line number. */
1612 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613 ADDOP_JREL(c, FOR_ITER, cleanup);
1614 VISIT(c, expr, s->v.For.target);
1615 VISIT_SEQ(c, stmt, s->v.For.body);
1616 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1617 compiler_use_next_block(c, cleanup);
1618 ADDOP(c, POP_BLOCK);
1619 compiler_pop_fblock(c, LOOP, start);
1620 VISIT_SEQ(c, stmt, s->v.For.orelse);
1621 compiler_use_next_block(c, end);
1622 return 1;
1623}
1624
1625static int
1626compiler_while(struct compiler *c, stmt_ty s)
1627{
1628 basicblock *loop, *orelse, *end, *anchor = NULL;
1629 int constant = expr_constant(s->v.While.test);
1630
1631 if (constant == 0)
1632 return 1;
1633 loop = compiler_new_block(c);
1634 end = compiler_new_block(c);
1635 if (constant == -1) {
1636 anchor = compiler_new_block(c);
1637 if (anchor == NULL)
1638 return 0;
1639 }
1640 if (loop == NULL || end == NULL)
1641 return 0;
1642 if (s->v.While.orelse) {
1643 orelse = compiler_new_block(c);
1644 if (orelse == NULL)
1645 return 0;
1646 }
1647 else
1648 orelse = NULL;
1649
1650 ADDOP_JREL(c, SETUP_LOOP, end);
1651 compiler_use_next_block(c, loop);
1652 if (!compiler_push_fblock(c, LOOP, loop))
1653 return 0;
1654 if (constant == -1) {
1655 VISIT(c, expr, s->v.While.test);
1656 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1657 ADDOP(c, POP_TOP);
1658 }
1659 VISIT_SEQ(c, stmt, s->v.While.body);
1660 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1661
1662 /* XXX should the two POP instructions be in a separate block
1663 if there is no else clause ?
1664 */
1665
1666 if (constant == -1) {
1667 compiler_use_next_block(c, anchor);
1668 ADDOP(c, POP_TOP);
1669 ADDOP(c, POP_BLOCK);
1670 }
1671 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001672 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673 VISIT_SEQ(c, stmt, s->v.While.orelse);
1674 compiler_use_next_block(c, end);
1675
1676 return 1;
1677}
1678
1679static int
1680compiler_continue(struct compiler *c)
1681{
1682 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1683 int i;
1684
1685 if (!c->u->u_nfblocks)
1686 return compiler_error(c, LOOP_ERROR_MSG);
1687 i = c->u->u_nfblocks - 1;
1688 switch (c->u->u_fblock[i].fb_type) {
1689 case LOOP:
1690 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1691 break;
1692 case EXCEPT:
1693 case FINALLY_TRY:
1694 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1695 ;
1696 if (i == -1)
1697 return compiler_error(c, LOOP_ERROR_MSG);
1698 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1699 break;
1700 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001701 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 "'continue' not supported inside 'finally' clause");
1703 }
1704
1705 return 1;
1706}
1707
1708/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1709
1710 SETUP_FINALLY L
1711 <code for body>
1712 POP_BLOCK
1713 LOAD_CONST <None>
1714 L: <code for finalbody>
1715 END_FINALLY
1716
1717 The special instructions use the block stack. Each block
1718 stack entry contains the instruction that created it (here
1719 SETUP_FINALLY), the level of the value stack at the time the
1720 block stack entry was created, and a label (here L).
1721
1722 SETUP_FINALLY:
1723 Pushes the current value stack level and the label
1724 onto the block stack.
1725 POP_BLOCK:
1726 Pops en entry from the block stack, and pops the value
1727 stack until its level is the same as indicated on the
1728 block stack. (The label is ignored.)
1729 END_FINALLY:
1730 Pops a variable number of entries from the *value* stack
1731 and re-raises the exception they specify. The number of
1732 entries popped depends on the (pseudo) exception type.
1733
1734 The block stack is unwound when an exception is raised:
1735 when a SETUP_FINALLY entry is found, the exception is pushed
1736 onto the value stack (and the exception condition is cleared),
1737 and the interpreter jumps to the label gotten from the block
1738 stack.
1739*/
1740
1741static int
1742compiler_try_finally(struct compiler *c, stmt_ty s)
1743{
1744 basicblock *body, *end;
1745 body = compiler_new_block(c);
1746 end = compiler_new_block(c);
1747 if (body == NULL || end == NULL)
1748 return 0;
1749
1750 ADDOP_JREL(c, SETUP_FINALLY, end);
1751 compiler_use_next_block(c, body);
1752 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1753 return 0;
1754 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1755 ADDOP(c, POP_BLOCK);
1756 compiler_pop_fblock(c, FINALLY_TRY, body);
1757
1758 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1759 compiler_use_next_block(c, end);
1760 if (!compiler_push_fblock(c, FINALLY_END, end))
1761 return 0;
1762 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1763 ADDOP(c, END_FINALLY);
1764 compiler_pop_fblock(c, FINALLY_END, end);
1765
1766 return 1;
1767}
1768
1769/*
1770 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1771 (The contents of the value stack is shown in [], with the top
1772 at the right; 'tb' is trace-back info, 'val' the exception's
1773 associated value, and 'exc' the exception.)
1774
1775 Value stack Label Instruction Argument
1776 [] SETUP_EXCEPT L1
1777 [] <code for S>
1778 [] POP_BLOCK
1779 [] JUMP_FORWARD L0
1780
1781 [tb, val, exc] L1: DUP )
1782 [tb, val, exc, exc] <evaluate E1> )
1783 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1784 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1785 [tb, val, exc, 1] POP )
1786 [tb, val, exc] POP
1787 [tb, val] <assign to V1> (or POP if no V1)
1788 [tb] POP
1789 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001790 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
1792 [tb, val, exc, 0] L2: POP
1793 [tb, val, exc] DUP
1794 .............................etc.......................
1795
1796 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001797 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798
1799 [] L0: <next statement>
1800
1801 Of course, parts are not generated if Vi or Ei is not present.
1802*/
1803static int
1804compiler_try_except(struct compiler *c, stmt_ty s)
1805{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001806 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 int i, n;
1808
1809 body = compiler_new_block(c);
1810 except = compiler_new_block(c);
1811 orelse = compiler_new_block(c);
1812 end = compiler_new_block(c);
1813 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1814 return 0;
1815 ADDOP_JREL(c, SETUP_EXCEPT, except);
1816 compiler_use_next_block(c, body);
1817 if (!compiler_push_fblock(c, EXCEPT, body))
1818 return 0;
1819 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1820 ADDOP(c, POP_BLOCK);
1821 compiler_pop_fblock(c, EXCEPT, body);
1822 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1823 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1824 compiler_use_next_block(c, except);
1825 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001826 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 s->v.TryExcept.handlers, i);
1828 if (!handler->type && i < n-1)
1829 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001830 c->u->u_lineno_set = false;
1831 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 except = compiler_new_block(c);
1833 if (except == NULL)
1834 return 0;
1835 if (handler->type) {
1836 ADDOP(c, DUP_TOP);
1837 VISIT(c, expr, handler->type);
1838 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1839 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1840 ADDOP(c, POP_TOP);
1841 }
1842 ADDOP(c, POP_TOP);
1843 if (handler->name) {
1844 VISIT(c, expr, handler->name);
1845 }
1846 else {
1847 ADDOP(c, POP_TOP);
1848 }
1849 ADDOP(c, POP_TOP);
1850 VISIT_SEQ(c, stmt, handler->body);
1851 ADDOP_JREL(c, JUMP_FORWARD, end);
1852 compiler_use_next_block(c, except);
1853 if (handler->type)
1854 ADDOP(c, POP_TOP);
1855 }
1856 ADDOP(c, END_FINALLY);
1857 compiler_use_next_block(c, orelse);
1858 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1859 compiler_use_next_block(c, end);
1860 return 1;
1861}
1862
1863static int
1864compiler_import_as(struct compiler *c, identifier name, identifier asname)
1865{
1866 /* The IMPORT_NAME opcode was already generated. This function
1867 merely needs to bind the result to a name.
1868
1869 If there is a dot in name, we need to split it and emit a
1870 LOAD_ATTR for each name.
1871 */
1872 const char *src = PyString_AS_STRING(name);
1873 const char *dot = strchr(src, '.');
1874 if (dot) {
1875 /* Consume the base module name to get the first attribute */
1876 src = dot + 1;
1877 while (dot) {
1878 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001879 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001881 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001883 if (!attr)
1884 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001886 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 src = dot + 1;
1888 }
1889 }
1890 return compiler_nameop(c, asname, Store);
1891}
1892
1893static int
1894compiler_import(struct compiler *c, stmt_ty s)
1895{
1896 /* The Import node stores a module name like a.b.c as a single
1897 string. This is convenient for all cases except
1898 import a.b.c as d
1899 where we need to parse that string to extract the individual
1900 module names.
1901 XXX Perhaps change the representation to make this case simpler?
1902 */
1903 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001906 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001908 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909
Guido van Rossum45aecf42006-03-15 04:58:47 +00001910 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001911 if (level == NULL)
1912 return 0;
1913
1914 ADDOP_O(c, LOAD_CONST, level, consts);
1915 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1917 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1918
1919 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001920 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001921 if (!r)
1922 return r;
1923 }
1924 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925 identifier tmp = alias->name;
1926 const char *base = PyString_AS_STRING(alias->name);
1927 char *dot = strchr(base, '.');
1928 if (dot)
1929 tmp = PyString_FromStringAndSize(base,
1930 dot - base);
1931 r = compiler_nameop(c, tmp, Store);
1932 if (dot) {
1933 Py_DECREF(tmp);
1934 }
1935 if (!r)
1936 return r;
1937 }
1938 }
1939 return 1;
1940}
1941
1942static int
1943compiler_from_import(struct compiler *c, stmt_ty s)
1944{
1945 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
1947 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001948 PyObject *level;
1949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950 if (!names)
1951 return 0;
1952
Guido van Rossum45aecf42006-03-15 04:58:47 +00001953 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001954 if (!level) {
1955 Py_DECREF(names);
1956 return 0;
1957 }
1958
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 /* build up the names */
1960 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001961 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 Py_INCREF(alias->name);
1963 PyTuple_SET_ITEM(names, i, alias->name);
1964 }
1965
1966 if (s->lineno > c->c_future->ff_lineno) {
1967 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1968 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001969 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970 Py_DECREF(names);
1971 return compiler_error(c,
1972 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001973 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
1975 }
1976 }
1977
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001978 ADDOP_O(c, LOAD_CONST, level, consts);
1979 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001981 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1983 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001984 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 identifier store_name;
1986
1987 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1988 assert(n == 1);
1989 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 }
1992
1993 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1994 store_name = alias->name;
1995 if (alias->asname)
1996 store_name = alias->asname;
1997
1998 if (!compiler_nameop(c, store_name, Store)) {
1999 Py_DECREF(names);
2000 return 0;
2001 }
2002 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002003 /* remove imported module */
2004 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 return 1;
2006}
2007
2008static int
2009compiler_assert(struct compiler *c, stmt_ty s)
2010{
2011 static PyObject *assertion_error = NULL;
2012 basicblock *end;
2013
2014 if (Py_OptimizeFlag)
2015 return 1;
2016 if (assertion_error == NULL) {
2017 assertion_error = PyString_FromString("AssertionError");
2018 if (assertion_error == NULL)
2019 return 0;
2020 }
2021 VISIT(c, expr, s->v.Assert.test);
2022 end = compiler_new_block(c);
2023 if (end == NULL)
2024 return 0;
2025 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2026 ADDOP(c, POP_TOP);
2027 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2028 if (s->v.Assert.msg) {
2029 VISIT(c, expr, s->v.Assert.msg);
2030 ADDOP_I(c, RAISE_VARARGS, 2);
2031 }
2032 else {
2033 ADDOP_I(c, RAISE_VARARGS, 1);
2034 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002035 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 ADDOP(c, POP_TOP);
2037 return 1;
2038}
2039
2040static int
2041compiler_visit_stmt(struct compiler *c, stmt_ty s)
2042{
2043 int i, n;
2044
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002045 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 c->u->u_lineno = s->lineno;
2047 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002048
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002050 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002054 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 if (c->u->u_ste->ste_type != FunctionBlock)
2056 return compiler_error(c, "'return' outside function");
2057 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 VISIT(c, expr, s->v.Return.value);
2059 }
2060 else
2061 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2062 ADDOP(c, RETURN_VALUE);
2063 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002064 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 VISIT_SEQ(c, expr, s->v.Delete.targets)
2066 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 n = asdl_seq_LEN(s->v.Assign.targets);
2069 VISIT(c, expr, s->v.Assign.value);
2070 for (i = 0; i < n; i++) {
2071 if (i < n - 1)
2072 ADDOP(c, DUP_TOP);
2073 VISIT(c, expr,
2074 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2075 }
2076 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002083 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 n = 0;
2089 if (s->v.Raise.type) {
2090 VISIT(c, expr, s->v.Raise.type);
2091 n++;
2092 if (s->v.Raise.inst) {
2093 VISIT(c, expr, s->v.Raise.inst);
2094 n++;
2095 if (s->v.Raise.tback) {
2096 VISIT(c, expr, s->v.Raise.tback);
2097 n++;
2098 }
2099 }
2100 }
2101 ADDOP_I(c, RAISE_VARARGS, n);
2102 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002115 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002117 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 ADDOP(c, PRINT_EXPR);
2119 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002120 else if (s->v.Expr.value->kind != Str_kind &&
2121 s->v.Expr.value->kind != Num_kind) {
2122 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123 ADDOP(c, POP_TOP);
2124 }
2125 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002126 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002128 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 if (!c->u->u_nfblocks)
2130 return compiler_error(c, "'break' outside loop");
2131 ADDOP(c, BREAK_LOOP);
2132 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002133 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002135 case With_kind:
2136 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002137 }
2138 return 1;
2139}
2140
2141static int
2142unaryop(unaryop_ty op)
2143{
2144 switch (op) {
2145 case Invert:
2146 return UNARY_INVERT;
2147 case Not:
2148 return UNARY_NOT;
2149 case UAdd:
2150 return UNARY_POSITIVE;
2151 case USub:
2152 return UNARY_NEGATIVE;
2153 }
2154 return 0;
2155}
2156
2157static int
2158binop(struct compiler *c, operator_ty op)
2159{
2160 switch (op) {
2161 case Add:
2162 return BINARY_ADD;
2163 case Sub:
2164 return BINARY_SUBTRACT;
2165 case Mult:
2166 return BINARY_MULTIPLY;
2167 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002168 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 case Mod:
2170 return BINARY_MODULO;
2171 case Pow:
2172 return BINARY_POWER;
2173 case LShift:
2174 return BINARY_LSHIFT;
2175 case RShift:
2176 return BINARY_RSHIFT;
2177 case BitOr:
2178 return BINARY_OR;
2179 case BitXor:
2180 return BINARY_XOR;
2181 case BitAnd:
2182 return BINARY_AND;
2183 case FloorDiv:
2184 return BINARY_FLOOR_DIVIDE;
2185 }
2186 return 0;
2187}
2188
2189static int
2190cmpop(cmpop_ty op)
2191{
2192 switch (op) {
2193 case Eq:
2194 return PyCmp_EQ;
2195 case NotEq:
2196 return PyCmp_NE;
2197 case Lt:
2198 return PyCmp_LT;
2199 case LtE:
2200 return PyCmp_LE;
2201 case Gt:
2202 return PyCmp_GT;
2203 case GtE:
2204 return PyCmp_GE;
2205 case Is:
2206 return PyCmp_IS;
2207 case IsNot:
2208 return PyCmp_IS_NOT;
2209 case In:
2210 return PyCmp_IN;
2211 case NotIn:
2212 return PyCmp_NOT_IN;
2213 }
2214 return PyCmp_BAD;
2215}
2216
2217static int
2218inplace_binop(struct compiler *c, operator_ty op)
2219{
2220 switch (op) {
2221 case Add:
2222 return INPLACE_ADD;
2223 case Sub:
2224 return INPLACE_SUBTRACT;
2225 case Mult:
2226 return INPLACE_MULTIPLY;
2227 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002228 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 case Mod:
2230 return INPLACE_MODULO;
2231 case Pow:
2232 return INPLACE_POWER;
2233 case LShift:
2234 return INPLACE_LSHIFT;
2235 case RShift:
2236 return INPLACE_RSHIFT;
2237 case BitOr:
2238 return INPLACE_OR;
2239 case BitXor:
2240 return INPLACE_XOR;
2241 case BitAnd:
2242 return INPLACE_AND;
2243 case FloorDiv:
2244 return INPLACE_FLOOR_DIVIDE;
2245 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002246 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002247 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 return 0;
2249}
2250
2251static int
2252compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2253{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002254 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2256
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002257 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002258 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259 /* XXX AugStore isn't used anywhere! */
2260
2261 /* First check for assignment to __debug__. Param? */
2262 if ((ctx == Store || ctx == AugStore || ctx == Del)
2263 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2264 return compiler_error(c, "can not assign to __debug__");
2265 }
2266
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002267 mangled = _Py_Mangle(c->u->u_private, name);
2268 if (!mangled)
2269 return 0;
2270
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 op = 0;
2272 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002273 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 switch (scope) {
2275 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002276 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277 optype = OP_DEREF;
2278 break;
2279 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002280 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 optype = OP_DEREF;
2282 break;
2283 case LOCAL:
2284 if (c->u->u_ste->ste_type == FunctionBlock)
2285 optype = OP_FAST;
2286 break;
2287 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002288 if (c->u->u_ste->ste_type == FunctionBlock &&
2289 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 optype = OP_GLOBAL;
2291 break;
2292 case GLOBAL_EXPLICIT:
2293 optype = OP_GLOBAL;
2294 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002295 default:
2296 /* scope can be 0 */
2297 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 }
2299
2300 /* XXX Leave assert here, but handle __doc__ and the like better */
2301 assert(scope || PyString_AS_STRING(name)[0] == '_');
2302
2303 switch (optype) {
2304 case OP_DEREF:
2305 switch (ctx) {
2306 case Load: op = LOAD_DEREF; break;
2307 case Store: op = STORE_DEREF; break;
2308 case AugLoad:
2309 case AugStore:
2310 break;
2311 case Del:
2312 PyErr_Format(PyExc_SyntaxError,
2313 "can not delete variable '%s' referenced "
2314 "in nested scope",
2315 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002316 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002319 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002320 PyErr_SetString(PyExc_SystemError,
2321 "param invalid for deref variable");
2322 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 }
2324 break;
2325 case OP_FAST:
2326 switch (ctx) {
2327 case Load: op = LOAD_FAST; break;
2328 case Store: op = STORE_FAST; break;
2329 case Del: op = DELETE_FAST; break;
2330 case AugLoad:
2331 case AugStore:
2332 break;
2333 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002334 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002335 PyErr_SetString(PyExc_SystemError,
2336 "param invalid for local variable");
2337 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002339 ADDOP_O(c, op, mangled, varnames);
2340 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 return 1;
2342 case OP_GLOBAL:
2343 switch (ctx) {
2344 case Load: op = LOAD_GLOBAL; break;
2345 case Store: op = STORE_GLOBAL; break;
2346 case Del: op = DELETE_GLOBAL; 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 global variable");
2354 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355 }
2356 break;
2357 case OP_NAME:
2358 switch (ctx) {
2359 case Load: op = LOAD_NAME; break;
2360 case Store: op = STORE_NAME; break;
2361 case Del: op = DELETE_NAME; break;
2362 case AugLoad:
2363 case AugStore:
2364 break;
2365 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002366 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002367 PyErr_SetString(PyExc_SystemError,
2368 "param invalid for name variable");
2369 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370 }
2371 break;
2372 }
2373
2374 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002375 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002376 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002377 if (arg < 0)
2378 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002379 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002380}
2381
2382static int
2383compiler_boolop(struct compiler *c, expr_ty e)
2384{
2385 basicblock *end;
2386 int jumpi, i, n;
2387 asdl_seq *s;
2388
2389 assert(e->kind == BoolOp_kind);
2390 if (e->v.BoolOp.op == And)
2391 jumpi = JUMP_IF_FALSE;
2392 else
2393 jumpi = JUMP_IF_TRUE;
2394 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002395 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396 return 0;
2397 s = e->v.BoolOp.values;
2398 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002399 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002401 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002402 ADDOP_JREL(c, jumpi, end);
2403 ADDOP(c, POP_TOP)
2404 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406 compiler_use_next_block(c, end);
2407 return 1;
2408}
2409
2410static int
2411compiler_list(struct compiler *c, expr_ty e)
2412{
2413 int n = asdl_seq_LEN(e->v.List.elts);
2414 if (e->v.List.ctx == Store) {
2415 ADDOP_I(c, UNPACK_SEQUENCE, n);
2416 }
2417 VISIT_SEQ(c, expr, e->v.List.elts);
2418 if (e->v.List.ctx == Load) {
2419 ADDOP_I(c, BUILD_LIST, n);
2420 }
2421 return 1;
2422}
2423
2424static int
2425compiler_tuple(struct compiler *c, expr_ty e)
2426{
2427 int n = asdl_seq_LEN(e->v.Tuple.elts);
2428 if (e->v.Tuple.ctx == Store) {
2429 ADDOP_I(c, UNPACK_SEQUENCE, n);
2430 }
2431 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2432 if (e->v.Tuple.ctx == Load) {
2433 ADDOP_I(c, BUILD_TUPLE, n);
2434 }
2435 return 1;
2436}
2437
2438static int
2439compiler_compare(struct compiler *c, expr_ty e)
2440{
2441 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002442 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002443
2444 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2445 VISIT(c, expr, e->v.Compare.left);
2446 n = asdl_seq_LEN(e->v.Compare.ops);
2447 assert(n > 0);
2448 if (n > 1) {
2449 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002450 if (cleanup == NULL)
2451 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002452 VISIT(c, expr,
2453 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 }
2455 for (i = 1; i < n; i++) {
2456 ADDOP(c, DUP_TOP);
2457 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002459 cmpop((cmpop_ty)(asdl_seq_GET(
2460 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2462 NEXT_BLOCK(c);
2463 ADDOP(c, POP_TOP);
2464 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002465 VISIT(c, expr,
2466 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002468 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002470 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 if (n > 1) {
2472 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002473 if (end == NULL)
2474 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 ADDOP_JREL(c, JUMP_FORWARD, end);
2476 compiler_use_next_block(c, cleanup);
2477 ADDOP(c, ROT_TWO);
2478 ADDOP(c, POP_TOP);
2479 compiler_use_next_block(c, end);
2480 }
2481 return 1;
2482}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002483#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484
2485static int
2486compiler_call(struct compiler *c, expr_ty e)
2487{
2488 int n, code = 0;
2489
2490 VISIT(c, expr, e->v.Call.func);
2491 n = asdl_seq_LEN(e->v.Call.args);
2492 VISIT_SEQ(c, expr, e->v.Call.args);
2493 if (e->v.Call.keywords) {
2494 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2495 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2496 }
2497 if (e->v.Call.starargs) {
2498 VISIT(c, expr, e->v.Call.starargs);
2499 code |= 1;
2500 }
2501 if (e->v.Call.kwargs) {
2502 VISIT(c, expr, e->v.Call.kwargs);
2503 code |= 2;
2504 }
2505 switch (code) {
2506 case 0:
2507 ADDOP_I(c, CALL_FUNCTION, n);
2508 break;
2509 case 1:
2510 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2511 break;
2512 case 2:
2513 ADDOP_I(c, CALL_FUNCTION_KW, n);
2514 break;
2515 case 3:
2516 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2517 break;
2518 }
2519 return 1;
2520}
2521
2522static int
2523compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002524 asdl_seq *generators, int gen_index,
2525 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526{
2527 /* generate code for the iterator, then each of the ifs,
2528 and then write to the element */
2529
2530 comprehension_ty l;
2531 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002532 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533
2534 start = compiler_new_block(c);
2535 skip = compiler_new_block(c);
2536 if_cleanup = compiler_new_block(c);
2537 anchor = compiler_new_block(c);
2538
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2540 anchor == NULL)
2541 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002543 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 VISIT(c, expr, l->iter);
2545 ADDOP(c, GET_ITER);
2546 compiler_use_next_block(c, start);
2547 ADDOP_JREL(c, FOR_ITER, anchor);
2548 NEXT_BLOCK(c);
2549 VISIT(c, expr, l->target);
2550
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002551 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552 n = asdl_seq_LEN(l->ifs);
2553 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002554 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555 VISIT(c, expr, e);
2556 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2557 NEXT_BLOCK(c);
2558 ADDOP(c, POP_TOP);
2559 }
2560
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002561 if (++gen_index < asdl_seq_LEN(generators))
2562 if (!compiler_listcomp_generator(c, tmpname,
2563 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002566 /* only append after the last for generator */
2567 if (gen_index >= asdl_seq_LEN(generators)) {
2568 if (!compiler_nameop(c, tmpname, Load))
2569 return 0;
2570 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002571 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002572
2573 compiler_use_next_block(c, skip);
2574 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575 for (i = 0; i < n; i++) {
2576 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002577 if (i == 0)
2578 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 ADDOP(c, POP_TOP);
2580 }
2581 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2582 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002583 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002584 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002585 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 return 0;
2587
2588 return 1;
2589}
2590
2591static int
2592compiler_listcomp(struct compiler *c, expr_ty e)
2593{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002595 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002596 static identifier append;
2597 asdl_seq *generators = e->v.ListComp.generators;
2598
2599 assert(e->kind == ListComp_kind);
2600 if (!append) {
2601 append = PyString_InternFromString("append");
2602 if (!append)
2603 return 0;
2604 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002605 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 if (!tmp)
2607 return 0;
2608 ADDOP_I(c, BUILD_LIST, 0);
2609 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2612 e->v.ListComp.elt);
2613 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 return rc;
2615}
2616
2617static int
2618compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 asdl_seq *generators, int gen_index,
2620 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621{
2622 /* generate code for the iterator, then each of the ifs,
2623 and then write to the element */
2624
2625 comprehension_ty ge;
2626 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628
2629 start = compiler_new_block(c);
2630 skip = compiler_new_block(c);
2631 if_cleanup = compiler_new_block(c);
2632 anchor = compiler_new_block(c);
2633 end = compiler_new_block(c);
2634
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002635 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 anchor == NULL || end == NULL)
2637 return 0;
2638
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 ADDOP_JREL(c, SETUP_LOOP, end);
2641 if (!compiler_push_fblock(c, LOOP, start))
2642 return 0;
2643
2644 if (gen_index == 0) {
2645 /* Receive outermost iter as an implicit argument */
2646 c->u->u_argcount = 1;
2647 ADDOP_I(c, LOAD_FAST, 0);
2648 }
2649 else {
2650 /* Sub-iter - calculate on the fly */
2651 VISIT(c, expr, ge->iter);
2652 ADDOP(c, GET_ITER);
2653 }
2654 compiler_use_next_block(c, start);
2655 ADDOP_JREL(c, FOR_ITER, anchor);
2656 NEXT_BLOCK(c);
2657 VISIT(c, expr, ge->target);
2658
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 n = asdl_seq_LEN(ge->ifs);
2661 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002662 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 VISIT(c, expr, e);
2664 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2665 NEXT_BLOCK(c);
2666 ADDOP(c, POP_TOP);
2667 }
2668
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2671 return 0;
2672
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 /* only append after the last 'for' generator */
2674 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 VISIT(c, expr, elt);
2676 ADDOP(c, YIELD_VALUE);
2677 ADDOP(c, POP_TOP);
2678
2679 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 for (i = 0; i < n; i++) {
2682 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 compiler_use_next_block(c, if_cleanup);
2685
2686 ADDOP(c, POP_TOP);
2687 }
2688 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2689 compiler_use_next_block(c, anchor);
2690 ADDOP(c, POP_BLOCK);
2691 compiler_pop_fblock(c, LOOP, start);
2692 compiler_use_next_block(c, end);
2693
2694 return 1;
2695}
2696
2697static int
2698compiler_genexp(struct compiler *c, expr_ty e)
2699{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002700 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 PyCodeObject *co;
2702 expr_ty outermost_iter = ((comprehension_ty)
2703 (asdl_seq_GET(e->v.GeneratorExp.generators,
2704 0)))->iter;
2705
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002706 if (!name) {
2707 name = PyString_FromString("<genexpr>");
2708 if (!name)
2709 return 0;
2710 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
2712 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2713 return 0;
2714 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2715 e->v.GeneratorExp.elt);
2716 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002717 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 if (co == NULL)
2719 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002722 Py_DECREF(co);
2723
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 VISIT(c, expr, outermost_iter);
2725 ADDOP(c, GET_ITER);
2726 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
2728 return 1;
2729}
2730
2731static int
2732compiler_visit_keyword(struct compiler *c, keyword_ty k)
2733{
2734 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2735 VISIT(c, expr, k->value);
2736 return 1;
2737}
2738
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002739/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 whether they are true or false.
2741
2742 Return values: 1 for true, 0 for false, -1 for non-constant.
2743 */
2744
2745static int
2746expr_constant(expr_ty e)
2747{
2748 switch (e->kind) {
2749 case Num_kind:
2750 return PyObject_IsTrue(e->v.Num.n);
2751 case Str_kind:
2752 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002753 case Name_kind:
2754 /* __debug__ is not assignable, so we can optimize
2755 * it away in if and while statements */
2756 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2757 "__debug__") == 0)
2758 return ! Py_OptimizeFlag;
2759 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760 default:
2761 return -1;
2762 }
2763}
2764
Guido van Rossumc2e20742006-02-27 22:32:47 +00002765/*
2766 Implements the with statement from PEP 343.
2767
2768 The semantics outlined in that PEP are as follows:
2769
2770 with EXPR as VAR:
2771 BLOCK
2772
2773 It is implemented roughly as:
2774
Thomas Wouters477c8d52006-05-27 19:21:47 +00002775 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002776 exit = context.__exit__ # not calling it
2777 value = context.__enter__()
2778 try:
2779 VAR = value # if VAR present in the syntax
2780 BLOCK
2781 finally:
2782 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002783 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002784 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002785 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002786 exit(*exc)
2787 */
2788static int
2789compiler_with(struct compiler *c, stmt_ty s)
2790{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002791 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002792 basicblock *block, *finally;
2793 identifier tmpexit, tmpvalue = NULL;
2794
2795 assert(s->kind == With_kind);
2796
Guido van Rossumc2e20742006-02-27 22:32:47 +00002797 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002798 enter_attr = PyString_InternFromString("__enter__");
2799 if (!enter_attr)
2800 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 }
2802 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002803 exit_attr = PyString_InternFromString("__exit__");
2804 if (!exit_attr)
2805 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002806 }
2807
2808 block = compiler_new_block(c);
2809 finally = compiler_new_block(c);
2810 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002811 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812
2813 /* Create a temporary variable to hold context.__exit__ */
2814 tmpexit = compiler_new_tmpname(c);
2815 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 PyArena_AddPyObject(c->c_arena, tmpexit);
2818
2819 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002820 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821 We need to do this rather than preserving it on the stack
2822 because SETUP_FINALLY remembers the stack level.
2823 We need to do the assignment *inside* the try/finally
2824 so that context.__exit__() is called when the assignment
2825 fails. But we need to call context.__enter__() *before*
2826 the try/finally so that if it fails we won't call
2827 context.__exit__().
2828 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002829 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002830 if (tmpvalue == NULL)
2831 return 0;
2832 PyArena_AddPyObject(c->c_arena, tmpvalue);
2833 }
2834
Thomas Wouters477c8d52006-05-27 19:21:47 +00002835 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837
2838 /* Squirrel away context.__exit__ */
2839 ADDOP(c, DUP_TOP);
2840 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2841 if (!compiler_nameop(c, tmpexit, Store))
2842 return 0;
2843
2844 /* Call context.__enter__() */
2845 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2846 ADDOP_I(c, CALL_FUNCTION, 0);
2847
2848 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002849 /* Store it in tmpvalue */
2850 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851 return 0;
2852 }
2853 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002854 /* Discard result from context.__enter__() */
2855 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002856 }
2857
2858 /* Start the try block */
2859 ADDOP_JREL(c, SETUP_FINALLY, finally);
2860
2861 compiler_use_next_block(c, block);
2862 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002864 }
2865
2866 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002867 /* Bind saved result of context.__enter__() to VAR */
2868 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002869 !compiler_nameop(c, tmpvalue, Del))
2870 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002871 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002872 }
2873
2874 /* BLOCK code */
2875 VISIT_SEQ(c, stmt, s->v.With.body);
2876
2877 /* End of try block; start the finally block */
2878 ADDOP(c, POP_BLOCK);
2879 compiler_pop_fblock(c, FINALLY_TRY, block);
2880
2881 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2882 compiler_use_next_block(c, finally);
2883 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002884 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002885
2886 /* Finally block starts; push tmpexit and issue our magic opcode. */
2887 if (!compiler_nameop(c, tmpexit, Load) ||
2888 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002889 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002890 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002891
2892 /* Finally block ends. */
2893 ADDOP(c, END_FINALLY);
2894 compiler_pop_fblock(c, FINALLY_END, finally);
2895 return 1;
2896}
2897
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898static int
2899compiler_visit_expr(struct compiler *c, expr_ty e)
2900{
2901 int i, n;
2902
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002903 /* If expr e has a different line number than the last expr/stmt,
2904 set a new line number for the next instruction.
2905 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 if (e->lineno > c->u->u_lineno) {
2907 c->u->u_lineno = e->lineno;
2908 c->u->u_lineno_set = false;
2909 }
2910 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002911 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002913 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 VISIT(c, expr, e->v.BinOp.left);
2915 VISIT(c, expr, e->v.BinOp.right);
2916 ADDOP(c, binop(c, e->v.BinOp.op));
2917 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002918 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919 VISIT(c, expr, e->v.UnaryOp.operand);
2920 ADDOP(c, unaryop(e->v.UnaryOp.op));
2921 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002922 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002924 case IfExp_kind:
2925 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 /* XXX get rid of arg? */
2928 ADDOP_I(c, BUILD_MAP, 0);
2929 n = asdl_seq_LEN(e->v.Dict.values);
2930 /* We must arrange things just right for STORE_SUBSCR.
2931 It wants the stack to look like (value) (dict) (key) */
2932 for (i = 0; i < n; i++) {
2933 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002934 VISIT(c, expr,
2935 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002937 VISIT(c, expr,
2938 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 ADDOP(c, STORE_SUBSCR);
2940 }
2941 break;
Guido van Rossum86e58e22006-08-28 15:27:34 +00002942 case Set_kind:
2943 n = asdl_seq_LEN(e->v.Set.elts);
2944 VISIT_SEQ(c, expr, e->v.Set.elts);
2945 ADDOP_I(c, BUILD_SET, n);
2946 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002947 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002949 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 return compiler_genexp(c, e);
2951 case Yield_kind:
2952 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002953 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 /*
2955 for (i = 0; i < c->u->u_nfblocks; i++) {
2956 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2957 return compiler_error(
2958 c, "'yield' not allowed in a 'try' "
2959 "block with a 'finally' clause");
2960 }
2961 */
2962 if (e->v.Yield.value) {
2963 VISIT(c, expr, e->v.Yield.value);
2964 }
2965 else {
2966 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2967 }
2968 ADDOP(c, YIELD_VALUE);
2969 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002970 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002972 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002974 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2976 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002977 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2979 break;
2980 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 if (e->v.Attribute.ctx != AugStore)
2983 VISIT(c, expr, e->v.Attribute.value);
2984 switch (e->v.Attribute.ctx) {
2985 case AugLoad:
2986 ADDOP(c, DUP_TOP);
2987 /* Fall through to load */
2988 case Load:
2989 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
2990 break;
2991 case AugStore:
2992 ADDOP(c, ROT_TWO);
2993 /* Fall through to save */
2994 case Store:
2995 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
2996 break;
2997 case Del:
2998 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
2999 break;
3000 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003001 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003002 PyErr_SetString(PyExc_SystemError,
3003 "param invalid in attribute expression");
3004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 }
3006 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003007 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008 switch (e->v.Subscript.ctx) {
3009 case AugLoad:
3010 VISIT(c, expr, e->v.Subscript.value);
3011 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3012 break;
3013 case Load:
3014 VISIT(c, expr, e->v.Subscript.value);
3015 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3016 break;
3017 case AugStore:
3018 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3019 break;
3020 case Store:
3021 VISIT(c, expr, e->v.Subscript.value);
3022 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3023 break;
3024 case Del:
3025 VISIT(c, expr, e->v.Subscript.value);
3026 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3027 break;
3028 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003029 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003030 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003031 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003032 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 }
3034 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003035 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3037 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003038 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003040 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003041 return compiler_tuple(c, e);
3042 }
3043 return 1;
3044}
3045
3046static int
3047compiler_augassign(struct compiler *c, stmt_ty s)
3048{
3049 expr_ty e = s->v.AugAssign.target;
3050 expr_ty auge;
3051
3052 assert(s->kind == AugAssign_kind);
3053
3054 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003055 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003057 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003058 if (auge == NULL)
3059 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060 VISIT(c, expr, auge);
3061 VISIT(c, expr, s->v.AugAssign.value);
3062 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3063 auge->v.Attribute.ctx = AugStore;
3064 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003065 break;
3066 case Subscript_kind:
3067 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003068 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003069 if (auge == NULL)
3070 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003071 VISIT(c, expr, auge);
3072 VISIT(c, expr, s->v.AugAssign.value);
3073 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003076 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003078 if (!compiler_nameop(c, e->v.Name.id, Load))
3079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 VISIT(c, expr, s->v.AugAssign.value);
3081 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3082 return compiler_nameop(c, e->v.Name.id, Store);
3083 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003084 PyErr_Format(PyExc_SystemError,
3085 "invalid node type (%d) for augmented assignment",
3086 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 }
3089 return 1;
3090}
3091
3092static int
3093compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3094{
3095 struct fblockinfo *f;
3096 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3097 return 0;
3098 f = &c->u->u_fblock[c->u->u_nfblocks++];
3099 f->fb_type = t;
3100 f->fb_block = b;
3101 return 1;
3102}
3103
3104static void
3105compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3106{
3107 struct compiler_unit *u = c->u;
3108 assert(u->u_nfblocks > 0);
3109 u->u_nfblocks--;
3110 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3111 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3112}
3113
3114/* Raises a SyntaxError and returns 0.
3115 If something goes wrong, a different exception may be raised.
3116*/
3117
3118static int
3119compiler_error(struct compiler *c, const char *errstr)
3120{
3121 PyObject *loc;
3122 PyObject *u = NULL, *v = NULL;
3123
3124 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3125 if (!loc) {
3126 Py_INCREF(Py_None);
3127 loc = Py_None;
3128 }
3129 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3130 Py_None, loc);
3131 if (!u)
3132 goto exit;
3133 v = Py_BuildValue("(zO)", errstr, u);
3134 if (!v)
3135 goto exit;
3136 PyErr_SetObject(PyExc_SyntaxError, v);
3137 exit:
3138 Py_DECREF(loc);
3139 Py_XDECREF(u);
3140 Py_XDECREF(v);
3141 return 0;
3142}
3143
3144static int
3145compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 /* XXX this code is duplicated */
3151 switch (ctx) {
3152 case AugLoad: /* fall through to Load */
3153 case Load: op = BINARY_SUBSCR; break;
3154 case AugStore:/* fall through to Store */
3155 case Store: op = STORE_SUBSCR; break;
3156 case Del: op = DELETE_SUBSCR; break;
3157 case Param:
3158 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003159 "invalid %s kind %d in subscript\n",
3160 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 return 0;
3162 }
3163 if (ctx == AugLoad) {
3164 ADDOP_I(c, DUP_TOPX, 2);
3165 }
3166 else if (ctx == AugStore) {
3167 ADDOP(c, ROT_THREE);
3168 }
3169 ADDOP(c, op);
3170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171}
3172
3173static int
3174compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3175{
3176 int n = 2;
3177 assert(s->kind == Slice_kind);
3178
3179 /* only handles the cases where BUILD_SLICE is emitted */
3180 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 }
3183 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003184 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003186
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003188 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189 }
3190 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003191 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 }
3193
3194 if (s->v.Slice.step) {
3195 n++;
3196 VISIT(c, expr, s->v.Slice.step);
3197 }
3198 ADDOP_I(c, BUILD_SLICE, n);
3199 return 1;
3200}
3201
3202static int
3203compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3204{
3205 int op = 0, slice_offset = 0, stack_count = 0;
3206
3207 assert(s->v.Slice.step == NULL);
3208 if (s->v.Slice.lower) {
3209 slice_offset++;
3210 stack_count++;
3211 if (ctx != AugStore)
3212 VISIT(c, expr, s->v.Slice.lower);
3213 }
3214 if (s->v.Slice.upper) {
3215 slice_offset += 2;
3216 stack_count++;
3217 if (ctx != AugStore)
3218 VISIT(c, expr, s->v.Slice.upper);
3219 }
3220
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 if (ctx == AugLoad) {
3222 switch (stack_count) {
3223 case 0: ADDOP(c, DUP_TOP); break;
3224 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3225 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3226 }
3227 }
3228 else if (ctx == AugStore) {
3229 switch (stack_count) {
3230 case 0: ADDOP(c, ROT_TWO); break;
3231 case 1: ADDOP(c, ROT_THREE); break;
3232 case 2: ADDOP(c, ROT_FOUR); break;
3233 }
3234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003235
3236 switch (ctx) {
3237 case AugLoad: /* fall through to Load */
3238 case Load: op = SLICE; break;
3239 case AugStore:/* fall through to Store */
3240 case Store: op = STORE_SLICE; break;
3241 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003242 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003243 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003244 PyErr_SetString(PyExc_SystemError,
3245 "param invalid in simple slice");
3246 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 }
3248
3249 ADDOP(c, op + slice_offset);
3250 return 1;
3251}
3252
3253static int
3254compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3255 expr_context_ty ctx)
3256{
3257 switch (s->kind) {
3258 case Ellipsis_kind:
3259 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3260 break;
3261 case Slice_kind:
3262 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 case Index_kind:
3264 VISIT(c, expr, s->v.Index.value);
3265 break;
3266 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003267 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003268 PyErr_SetString(PyExc_SystemError,
3269 "extended slice invalid in nested slice");
3270 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271 }
3272 return 1;
3273}
3274
3275
3276static int
3277compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3278{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003279 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003281 case Index_kind:
3282 kindname = "index";
3283 if (ctx != AugStore) {
3284 VISIT(c, expr, s->v.Index.value);
3285 }
3286 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003288 kindname = "ellipsis";
3289 if (ctx != AugStore) {
3290 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3291 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292 break;
3293 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003294 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295 if (!s->v.Slice.step)
3296 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003297 if (ctx != AugStore) {
3298 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 return 0;
3300 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003301 break;
3302 case ExtSlice_kind:
3303 kindname = "extended slice";
3304 if (ctx != AugStore) {
3305 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3306 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003307 slice_ty sub = (slice_ty)asdl_seq_GET(
3308 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003309 if (!compiler_visit_nested_slice(c, sub, ctx))
3310 return 0;
3311 }
3312 ADDOP_I(c, BUILD_TUPLE, n);
3313 }
3314 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003315 default:
3316 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003317 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003318 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003320 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321}
3322
3323/* do depth-first search of basic block graph, starting with block.
3324 post records the block indices in post-order.
3325
3326 XXX must handle implicit jumps from one block to next
3327*/
3328
3329static void
3330dfs(struct compiler *c, basicblock *b, struct assembler *a)
3331{
3332 int i;
3333 struct instr *instr = NULL;
3334
3335 if (b->b_seen)
3336 return;
3337 b->b_seen = 1;
3338 if (b->b_next != NULL)
3339 dfs(c, b->b_next, a);
3340 for (i = 0; i < b->b_iused; i++) {
3341 instr = &b->b_instr[i];
3342 if (instr->i_jrel || instr->i_jabs)
3343 dfs(c, instr->i_target, a);
3344 }
3345 a->a_postorder[a->a_nblocks++] = b;
3346}
3347
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003348static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3350{
3351 int i;
3352 struct instr *instr;
3353 if (b->b_seen || b->b_startdepth >= depth)
3354 return maxdepth;
3355 b->b_seen = 1;
3356 b->b_startdepth = depth;
3357 for (i = 0; i < b->b_iused; i++) {
3358 instr = &b->b_instr[i];
3359 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3360 if (depth > maxdepth)
3361 maxdepth = depth;
3362 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3363 if (instr->i_jrel || instr->i_jabs) {
3364 maxdepth = stackdepth_walk(c, instr->i_target,
3365 depth, maxdepth);
3366 if (instr->i_opcode == JUMP_ABSOLUTE ||
3367 instr->i_opcode == JUMP_FORWARD) {
3368 goto out; /* remaining code is dead */
3369 }
3370 }
3371 }
3372 if (b->b_next)
3373 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3374out:
3375 b->b_seen = 0;
3376 return maxdepth;
3377}
3378
3379/* Find the flow path that needs the largest stack. We assume that
3380 * cycles in the flow graph have no net effect on the stack depth.
3381 */
3382static int
3383stackdepth(struct compiler *c)
3384{
3385 basicblock *b, *entryblock;
3386 entryblock = NULL;
3387 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3388 b->b_seen = 0;
3389 b->b_startdepth = INT_MIN;
3390 entryblock = b;
3391 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003392 if (!entryblock)
3393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394 return stackdepth_walk(c, entryblock, 0, 0);
3395}
3396
3397static int
3398assemble_init(struct assembler *a, int nblocks, int firstlineno)
3399{
3400 memset(a, 0, sizeof(struct assembler));
3401 a->a_lineno = firstlineno;
3402 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3403 if (!a->a_bytecode)
3404 return 0;
3405 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3406 if (!a->a_lnotab)
3407 return 0;
3408 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003409 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003410 if (!a->a_postorder) {
3411 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003413 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414 return 1;
3415}
3416
3417static void
3418assemble_free(struct assembler *a)
3419{
3420 Py_XDECREF(a->a_bytecode);
3421 Py_XDECREF(a->a_lnotab);
3422 if (a->a_postorder)
3423 PyObject_Free(a->a_postorder);
3424}
3425
3426/* Return the size of a basic block in bytes. */
3427
3428static int
3429instrsize(struct instr *instr)
3430{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003431 if (!instr->i_hasarg)
3432 return 1;
3433 if (instr->i_oparg > 0xffff)
3434 return 6;
3435 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003436}
3437
3438static int
3439blocksize(basicblock *b)
3440{
3441 int i;
3442 int size = 0;
3443
3444 for (i = 0; i < b->b_iused; i++)
3445 size += instrsize(&b->b_instr[i]);
3446 return size;
3447}
3448
3449/* All about a_lnotab.
3450
3451c_lnotab is an array of unsigned bytes disguised as a Python string.
3452It is used to map bytecode offsets to source code line #s (when needed
3453for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003454
Tim Peters2a7f3842001-06-09 09:26:21 +00003455The array is conceptually a list of
3456 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003458
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 byte code offset source code line number
3460 0 1
3461 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003462 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 350 307
3464 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003465
3466The first trick is that these numbers aren't stored, only the increments
3467from one row to the next (this doesn't really work, but it's a start):
3468
3469 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3470
3471The second trick is that an unsigned byte can't hold negative values, or
3472values larger than 255, so (a) there's a deep assumption that byte code
3473offsets and their corresponding line #s both increase monotonically, and (b)
3474if at least one column jumps by more than 255 from one row to the next, more
3475than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003477part. A user of c_lnotab desiring to find the source line number
3478corresponding to a bytecode address A should do something like this
3479
3480 lineno = addr = 0
3481 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 addr += addr_incr
3483 if addr > A:
3484 return lineno
3485 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003486
3487In order for this to work, when the addr field increments by more than 255,
3488the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003489increment is < 256. So, in the example above, assemble_lnotab (it used
3490to be called com_set_lineno) should not (as was actually done until 2.2)
3491expand 300, 300 to 255, 255, 45, 45,
3492 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003493*/
3494
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003495static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003497{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 int d_bytecode, d_lineno;
3499 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003500 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501
3502 d_bytecode = a->a_offset - a->a_lineno_off;
3503 d_lineno = i->i_lineno - a->a_lineno;
3504
3505 assert(d_bytecode >= 0);
3506 assert(d_lineno >= 0);
3507
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003508 /* XXX(nnorwitz): is there a better way to handle this?
3509 for loops are special, we want to be able to trace them
3510 each time around, so we need to set an extra line number. */
3511 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003512 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003515 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003516 nbytes = a->a_lnotab_off + 2 * ncodes;
3517 len = PyString_GET_SIZE(a->a_lnotab);
3518 if (nbytes >= len) {
3519 if (len * 2 < nbytes)
3520 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003521 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522 len *= 2;
3523 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3524 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003525 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003526 lnotab = (unsigned char *)
3527 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003528 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 *lnotab++ = 255;
3530 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 d_bytecode -= ncodes * 255;
3533 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 assert(d_bytecode <= 255);
3536 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003537 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 nbytes = a->a_lnotab_off + 2 * ncodes;
3539 len = PyString_GET_SIZE(a->a_lnotab);
3540 if (nbytes >= len) {
3541 if (len * 2 < nbytes)
3542 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003543 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544 len *= 2;
3545 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3546 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003547 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003548 lnotab = (unsigned char *)
3549 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003551 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003553 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003555 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 d_lineno -= ncodes * 255;
3558 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003559 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 len = PyString_GET_SIZE(a->a_lnotab);
3562 if (a->a_lnotab_off + 2 >= len) {
3563 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003564 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003565 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003566 lnotab = (unsigned char *)
3567 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 a->a_lnotab_off += 2;
3570 if (d_bytecode) {
3571 *lnotab++ = d_bytecode;
3572 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003573 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003574 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 *lnotab++ = 0;
3576 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003577 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003578 a->a_lineno = i->i_lineno;
3579 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003580 return 1;
3581}
3582
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583/* assemble_emit()
3584 Extend the bytecode with a new instruction.
3585 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003586*/
3587
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003588static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003590{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003591 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003592 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 char *code;
3594
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003595 size = instrsize(i);
3596 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003598 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003601 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 if (a->a_offset + size >= len) {
3603 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003604 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003605 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3607 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003608 if (size == 6) {
3609 assert(i->i_hasarg);
3610 *code++ = (char)EXTENDED_ARG;
3611 *code++ = ext & 0xff;
3612 *code++ = ext >> 8;
3613 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003614 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003616 if (i->i_hasarg) {
3617 assert(size == 3 || size == 6);
3618 *code++ = arg & 0xff;
3619 *code++ = arg >> 8;
3620 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003622}
3623
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003624static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003626{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003628 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003629 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003630
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 /* Compute the size of each block and fixup jump args.
3632 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003633start:
3634 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003636 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 bsize = blocksize(b);
3638 b->b_offset = totsize;
3639 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003640 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003641 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3643 bsize = b->b_offset;
3644 for (i = 0; i < b->b_iused; i++) {
3645 struct instr *instr = &b->b_instr[i];
3646 /* Relative jumps are computed relative to
3647 the instruction pointer after fetching
3648 the jump instruction.
3649 */
3650 bsize += instrsize(instr);
3651 if (instr->i_jabs)
3652 instr->i_oparg = instr->i_target->b_offset;
3653 else if (instr->i_jrel) {
3654 int delta = instr->i_target->b_offset - bsize;
3655 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003656 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003657 else
3658 continue;
3659 if (instr->i_oparg > 0xffff)
3660 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003661 }
3662 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003663
3664 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003665 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003666 with a better solution.
3667
3668 In the meantime, should the goto be dropped in favor
3669 of a loop?
3670
3671 The issue is that in the first loop blocksize() is called
3672 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003673 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003674 i_oparg is calculated in the second loop above.
3675
3676 So we loop until we stop seeing new EXTENDED_ARGs.
3677 The only EXTENDED_ARGs that could be popping up are
3678 ones in jump instructions. So this should converge
3679 fairly quickly.
3680 */
3681 if (last_extended_arg_count != extended_arg_count) {
3682 last_extended_arg_count = extended_arg_count;
3683 goto start;
3684 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003685}
3686
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003687static PyObject *
3688dict_keys_inorder(PyObject *dict, int offset)
3689{
3690 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003691 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003692
3693 tuple = PyTuple_New(size);
3694 if (tuple == NULL)
3695 return NULL;
3696 while (PyDict_Next(dict, &pos, &k, &v)) {
3697 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003698 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003699 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003700 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003702 PyTuple_SET_ITEM(tuple, i - offset, k);
3703 }
3704 return tuple;
3705}
3706
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003707static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003709{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003710 PySTEntryObject *ste = c->u->u_ste;
3711 int flags = 0, n;
3712 if (ste->ste_type != ModuleBlock)
3713 flags |= CO_NEWLOCALS;
3714 if (ste->ste_type == FunctionBlock) {
3715 if (!ste->ste_unoptimized)
3716 flags |= CO_OPTIMIZED;
3717 if (ste->ste_nested)
3718 flags |= CO_NESTED;
3719 if (ste->ste_generator)
3720 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003721 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722 if (ste->ste_varargs)
3723 flags |= CO_VARARGS;
3724 if (ste->ste_varkeywords)
3725 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003726 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003728
3729 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003731
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003732 n = PyDict_Size(c->u->u_freevars);
3733 if (n < 0)
3734 return -1;
3735 if (n == 0) {
3736 n = PyDict_Size(c->u->u_cellvars);
3737 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003738 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739 if (n == 0) {
3740 flags |= CO_NOFREE;
3741 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003742 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003743
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003744 return flags;
3745}
3746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747static PyCodeObject *
3748makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003749{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 PyObject *tmp;
3751 PyCodeObject *co = NULL;
3752 PyObject *consts = NULL;
3753 PyObject *names = NULL;
3754 PyObject *varnames = NULL;
3755 PyObject *filename = NULL;
3756 PyObject *name = NULL;
3757 PyObject *freevars = NULL;
3758 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003759 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003761
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 tmp = dict_keys_inorder(c->u->u_consts, 0);
3763 if (!tmp)
3764 goto error;
3765 consts = PySequence_List(tmp); /* optimize_code requires a list */
3766 Py_DECREF(tmp);
3767
3768 names = dict_keys_inorder(c->u->u_names, 0);
3769 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3770 if (!consts || !names || !varnames)
3771 goto error;
3772
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3774 if (!cellvars)
3775 goto error;
3776 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3777 if (!freevars)
3778 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 filename = PyString_FromString(c->c_filename);
3780 if (!filename)
3781 goto error;
3782
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003783 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784 flags = compute_code_flags(c);
3785 if (flags < 0)
3786 goto error;
3787
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003788 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003789 if (!bytecode)
3790 goto error;
3791
3792 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3793 if (!tmp)
3794 goto error;
3795 Py_DECREF(consts);
3796 consts = tmp;
3797
3798 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3799 bytecode, consts, names, varnames,
3800 freevars, cellvars,
3801 filename, c->u->u_name,
3802 c->u->u_firstlineno,
3803 a->a_lnotab);
3804 error:
3805 Py_XDECREF(consts);
3806 Py_XDECREF(names);
3807 Py_XDECREF(varnames);
3808 Py_XDECREF(filename);
3809 Py_XDECREF(name);
3810 Py_XDECREF(freevars);
3811 Py_XDECREF(cellvars);
3812 Py_XDECREF(bytecode);
3813 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003814}
3815
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003816
3817/* For debugging purposes only */
3818#if 0
3819static void
3820dump_instr(const struct instr *i)
3821{
3822 const char *jrel = i->i_jrel ? "jrel " : "";
3823 const char *jabs = i->i_jabs ? "jabs " : "";
3824 char arg[128];
3825
3826 *arg = '\0';
3827 if (i->i_hasarg)
3828 sprintf(arg, "arg: %d ", i->i_oparg);
3829
3830 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3831 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3832}
3833
3834static void
3835dump_basicblock(const basicblock *b)
3836{
3837 const char *seen = b->b_seen ? "seen " : "";
3838 const char *b_return = b->b_return ? "return " : "";
3839 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3840 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3841 if (b->b_instr) {
3842 int i;
3843 for (i = 0; i < b->b_iused; i++) {
3844 fprintf(stderr, " [%02d] ", i);
3845 dump_instr(b->b_instr + i);
3846 }
3847 }
3848}
3849#endif
3850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851static PyCodeObject *
3852assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003853{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 basicblock *b, *entryblock;
3855 struct assembler a;
3856 int i, j, nblocks;
3857 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003858
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 /* Make sure every block that falls off the end returns None.
3860 XXX NEXT_BLOCK() isn't quite right, because if the last
3861 block ends with a jump or return b_next shouldn't set.
3862 */
3863 if (!c->u->u_curblock->b_return) {
3864 NEXT_BLOCK(c);
3865 if (addNone)
3866 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3867 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003868 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 nblocks = 0;
3871 entryblock = NULL;
3872 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3873 nblocks++;
3874 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003875 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003876
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003877 /* Set firstlineno if it wasn't explicitly set. */
3878 if (!c->u->u_firstlineno) {
3879 if (entryblock && entryblock->b_instr)
3880 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3881 else
3882 c->u->u_firstlineno = 1;
3883 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3885 goto error;
3886 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003889 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003890
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 /* Emit code in reverse postorder from dfs. */
3892 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003893 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 for (j = 0; j < b->b_iused; j++)
3895 if (!assemble_emit(&a, &b->b_instr[j]))
3896 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003897 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3900 goto error;
3901 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3902 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904 co = makecode(c, &a);
3905 error:
3906 assemble_free(&a);
3907 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003908}