blob: 4601f2ca7ede51d458ab91e4ac64057b2ae6a014 [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;
817 case EXEC_STMT:
818 return -3;
819 case YIELD_VALUE:
820 return 0;
821
822 case POP_BLOCK:
823 return 0;
824 case END_FINALLY:
825 return -1; /* or -2 or -3 if exception occurred */
826 case BUILD_CLASS:
827 return -2;
828
829 case STORE_NAME:
830 return -1;
831 case DELETE_NAME:
832 return 0;
833 case UNPACK_SEQUENCE:
834 return oparg-1;
835 case FOR_ITER:
836 return 1;
837
838 case STORE_ATTR:
839 return -2;
840 case DELETE_ATTR:
841 return -1;
842 case STORE_GLOBAL:
843 return -1;
844 case DELETE_GLOBAL:
845 return 0;
846 case DUP_TOPX:
847 return oparg;
848 case LOAD_CONST:
849 return 1;
850 case LOAD_NAME:
851 return 1;
852 case BUILD_TUPLE:
853 case BUILD_LIST:
854 return 1-oparg;
855 case BUILD_MAP:
856 return 1;
857 case LOAD_ATTR:
858 return 0;
859 case COMPARE_OP:
860 return -1;
861 case IMPORT_NAME:
862 return 0;
863 case IMPORT_FROM:
864 return 1;
865
866 case JUMP_FORWARD:
867 case JUMP_IF_FALSE:
868 case JUMP_IF_TRUE:
869 case JUMP_ABSOLUTE:
870 return 0;
871
872 case LOAD_GLOBAL:
873 return 1;
874
875 case CONTINUE_LOOP:
876 return 0;
877 case SETUP_LOOP:
878 return 0;
879 case SETUP_EXCEPT:
880 case SETUP_FINALLY:
881 return 3; /* actually pushed by an exception */
882
883 case LOAD_FAST:
884 return 1;
885 case STORE_FAST:
886 return -1;
887 case DELETE_FAST:
888 return 0;
889
890 case RAISE_VARARGS:
891 return -oparg;
892#define NARGS(o) (((o) % 256) + 2*((o) / 256))
893 case CALL_FUNCTION:
894 return -NARGS(oparg);
895 case CALL_FUNCTION_VAR:
896 case CALL_FUNCTION_KW:
897 return -NARGS(oparg)-1;
898 case CALL_FUNCTION_VAR_KW:
899 return -NARGS(oparg)-2;
900#undef NARGS
901 case MAKE_FUNCTION:
902 return -oparg;
903 case BUILD_SLICE:
904 if (oparg == 3)
905 return -2;
906 else
907 return -1;
908
909 case MAKE_CLOSURE:
910 return -oparg;
911 case LOAD_CLOSURE:
912 return 1;
913 case LOAD_DEREF:
914 return 1;
915 case STORE_DEREF:
916 return -1;
917 default:
918 fprintf(stderr, "opcode = %d\n", opcode);
919 Py_FatalError("opcode_stack_effect()");
920
921 }
922 return 0; /* not reachable */
923}
924
925/* Add an opcode with no argument.
926 Returns 0 on failure, 1 on success.
927*/
928
929static int
930compiler_addop(struct compiler *c, int opcode)
931{
932 basicblock *b;
933 struct instr *i;
934 int off;
935 off = compiler_next_instr(c, c->u->u_curblock);
936 if (off < 0)
937 return 0;
938 b = c->u->u_curblock;
939 i = &b->b_instr[off];
940 i->i_opcode = opcode;
941 i->i_hasarg = 0;
942 if (opcode == RETURN_VALUE)
943 b->b_return = 1;
944 compiler_set_lineno(c, off);
945 return 1;
946}
947
948static int
949compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
950{
951 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000952 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000954 /* necessary to make sure types aren't coerced (e.g., int and long) */
955 t = PyTuple_Pack(2, o, o->ob_type);
956 if (t == NULL)
957 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000958
959 v = PyDict_GetItem(dict, t);
960 if (!v) {
Jeremy Hyltonfbfe0932006-08-23 18:13:39 +0000961 if (PyErr_Occurred())
962 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963 arg = PyDict_Size(dict);
964 v = PyInt_FromLong(arg);
965 if (!v) {
966 Py_DECREF(t);
967 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000968 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969 if (PyDict_SetItem(dict, t, v) < 0) {
970 Py_DECREF(t);
971 Py_DECREF(v);
972 return -1;
973 }
974 Py_DECREF(v);
975 }
976 else
977 arg = PyInt_AsLong(v);
978 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000979 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980}
981
982static int
983compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
984 PyObject *o)
985{
986 int arg = compiler_add_o(c, dict, o);
987 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000988 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return compiler_addop_i(c, opcode, arg);
990}
991
992static int
993compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000994 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995{
996 int arg;
997 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
998 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000999 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000 arg = compiler_add_o(c, dict, mangled);
1001 Py_DECREF(mangled);
1002 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004 return compiler_addop_i(c, opcode, arg);
1005}
1006
1007/* Add an opcode with an integer argument.
1008 Returns 0 on failure, 1 on success.
1009*/
1010
1011static int
1012compiler_addop_i(struct compiler *c, int opcode, int oparg)
1013{
1014 struct instr *i;
1015 int off;
1016 off = compiler_next_instr(c, c->u->u_curblock);
1017 if (off < 0)
1018 return 0;
1019 i = &c->u->u_curblock->b_instr[off];
1020 i->i_opcode = opcode;
1021 i->i_oparg = oparg;
1022 i->i_hasarg = 1;
1023 compiler_set_lineno(c, off);
1024 return 1;
1025}
1026
1027static int
1028compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1029{
1030 struct instr *i;
1031 int off;
1032
1033 assert(b != NULL);
1034 off = compiler_next_instr(c, c->u->u_curblock);
1035 if (off < 0)
1036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001037 i = &c->u->u_curblock->b_instr[off];
1038 i->i_opcode = opcode;
1039 i->i_target = b;
1040 i->i_hasarg = 1;
1041 if (absolute)
1042 i->i_jabs = 1;
1043 else
1044 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001045 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046 return 1;
1047}
1048
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001049/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1050 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051 it as the current block. NEXT_BLOCK() also creates an implicit jump
1052 from the current block to the new block.
1053*/
1054
1055/* XXX The returns inside these macros make it impossible to decref
1056 objects created in the local function.
1057*/
1058
1059
1060#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001061 if (compiler_use_new_block((C)) == NULL) \
1062 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063}
1064
1065#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001066 if (compiler_next_block((C)) == NULL) \
1067 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068}
1069
1070#define ADDOP(C, OP) { \
1071 if (!compiler_addop((C), (OP))) \
1072 return 0; \
1073}
1074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001075#define ADDOP_IN_SCOPE(C, OP) { \
1076 if (!compiler_addop((C), (OP))) { \
1077 compiler_exit_scope(c); \
1078 return 0; \
1079 } \
1080}
1081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082#define ADDOP_O(C, OP, O, TYPE) { \
1083 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1084 return 0; \
1085}
1086
1087#define ADDOP_NAME(C, OP, O, TYPE) { \
1088 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1089 return 0; \
1090}
1091
1092#define ADDOP_I(C, OP, O) { \
1093 if (!compiler_addop_i((C), (OP), (O))) \
1094 return 0; \
1095}
1096
1097#define ADDOP_JABS(C, OP, O) { \
1098 if (!compiler_addop_j((C), (OP), (O), 1)) \
1099 return 0; \
1100}
1101
1102#define ADDOP_JREL(C, OP, O) { \
1103 if (!compiler_addop_j((C), (OP), (O), 0)) \
1104 return 0; \
1105}
1106
1107/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1108 the ASDL name to synthesize the name of the C type and the visit function.
1109*/
1110
1111#define VISIT(C, TYPE, V) {\
1112 if (!compiler_visit_ ## TYPE((C), (V))) \
1113 return 0; \
1114}
1115
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001116#define VISIT_IN_SCOPE(C, TYPE, V) {\
1117 if (!compiler_visit_ ## TYPE((C), (V))) { \
1118 compiler_exit_scope(c); \
1119 return 0; \
1120 } \
1121}
1122
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123#define VISIT_SLICE(C, V, CTX) {\
1124 if (!compiler_visit_slice((C), (V), (CTX))) \
1125 return 0; \
1126}
1127
1128#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001129 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001131 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001132 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 if (!compiler_visit_ ## TYPE((C), elt)) \
1134 return 0; \
1135 } \
1136}
1137
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001138#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001139 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001140 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001141 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001143 if (!compiler_visit_ ## TYPE((C), elt)) { \
1144 compiler_exit_scope(c); \
1145 return 0; \
1146 } \
1147 } \
1148}
1149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150static int
1151compiler_isdocstring(stmt_ty s)
1152{
1153 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001154 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return s->v.Expr.value->kind == Str_kind;
1156}
1157
1158/* Compile a sequence of statements, checking for a docstring. */
1159
1160static int
1161compiler_body(struct compiler *c, asdl_seq *stmts)
1162{
1163 int i = 0;
1164 stmt_ty st;
1165
1166 if (!asdl_seq_LEN(stmts))
1167 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169 if (compiler_isdocstring(st)) {
1170 i = 1;
1171 VISIT(c, expr, st->v.Expr.value);
1172 if (!compiler_nameop(c, __doc__, Store))
1173 return 0;
1174 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001175 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177 return 1;
1178}
1179
1180static PyCodeObject *
1181compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001182{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001184 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 static PyObject *module;
1186 if (!module) {
1187 module = PyString_FromString("<module>");
1188 if (!module)
1189 return NULL;
1190 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001191 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1192 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001193 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 switch (mod->kind) {
1195 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001196 if (!compiler_body(c, mod->v.Module.body)) {
1197 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200 break;
1201 case Interactive_kind:
1202 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 VISIT_SEQ_IN_SCOPE(c, stmt,
1204 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205 break;
1206 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001207 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001208 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 break;
1210 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001211 PyErr_SetString(PyExc_SystemError,
1212 "suite should not be possible");
1213 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001214 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001215 PyErr_Format(PyExc_SystemError,
1216 "module kind %d should not be possible",
1217 mod->kind);
1218 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 co = assemble(c, addNone);
1221 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001222 return co;
1223}
1224
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001225/* The test for LOCAL must come before the test for FREE in order to
1226 handle classes where name is both local and free. The local var is
1227 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001228*/
1229
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230static int
1231get_ref_type(struct compiler *c, PyObject *name)
1232{
1233 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001234 if (scope == 0) {
1235 char buf[350];
1236 PyOS_snprintf(buf, sizeof(buf),
1237 "unknown scope for %.100s in %.100s(%s) in %s\n"
1238 "symbols: %s\nlocals: %s\nglobals: %s\n",
1239 PyString_AS_STRING(name),
1240 PyString_AS_STRING(c->u->u_name),
1241 PyObject_REPR(c->u->u_ste->ste_id),
1242 c->c_filename,
1243 PyObject_REPR(c->u->u_ste->ste_symbols),
1244 PyObject_REPR(c->u->u_varnames),
1245 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 Py_FatalError(buf);
1248 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001249
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251}
1252
1253static int
1254compiler_lookup_arg(PyObject *dict, PyObject *name)
1255{
1256 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001259 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001261 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001262 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001263 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 return PyInt_AS_LONG(v);
1265}
1266
1267static int
1268compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1269{
1270 int i, free = PyCode_GetNumFree(co);
1271 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1273 ADDOP_I(c, MAKE_FUNCTION, args);
1274 return 1;
1275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001276 for (i = 0; i < free; ++i) {
1277 /* Bypass com_addop_varname because it will generate
1278 LOAD_DEREF but LOAD_CLOSURE is needed.
1279 */
1280 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1281 int arg, reftype;
1282
1283 /* Special case: If a class contains a method with a
1284 free variable that has the same name as a method,
1285 the name will be considered free *and* local in the
1286 class. It should be handled by the closure, as
1287 well as by the normal name loookup logic.
1288 */
1289 reftype = get_ref_type(c, name);
1290 if (reftype == CELL)
1291 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1292 else /* (reftype == FREE) */
1293 arg = compiler_lookup_arg(c->u->u_freevars, name);
1294 if (arg == -1) {
1295 printf("lookup %s in %s %d %d\n"
1296 "freevars of %s: %s\n",
1297 PyObject_REPR(name),
1298 PyString_AS_STRING(c->u->u_name),
1299 reftype, arg,
1300 PyString_AS_STRING(co->co_name),
1301 PyObject_REPR(co->co_freevars));
1302 Py_FatalError("compiler_make_closure()");
1303 }
1304 ADDOP_I(c, LOAD_CLOSURE, arg);
1305 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001306 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001307 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001308 ADDOP_I(c, MAKE_CLOSURE, args);
1309 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001310}
1311
1312static int
1313compiler_decorators(struct compiler *c, asdl_seq* decos)
1314{
1315 int i;
1316
1317 if (!decos)
1318 return 1;
1319
1320 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001321 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322 }
1323 return 1;
1324}
1325
1326static int
1327compiler_arguments(struct compiler *c, arguments_ty args)
1328{
1329 int i;
1330 int n = asdl_seq_LEN(args->args);
1331 /* Correctly handle nested argument lists */
1332 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001333 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 if (arg->kind == Tuple_kind) {
1335 PyObject *id = PyString_FromFormat(".%d", i);
1336 if (id == NULL) {
1337 return 0;
1338 }
1339 if (!compiler_nameop(c, id, Load)) {
1340 Py_DECREF(id);
1341 return 0;
1342 }
1343 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001344 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345 }
1346 }
1347 return 1;
1348}
1349
1350static int
1351compiler_function(struct compiler *c, stmt_ty s)
1352{
1353 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001354 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 arguments_ty args = s->v.FunctionDef.args;
1356 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001357 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001358 int i, n, docstring;
1359
1360 assert(s->kind == FunctionDef_kind);
1361
1362 if (!compiler_decorators(c, decos))
1363 return 0;
1364 if (args->defaults)
1365 VISIT_SEQ(c, expr, args->defaults);
1366 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1367 s->lineno))
1368 return 0;
1369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001371 docstring = compiler_isdocstring(st);
1372 if (docstring)
1373 first_const = st->v.Expr.value->v.Str.s;
1374 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001375 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001376 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001377 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001379 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 compiler_arguments(c, args);
1381
1382 c->u->u_argcount = asdl_seq_LEN(args->args);
1383 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001384 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001386 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1387 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 }
1389 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001390 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 if (co == NULL)
1392 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001393
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001394 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001395 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001396
1397 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1398 ADDOP_I(c, CALL_FUNCTION, 1);
1399 }
1400
1401 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1402}
1403
1404static int
1405compiler_class(struct compiler *c, stmt_ty s)
1406{
1407 int n;
1408 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001409 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410 /* push class name on stack, needed by BUILD_CLASS */
1411 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1412 /* push the tuple of base classes on the stack */
1413 n = asdl_seq_LEN(s->v.ClassDef.bases);
1414 if (n > 0)
1415 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1416 ADDOP_I(c, BUILD_TUPLE, n);
1417 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1418 s->lineno))
1419 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001420 c->u->u_private = s->v.ClassDef.name;
1421 Py_INCREF(c->u->u_private);
1422 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423 if (!str || !compiler_nameop(c, str, Load)) {
1424 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001425 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001426 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001427 }
1428
1429 Py_DECREF(str);
1430 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 if (!str || !compiler_nameop(c, str, Store)) {
1432 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001433 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001435 }
1436 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001438 if (!compiler_body(c, s->v.ClassDef.body)) {
1439 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001441 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001443 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1444 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001445 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001446 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 if (co == NULL)
1448 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001450 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001451 Py_DECREF(co);
1452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 ADDOP_I(c, CALL_FUNCTION, 0);
1454 ADDOP(c, BUILD_CLASS);
1455 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1456 return 0;
1457 return 1;
1458}
1459
1460static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001461compiler_ifexp(struct compiler *c, expr_ty e)
1462{
1463 basicblock *end, *next;
1464
1465 assert(e->kind == IfExp_kind);
1466 end = compiler_new_block(c);
1467 if (end == NULL)
1468 return 0;
1469 next = compiler_new_block(c);
1470 if (next == NULL)
1471 return 0;
1472 VISIT(c, expr, e->v.IfExp.test);
1473 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1474 ADDOP(c, POP_TOP);
1475 VISIT(c, expr, e->v.IfExp.body);
1476 ADDOP_JREL(c, JUMP_FORWARD, end);
1477 compiler_use_next_block(c, next);
1478 ADDOP(c, POP_TOP);
1479 VISIT(c, expr, e->v.IfExp.orelse);
1480 compiler_use_next_block(c, end);
1481 return 1;
1482}
1483
1484static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001485compiler_lambda(struct compiler *c, expr_ty e)
1486{
1487 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001488 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001489 arguments_ty args = e->v.Lambda.args;
1490 assert(e->kind == Lambda_kind);
1491
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001492 if (!name) {
1493 name = PyString_InternFromString("<lambda>");
1494 if (!name)
1495 return 0;
1496 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497
1498 if (args->defaults)
1499 VISIT_SEQ(c, expr, args->defaults);
1500 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1501 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001502
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001503 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001504 compiler_arguments(c, args);
1505
1506 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001507 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1508 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001510 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511 if (co == NULL)
1512 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001513
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001514 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001515 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516
1517 return 1;
1518}
1519
1520static int
1521compiler_print(struct compiler *c, stmt_ty s)
1522{
1523 int i, n;
1524 bool dest;
1525
1526 assert(s->kind == Print_kind);
1527 n = asdl_seq_LEN(s->v.Print.values);
1528 dest = false;
1529 if (s->v.Print.dest) {
1530 VISIT(c, expr, s->v.Print.dest);
1531 dest = true;
1532 }
1533 for (i = 0; i < n; i++) {
1534 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1535 if (dest) {
1536 ADDOP(c, DUP_TOP);
1537 VISIT(c, expr, e);
1538 ADDOP(c, ROT_TWO);
1539 ADDOP(c, PRINT_ITEM_TO);
1540 }
1541 else {
1542 VISIT(c, expr, e);
1543 ADDOP(c, PRINT_ITEM);
1544 }
1545 }
1546 if (s->v.Print.nl) {
1547 if (dest)
1548 ADDOP(c, PRINT_NEWLINE_TO)
1549 else
1550 ADDOP(c, PRINT_NEWLINE)
1551 }
1552 else if (dest)
1553 ADDOP(c, POP_TOP);
1554 return 1;
1555}
1556
1557static int
1558compiler_if(struct compiler *c, stmt_ty s)
1559{
1560 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001561 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562 assert(s->kind == If_kind);
1563 end = compiler_new_block(c);
1564 if (end == NULL)
1565 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001566 next = compiler_new_block(c);
1567 if (next == NULL)
1568 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001569
1570 constant = expr_constant(s->v.If.test);
1571 /* constant = 0: "if 0"
1572 * constant = 1: "if 1", "if 2", ...
1573 * constant = -1: rest */
1574 if (constant == 0) {
1575 if (s->v.If.orelse)
1576 VISIT_SEQ(c, stmt, s->v.If.orelse);
1577 } else if (constant == 1) {
1578 VISIT_SEQ(c, stmt, s->v.If.body);
1579 } else {
1580 VISIT(c, expr, s->v.If.test);
1581 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1582 ADDOP(c, POP_TOP);
1583 VISIT_SEQ(c, stmt, s->v.If.body);
1584 ADDOP_JREL(c, JUMP_FORWARD, end);
1585 compiler_use_next_block(c, next);
1586 ADDOP(c, POP_TOP);
1587 if (s->v.If.orelse)
1588 VISIT_SEQ(c, stmt, s->v.If.orelse);
1589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001590 compiler_use_next_block(c, end);
1591 return 1;
1592}
1593
1594static int
1595compiler_for(struct compiler *c, stmt_ty s)
1596{
1597 basicblock *start, *cleanup, *end;
1598
1599 start = compiler_new_block(c);
1600 cleanup = compiler_new_block(c);
1601 end = compiler_new_block(c);
1602 if (start == NULL || end == NULL || cleanup == NULL)
1603 return 0;
1604 ADDOP_JREL(c, SETUP_LOOP, end);
1605 if (!compiler_push_fblock(c, LOOP, start))
1606 return 0;
1607 VISIT(c, expr, s->v.For.iter);
1608 ADDOP(c, GET_ITER);
1609 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001610 /* XXX(nnorwitz): is there a better way to handle this?
1611 for loops are special, we want to be able to trace them
1612 each time around, so we need to set an extra line number. */
1613 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001614 ADDOP_JREL(c, FOR_ITER, cleanup);
1615 VISIT(c, expr, s->v.For.target);
1616 VISIT_SEQ(c, stmt, s->v.For.body);
1617 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1618 compiler_use_next_block(c, cleanup);
1619 ADDOP(c, POP_BLOCK);
1620 compiler_pop_fblock(c, LOOP, start);
1621 VISIT_SEQ(c, stmt, s->v.For.orelse);
1622 compiler_use_next_block(c, end);
1623 return 1;
1624}
1625
1626static int
1627compiler_while(struct compiler *c, stmt_ty s)
1628{
1629 basicblock *loop, *orelse, *end, *anchor = NULL;
1630 int constant = expr_constant(s->v.While.test);
1631
1632 if (constant == 0)
1633 return 1;
1634 loop = compiler_new_block(c);
1635 end = compiler_new_block(c);
1636 if (constant == -1) {
1637 anchor = compiler_new_block(c);
1638 if (anchor == NULL)
1639 return 0;
1640 }
1641 if (loop == NULL || end == NULL)
1642 return 0;
1643 if (s->v.While.orelse) {
1644 orelse = compiler_new_block(c);
1645 if (orelse == NULL)
1646 return 0;
1647 }
1648 else
1649 orelse = NULL;
1650
1651 ADDOP_JREL(c, SETUP_LOOP, end);
1652 compiler_use_next_block(c, loop);
1653 if (!compiler_push_fblock(c, LOOP, loop))
1654 return 0;
1655 if (constant == -1) {
1656 VISIT(c, expr, s->v.While.test);
1657 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1658 ADDOP(c, POP_TOP);
1659 }
1660 VISIT_SEQ(c, stmt, s->v.While.body);
1661 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1662
1663 /* XXX should the two POP instructions be in a separate block
1664 if there is no else clause ?
1665 */
1666
1667 if (constant == -1) {
1668 compiler_use_next_block(c, anchor);
1669 ADDOP(c, POP_TOP);
1670 ADDOP(c, POP_BLOCK);
1671 }
1672 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001673 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674 VISIT_SEQ(c, stmt, s->v.While.orelse);
1675 compiler_use_next_block(c, end);
1676
1677 return 1;
1678}
1679
1680static int
1681compiler_continue(struct compiler *c)
1682{
1683 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1684 int i;
1685
1686 if (!c->u->u_nfblocks)
1687 return compiler_error(c, LOOP_ERROR_MSG);
1688 i = c->u->u_nfblocks - 1;
1689 switch (c->u->u_fblock[i].fb_type) {
1690 case LOOP:
1691 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1692 break;
1693 case EXCEPT:
1694 case FINALLY_TRY:
1695 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1696 ;
1697 if (i == -1)
1698 return compiler_error(c, LOOP_ERROR_MSG);
1699 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1700 break;
1701 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001702 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 "'continue' not supported inside 'finally' clause");
1704 }
1705
1706 return 1;
1707}
1708
1709/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1710
1711 SETUP_FINALLY L
1712 <code for body>
1713 POP_BLOCK
1714 LOAD_CONST <None>
1715 L: <code for finalbody>
1716 END_FINALLY
1717
1718 The special instructions use the block stack. Each block
1719 stack entry contains the instruction that created it (here
1720 SETUP_FINALLY), the level of the value stack at the time the
1721 block stack entry was created, and a label (here L).
1722
1723 SETUP_FINALLY:
1724 Pushes the current value stack level and the label
1725 onto the block stack.
1726 POP_BLOCK:
1727 Pops en entry from the block stack, and pops the value
1728 stack until its level is the same as indicated on the
1729 block stack. (The label is ignored.)
1730 END_FINALLY:
1731 Pops a variable number of entries from the *value* stack
1732 and re-raises the exception they specify. The number of
1733 entries popped depends on the (pseudo) exception type.
1734
1735 The block stack is unwound when an exception is raised:
1736 when a SETUP_FINALLY entry is found, the exception is pushed
1737 onto the value stack (and the exception condition is cleared),
1738 and the interpreter jumps to the label gotten from the block
1739 stack.
1740*/
1741
1742static int
1743compiler_try_finally(struct compiler *c, stmt_ty s)
1744{
1745 basicblock *body, *end;
1746 body = compiler_new_block(c);
1747 end = compiler_new_block(c);
1748 if (body == NULL || end == NULL)
1749 return 0;
1750
1751 ADDOP_JREL(c, SETUP_FINALLY, end);
1752 compiler_use_next_block(c, body);
1753 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1754 return 0;
1755 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1756 ADDOP(c, POP_BLOCK);
1757 compiler_pop_fblock(c, FINALLY_TRY, body);
1758
1759 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1760 compiler_use_next_block(c, end);
1761 if (!compiler_push_fblock(c, FINALLY_END, end))
1762 return 0;
1763 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1764 ADDOP(c, END_FINALLY);
1765 compiler_pop_fblock(c, FINALLY_END, end);
1766
1767 return 1;
1768}
1769
1770/*
1771 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1772 (The contents of the value stack is shown in [], with the top
1773 at the right; 'tb' is trace-back info, 'val' the exception's
1774 associated value, and 'exc' the exception.)
1775
1776 Value stack Label Instruction Argument
1777 [] SETUP_EXCEPT L1
1778 [] <code for S>
1779 [] POP_BLOCK
1780 [] JUMP_FORWARD L0
1781
1782 [tb, val, exc] L1: DUP )
1783 [tb, val, exc, exc] <evaluate E1> )
1784 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1785 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1786 [tb, val, exc, 1] POP )
1787 [tb, val, exc] POP
1788 [tb, val] <assign to V1> (or POP if no V1)
1789 [tb] POP
1790 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001791 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792
1793 [tb, val, exc, 0] L2: POP
1794 [tb, val, exc] DUP
1795 .............................etc.......................
1796
1797 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001798 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799
1800 [] L0: <next statement>
1801
1802 Of course, parts are not generated if Vi or Ei is not present.
1803*/
1804static int
1805compiler_try_except(struct compiler *c, stmt_ty s)
1806{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001807 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 int i, n;
1809
1810 body = compiler_new_block(c);
1811 except = compiler_new_block(c);
1812 orelse = compiler_new_block(c);
1813 end = compiler_new_block(c);
1814 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1815 return 0;
1816 ADDOP_JREL(c, SETUP_EXCEPT, except);
1817 compiler_use_next_block(c, body);
1818 if (!compiler_push_fblock(c, EXCEPT, body))
1819 return 0;
1820 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1821 ADDOP(c, POP_BLOCK);
1822 compiler_pop_fblock(c, EXCEPT, body);
1823 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1824 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1825 compiler_use_next_block(c, except);
1826 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001827 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 s->v.TryExcept.handlers, i);
1829 if (!handler->type && i < n-1)
1830 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001831 c->u->u_lineno_set = false;
1832 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 except = compiler_new_block(c);
1834 if (except == NULL)
1835 return 0;
1836 if (handler->type) {
1837 ADDOP(c, DUP_TOP);
1838 VISIT(c, expr, handler->type);
1839 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1840 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1841 ADDOP(c, POP_TOP);
1842 }
1843 ADDOP(c, POP_TOP);
1844 if (handler->name) {
1845 VISIT(c, expr, handler->name);
1846 }
1847 else {
1848 ADDOP(c, POP_TOP);
1849 }
1850 ADDOP(c, POP_TOP);
1851 VISIT_SEQ(c, stmt, handler->body);
1852 ADDOP_JREL(c, JUMP_FORWARD, end);
1853 compiler_use_next_block(c, except);
1854 if (handler->type)
1855 ADDOP(c, POP_TOP);
1856 }
1857 ADDOP(c, END_FINALLY);
1858 compiler_use_next_block(c, orelse);
1859 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1860 compiler_use_next_block(c, end);
1861 return 1;
1862}
1863
1864static int
1865compiler_import_as(struct compiler *c, identifier name, identifier asname)
1866{
1867 /* The IMPORT_NAME opcode was already generated. This function
1868 merely needs to bind the result to a name.
1869
1870 If there is a dot in name, we need to split it and emit a
1871 LOAD_ATTR for each name.
1872 */
1873 const char *src = PyString_AS_STRING(name);
1874 const char *dot = strchr(src, '.');
1875 if (dot) {
1876 /* Consume the base module name to get the first attribute */
1877 src = dot + 1;
1878 while (dot) {
1879 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001880 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001882 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001884 if (!attr)
1885 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001887 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888 src = dot + 1;
1889 }
1890 }
1891 return compiler_nameop(c, asname, Store);
1892}
1893
1894static int
1895compiler_import(struct compiler *c, stmt_ty s)
1896{
1897 /* The Import node stores a module name like a.b.c as a single
1898 string. This is convenient for all cases except
1899 import a.b.c as d
1900 where we need to parse that string to extract the individual
1901 module names.
1902 XXX Perhaps change the representation to make this case simpler?
1903 */
1904 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001907 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001909 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
Guido van Rossum45aecf42006-03-15 04:58:47 +00001911 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001912 if (level == NULL)
1913 return 0;
1914
1915 ADDOP_O(c, LOAD_CONST, level, consts);
1916 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1918 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1919
1920 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001921 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001922 if (!r)
1923 return r;
1924 }
1925 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 identifier tmp = alias->name;
1927 const char *base = PyString_AS_STRING(alias->name);
1928 char *dot = strchr(base, '.');
1929 if (dot)
1930 tmp = PyString_FromStringAndSize(base,
1931 dot - base);
1932 r = compiler_nameop(c, tmp, Store);
1933 if (dot) {
1934 Py_DECREF(tmp);
1935 }
1936 if (!r)
1937 return r;
1938 }
1939 }
1940 return 1;
1941}
1942
1943static int
1944compiler_from_import(struct compiler *c, stmt_ty s)
1945{
1946 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947
1948 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001949 PyObject *level;
1950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 if (!names)
1952 return 0;
1953
Guido van Rossum45aecf42006-03-15 04:58:47 +00001954 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001955 if (!level) {
1956 Py_DECREF(names);
1957 return 0;
1958 }
1959
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 /* build up the names */
1961 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001962 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 Py_INCREF(alias->name);
1964 PyTuple_SET_ITEM(names, i, alias->name);
1965 }
1966
1967 if (s->lineno > c->c_future->ff_lineno) {
1968 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1969 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001970 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 Py_DECREF(names);
1972 return compiler_error(c,
1973 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001974 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
1976 }
1977 }
1978
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001979 ADDOP_O(c, LOAD_CONST, level, consts);
1980 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001982 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001983 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1984 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001985 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 identifier store_name;
1987
1988 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1989 assert(n == 1);
1990 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001991 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 }
1993
1994 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1995 store_name = alias->name;
1996 if (alias->asname)
1997 store_name = alias->asname;
1998
1999 if (!compiler_nameop(c, store_name, Store)) {
2000 Py_DECREF(names);
2001 return 0;
2002 }
2003 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002004 /* remove imported module */
2005 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006 return 1;
2007}
2008
2009static int
2010compiler_assert(struct compiler *c, stmt_ty s)
2011{
2012 static PyObject *assertion_error = NULL;
2013 basicblock *end;
2014
2015 if (Py_OptimizeFlag)
2016 return 1;
2017 if (assertion_error == NULL) {
2018 assertion_error = PyString_FromString("AssertionError");
2019 if (assertion_error == NULL)
2020 return 0;
2021 }
2022 VISIT(c, expr, s->v.Assert.test);
2023 end = compiler_new_block(c);
2024 if (end == NULL)
2025 return 0;
2026 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2027 ADDOP(c, POP_TOP);
2028 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2029 if (s->v.Assert.msg) {
2030 VISIT(c, expr, s->v.Assert.msg);
2031 ADDOP_I(c, RAISE_VARARGS, 2);
2032 }
2033 else {
2034 ADDOP_I(c, RAISE_VARARGS, 1);
2035 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002036 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037 ADDOP(c, POP_TOP);
2038 return 1;
2039}
2040
2041static int
2042compiler_visit_stmt(struct compiler *c, stmt_ty s)
2043{
2044 int i, n;
2045
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002046 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 c->u->u_lineno = s->lineno;
2048 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002050 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002051 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002053 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002055 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 if (c->u->u_ste->ste_type != FunctionBlock)
2057 return compiler_error(c, "'return' outside function");
2058 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059 VISIT(c, expr, s->v.Return.value);
2060 }
2061 else
2062 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2063 ADDOP(c, RETURN_VALUE);
2064 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 VISIT_SEQ(c, expr, s->v.Delete.targets)
2067 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002068 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069 n = asdl_seq_LEN(s->v.Assign.targets);
2070 VISIT(c, expr, s->v.Assign.value);
2071 for (i = 0; i < n; i++) {
2072 if (i < n - 1)
2073 ADDOP(c, DUP_TOP);
2074 VISIT(c, expr,
2075 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2076 }
2077 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002078 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002080 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002082 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002084 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002086 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 n = 0;
2090 if (s->v.Raise.type) {
2091 VISIT(c, expr, s->v.Raise.type);
2092 n++;
2093 if (s->v.Raise.inst) {
2094 VISIT(c, expr, s->v.Raise.inst);
2095 n++;
2096 if (s->v.Raise.tback) {
2097 VISIT(c, expr, s->v.Raise.tback);
2098 n++;
2099 }
2100 }
2101 }
2102 ADDOP_I(c, RAISE_VARARGS, n);
2103 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002104 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002105 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002106 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002108 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002110 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002112 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115 VISIT(c, expr, s->v.Exec.body);
2116 if (s->v.Exec.globals) {
2117 VISIT(c, expr, s->v.Exec.globals);
2118 if (s->v.Exec.locals) {
2119 VISIT(c, expr, s->v.Exec.locals);
2120 } else {
2121 ADDOP(c, DUP_TOP);
2122 }
2123 } else {
2124 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2125 ADDOP(c, DUP_TOP);
2126 }
2127 ADDOP(c, EXEC_STMT);
2128 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002129 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002131 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002133 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134 ADDOP(c, PRINT_EXPR);
2135 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002136 else if (s->v.Expr.value->kind != Str_kind &&
2137 s->v.Expr.value->kind != Num_kind) {
2138 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139 ADDOP(c, POP_TOP);
2140 }
2141 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002142 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002144 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 if (!c->u->u_nfblocks)
2146 return compiler_error(c, "'break' outside loop");
2147 ADDOP(c, BREAK_LOOP);
2148 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002149 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002151 case With_kind:
2152 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 }
2154 return 1;
2155}
2156
2157static int
2158unaryop(unaryop_ty op)
2159{
2160 switch (op) {
2161 case Invert:
2162 return UNARY_INVERT;
2163 case Not:
2164 return UNARY_NOT;
2165 case UAdd:
2166 return UNARY_POSITIVE;
2167 case USub:
2168 return UNARY_NEGATIVE;
2169 }
2170 return 0;
2171}
2172
2173static int
2174binop(struct compiler *c, operator_ty op)
2175{
2176 switch (op) {
2177 case Add:
2178 return BINARY_ADD;
2179 case Sub:
2180 return BINARY_SUBTRACT;
2181 case Mult:
2182 return BINARY_MULTIPLY;
2183 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002184 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002185 case Mod:
2186 return BINARY_MODULO;
2187 case Pow:
2188 return BINARY_POWER;
2189 case LShift:
2190 return BINARY_LSHIFT;
2191 case RShift:
2192 return BINARY_RSHIFT;
2193 case BitOr:
2194 return BINARY_OR;
2195 case BitXor:
2196 return BINARY_XOR;
2197 case BitAnd:
2198 return BINARY_AND;
2199 case FloorDiv:
2200 return BINARY_FLOOR_DIVIDE;
2201 }
2202 return 0;
2203}
2204
2205static int
2206cmpop(cmpop_ty op)
2207{
2208 switch (op) {
2209 case Eq:
2210 return PyCmp_EQ;
2211 case NotEq:
2212 return PyCmp_NE;
2213 case Lt:
2214 return PyCmp_LT;
2215 case LtE:
2216 return PyCmp_LE;
2217 case Gt:
2218 return PyCmp_GT;
2219 case GtE:
2220 return PyCmp_GE;
2221 case Is:
2222 return PyCmp_IS;
2223 case IsNot:
2224 return PyCmp_IS_NOT;
2225 case In:
2226 return PyCmp_IN;
2227 case NotIn:
2228 return PyCmp_NOT_IN;
2229 }
2230 return PyCmp_BAD;
2231}
2232
2233static int
2234inplace_binop(struct compiler *c, operator_ty op)
2235{
2236 switch (op) {
2237 case Add:
2238 return INPLACE_ADD;
2239 case Sub:
2240 return INPLACE_SUBTRACT;
2241 case Mult:
2242 return INPLACE_MULTIPLY;
2243 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002244 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 case Mod:
2246 return INPLACE_MODULO;
2247 case Pow:
2248 return INPLACE_POWER;
2249 case LShift:
2250 return INPLACE_LSHIFT;
2251 case RShift:
2252 return INPLACE_RSHIFT;
2253 case BitOr:
2254 return INPLACE_OR;
2255 case BitXor:
2256 return INPLACE_XOR;
2257 case BitAnd:
2258 return INPLACE_AND;
2259 case FloorDiv:
2260 return INPLACE_FLOOR_DIVIDE;
2261 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002262 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002263 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264 return 0;
2265}
2266
2267static int
2268compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2269{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002270 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2272
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002273 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002274 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275 /* XXX AugStore isn't used anywhere! */
2276
2277 /* First check for assignment to __debug__. Param? */
2278 if ((ctx == Store || ctx == AugStore || ctx == Del)
2279 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2280 return compiler_error(c, "can not assign to __debug__");
2281 }
2282
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002283 mangled = _Py_Mangle(c->u->u_private, name);
2284 if (!mangled)
2285 return 0;
2286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002287 op = 0;
2288 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002289 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 switch (scope) {
2291 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002292 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 optype = OP_DEREF;
2294 break;
2295 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002296 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297 optype = OP_DEREF;
2298 break;
2299 case LOCAL:
2300 if (c->u->u_ste->ste_type == FunctionBlock)
2301 optype = OP_FAST;
2302 break;
2303 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002304 if (c->u->u_ste->ste_type == FunctionBlock &&
2305 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 optype = OP_GLOBAL;
2307 break;
2308 case GLOBAL_EXPLICIT:
2309 optype = OP_GLOBAL;
2310 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002311 default:
2312 /* scope can be 0 */
2313 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314 }
2315
2316 /* XXX Leave assert here, but handle __doc__ and the like better */
2317 assert(scope || PyString_AS_STRING(name)[0] == '_');
2318
2319 switch (optype) {
2320 case OP_DEREF:
2321 switch (ctx) {
2322 case Load: op = LOAD_DEREF; break;
2323 case Store: op = STORE_DEREF; break;
2324 case AugLoad:
2325 case AugStore:
2326 break;
2327 case Del:
2328 PyErr_Format(PyExc_SyntaxError,
2329 "can not delete variable '%s' referenced "
2330 "in nested scope",
2331 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002332 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002334 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002335 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002336 PyErr_SetString(PyExc_SystemError,
2337 "param invalid for deref variable");
2338 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339 }
2340 break;
2341 case OP_FAST:
2342 switch (ctx) {
2343 case Load: op = LOAD_FAST; break;
2344 case Store: op = STORE_FAST; break;
2345 case Del: op = DELETE_FAST; break;
2346 case AugLoad:
2347 case AugStore:
2348 break;
2349 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002350 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002351 PyErr_SetString(PyExc_SystemError,
2352 "param invalid for local variable");
2353 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002355 ADDOP_O(c, op, mangled, varnames);
2356 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357 return 1;
2358 case OP_GLOBAL:
2359 switch (ctx) {
2360 case Load: op = LOAD_GLOBAL; break;
2361 case Store: op = STORE_GLOBAL; break;
2362 case Del: op = DELETE_GLOBAL; break;
2363 case AugLoad:
2364 case AugStore:
2365 break;
2366 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002367 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002368 PyErr_SetString(PyExc_SystemError,
2369 "param invalid for global variable");
2370 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371 }
2372 break;
2373 case OP_NAME:
2374 switch (ctx) {
2375 case Load: op = LOAD_NAME; break;
2376 case Store: op = STORE_NAME; break;
2377 case Del: op = DELETE_NAME; break;
2378 case AugLoad:
2379 case AugStore:
2380 break;
2381 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002382 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002383 PyErr_SetString(PyExc_SystemError,
2384 "param invalid for name variable");
2385 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386 }
2387 break;
2388 }
2389
2390 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002391 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002392 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002393 if (arg < 0)
2394 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002395 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002396}
2397
2398static int
2399compiler_boolop(struct compiler *c, expr_ty e)
2400{
2401 basicblock *end;
2402 int jumpi, i, n;
2403 asdl_seq *s;
2404
2405 assert(e->kind == BoolOp_kind);
2406 if (e->v.BoolOp.op == And)
2407 jumpi = JUMP_IF_FALSE;
2408 else
2409 jumpi = JUMP_IF_TRUE;
2410 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002411 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412 return 0;
2413 s = e->v.BoolOp.values;
2414 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002415 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002417 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002418 ADDOP_JREL(c, jumpi, end);
2419 ADDOP(c, POP_TOP)
2420 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422 compiler_use_next_block(c, end);
2423 return 1;
2424}
2425
2426static int
2427compiler_list(struct compiler *c, expr_ty e)
2428{
2429 int n = asdl_seq_LEN(e->v.List.elts);
2430 if (e->v.List.ctx == Store) {
2431 ADDOP_I(c, UNPACK_SEQUENCE, n);
2432 }
2433 VISIT_SEQ(c, expr, e->v.List.elts);
2434 if (e->v.List.ctx == Load) {
2435 ADDOP_I(c, BUILD_LIST, n);
2436 }
2437 return 1;
2438}
2439
2440static int
2441compiler_tuple(struct compiler *c, expr_ty e)
2442{
2443 int n = asdl_seq_LEN(e->v.Tuple.elts);
2444 if (e->v.Tuple.ctx == Store) {
2445 ADDOP_I(c, UNPACK_SEQUENCE, n);
2446 }
2447 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2448 if (e->v.Tuple.ctx == Load) {
2449 ADDOP_I(c, BUILD_TUPLE, n);
2450 }
2451 return 1;
2452}
2453
2454static int
2455compiler_compare(struct compiler *c, expr_ty e)
2456{
2457 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002458 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459
2460 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2461 VISIT(c, expr, e->v.Compare.left);
2462 n = asdl_seq_LEN(e->v.Compare.ops);
2463 assert(n > 0);
2464 if (n > 1) {
2465 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002466 if (cleanup == NULL)
2467 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002468 VISIT(c, expr,
2469 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 }
2471 for (i = 1; i < n; i++) {
2472 ADDOP(c, DUP_TOP);
2473 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002475 cmpop((cmpop_ty)(asdl_seq_GET(
2476 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2478 NEXT_BLOCK(c);
2479 ADDOP(c, POP_TOP);
2480 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002481 VISIT(c, expr,
2482 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002484 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002486 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487 if (n > 1) {
2488 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002489 if (end == NULL)
2490 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 ADDOP_JREL(c, JUMP_FORWARD, end);
2492 compiler_use_next_block(c, cleanup);
2493 ADDOP(c, ROT_TWO);
2494 ADDOP(c, POP_TOP);
2495 compiler_use_next_block(c, end);
2496 }
2497 return 1;
2498}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002499#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500
2501static int
2502compiler_call(struct compiler *c, expr_ty e)
2503{
2504 int n, code = 0;
2505
2506 VISIT(c, expr, e->v.Call.func);
2507 n = asdl_seq_LEN(e->v.Call.args);
2508 VISIT_SEQ(c, expr, e->v.Call.args);
2509 if (e->v.Call.keywords) {
2510 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2511 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2512 }
2513 if (e->v.Call.starargs) {
2514 VISIT(c, expr, e->v.Call.starargs);
2515 code |= 1;
2516 }
2517 if (e->v.Call.kwargs) {
2518 VISIT(c, expr, e->v.Call.kwargs);
2519 code |= 2;
2520 }
2521 switch (code) {
2522 case 0:
2523 ADDOP_I(c, CALL_FUNCTION, n);
2524 break;
2525 case 1:
2526 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2527 break;
2528 case 2:
2529 ADDOP_I(c, CALL_FUNCTION_KW, n);
2530 break;
2531 case 3:
2532 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2533 break;
2534 }
2535 return 1;
2536}
2537
2538static int
2539compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002540 asdl_seq *generators, int gen_index,
2541 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542{
2543 /* generate code for the iterator, then each of the ifs,
2544 and then write to the element */
2545
2546 comprehension_ty l;
2547 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002548 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549
2550 start = compiler_new_block(c);
2551 skip = compiler_new_block(c);
2552 if_cleanup = compiler_new_block(c);
2553 anchor = compiler_new_block(c);
2554
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002555 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2556 anchor == NULL)
2557 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002559 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 VISIT(c, expr, l->iter);
2561 ADDOP(c, GET_ITER);
2562 compiler_use_next_block(c, start);
2563 ADDOP_JREL(c, FOR_ITER, anchor);
2564 NEXT_BLOCK(c);
2565 VISIT(c, expr, l->target);
2566
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002567 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 n = asdl_seq_LEN(l->ifs);
2569 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002570 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 VISIT(c, expr, e);
2572 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2573 NEXT_BLOCK(c);
2574 ADDOP(c, POP_TOP);
2575 }
2576
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002577 if (++gen_index < asdl_seq_LEN(generators))
2578 if (!compiler_listcomp_generator(c, tmpname,
2579 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002582 /* only append after the last for generator */
2583 if (gen_index >= asdl_seq_LEN(generators)) {
2584 if (!compiler_nameop(c, tmpname, Load))
2585 return 0;
2586 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002587 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002588
2589 compiler_use_next_block(c, skip);
2590 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 for (i = 0; i < n; i++) {
2592 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002593 if (i == 0)
2594 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002595 ADDOP(c, POP_TOP);
2596 }
2597 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2598 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002599 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 return 0;
2603
2604 return 1;
2605}
2606
2607static int
2608compiler_listcomp(struct compiler *c, expr_ty e)
2609{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 static identifier append;
2613 asdl_seq *generators = e->v.ListComp.generators;
2614
2615 assert(e->kind == ListComp_kind);
2616 if (!append) {
2617 append = PyString_InternFromString("append");
2618 if (!append)
2619 return 0;
2620 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002621 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622 if (!tmp)
2623 return 0;
2624 ADDOP_I(c, BUILD_LIST, 0);
2625 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002627 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2628 e->v.ListComp.elt);
2629 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 return rc;
2631}
2632
2633static int
2634compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002635 asdl_seq *generators, int gen_index,
2636 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637{
2638 /* generate code for the iterator, then each of the ifs,
2639 and then write to the element */
2640
2641 comprehension_ty ge;
2642 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002643 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644
2645 start = compiler_new_block(c);
2646 skip = compiler_new_block(c);
2647 if_cleanup = compiler_new_block(c);
2648 anchor = compiler_new_block(c);
2649 end = compiler_new_block(c);
2650
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 anchor == NULL || end == NULL)
2653 return 0;
2654
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002655 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 ADDOP_JREL(c, SETUP_LOOP, end);
2657 if (!compiler_push_fblock(c, LOOP, start))
2658 return 0;
2659
2660 if (gen_index == 0) {
2661 /* Receive outermost iter as an implicit argument */
2662 c->u->u_argcount = 1;
2663 ADDOP_I(c, LOAD_FAST, 0);
2664 }
2665 else {
2666 /* Sub-iter - calculate on the fly */
2667 VISIT(c, expr, ge->iter);
2668 ADDOP(c, GET_ITER);
2669 }
2670 compiler_use_next_block(c, start);
2671 ADDOP_JREL(c, FOR_ITER, anchor);
2672 NEXT_BLOCK(c);
2673 VISIT(c, expr, ge->target);
2674
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 n = asdl_seq_LEN(ge->ifs);
2677 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002678 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 VISIT(c, expr, e);
2680 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2681 NEXT_BLOCK(c);
2682 ADDOP(c, POP_TOP);
2683 }
2684
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2687 return 0;
2688
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 /* only append after the last 'for' generator */
2690 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 VISIT(c, expr, elt);
2692 ADDOP(c, YIELD_VALUE);
2693 ADDOP(c, POP_TOP);
2694
2695 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 for (i = 0; i < n; i++) {
2698 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 compiler_use_next_block(c, if_cleanup);
2701
2702 ADDOP(c, POP_TOP);
2703 }
2704 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2705 compiler_use_next_block(c, anchor);
2706 ADDOP(c, POP_BLOCK);
2707 compiler_pop_fblock(c, LOOP, start);
2708 compiler_use_next_block(c, end);
2709
2710 return 1;
2711}
2712
2713static int
2714compiler_genexp(struct compiler *c, expr_ty e)
2715{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002716 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 PyCodeObject *co;
2718 expr_ty outermost_iter = ((comprehension_ty)
2719 (asdl_seq_GET(e->v.GeneratorExp.generators,
2720 0)))->iter;
2721
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002722 if (!name) {
2723 name = PyString_FromString("<genexpr>");
2724 if (!name)
2725 return 0;
2726 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727
2728 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2729 return 0;
2730 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2731 e->v.GeneratorExp.elt);
2732 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002733 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 if (co == NULL)
2735 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002737 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002738 Py_DECREF(co);
2739
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740 VISIT(c, expr, outermost_iter);
2741 ADDOP(c, GET_ITER);
2742 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743
2744 return 1;
2745}
2746
2747static int
2748compiler_visit_keyword(struct compiler *c, keyword_ty k)
2749{
2750 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2751 VISIT(c, expr, k->value);
2752 return 1;
2753}
2754
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002755/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 whether they are true or false.
2757
2758 Return values: 1 for true, 0 for false, -1 for non-constant.
2759 */
2760
2761static int
2762expr_constant(expr_ty e)
2763{
2764 switch (e->kind) {
2765 case Num_kind:
2766 return PyObject_IsTrue(e->v.Num.n);
2767 case Str_kind:
2768 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002769 case Name_kind:
2770 /* __debug__ is not assignable, so we can optimize
2771 * it away in if and while statements */
2772 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2773 "__debug__") == 0)
2774 return ! Py_OptimizeFlag;
2775 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776 default:
2777 return -1;
2778 }
2779}
2780
Guido van Rossumc2e20742006-02-27 22:32:47 +00002781/*
2782 Implements the with statement from PEP 343.
2783
2784 The semantics outlined in that PEP are as follows:
2785
2786 with EXPR as VAR:
2787 BLOCK
2788
2789 It is implemented roughly as:
2790
Thomas Wouters477c8d52006-05-27 19:21:47 +00002791 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002792 exit = context.__exit__ # not calling it
2793 value = context.__enter__()
2794 try:
2795 VAR = value # if VAR present in the syntax
2796 BLOCK
2797 finally:
2798 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002799 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002800 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002802 exit(*exc)
2803 */
2804static int
2805compiler_with(struct compiler *c, stmt_ty s)
2806{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002807 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002808 basicblock *block, *finally;
2809 identifier tmpexit, tmpvalue = NULL;
2810
2811 assert(s->kind == With_kind);
2812
Guido van Rossumc2e20742006-02-27 22:32:47 +00002813 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002814 enter_attr = PyString_InternFromString("__enter__");
2815 if (!enter_attr)
2816 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002817 }
2818 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002819 exit_attr = PyString_InternFromString("__exit__");
2820 if (!exit_attr)
2821 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002822 }
2823
2824 block = compiler_new_block(c);
2825 finally = compiler_new_block(c);
2826 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002827 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002828
2829 /* Create a temporary variable to hold context.__exit__ */
2830 tmpexit = compiler_new_tmpname(c);
2831 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002832 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002833 PyArena_AddPyObject(c->c_arena, tmpexit);
2834
2835 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002836 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002837 We need to do this rather than preserving it on the stack
2838 because SETUP_FINALLY remembers the stack level.
2839 We need to do the assignment *inside* the try/finally
2840 so that context.__exit__() is called when the assignment
2841 fails. But we need to call context.__enter__() *before*
2842 the try/finally so that if it fails we won't call
2843 context.__exit__().
2844 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002846 if (tmpvalue == NULL)
2847 return 0;
2848 PyArena_AddPyObject(c->c_arena, tmpvalue);
2849 }
2850
Thomas Wouters477c8d52006-05-27 19:21:47 +00002851 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002852 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002853
2854 /* Squirrel away context.__exit__ */
2855 ADDOP(c, DUP_TOP);
2856 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2857 if (!compiler_nameop(c, tmpexit, Store))
2858 return 0;
2859
2860 /* Call context.__enter__() */
2861 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2862 ADDOP_I(c, CALL_FUNCTION, 0);
2863
2864 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 /* Store it in tmpvalue */
2866 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002867 return 0;
2868 }
2869 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002870 /* Discard result from context.__enter__() */
2871 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002872 }
2873
2874 /* Start the try block */
2875 ADDOP_JREL(c, SETUP_FINALLY, finally);
2876
2877 compiler_use_next_block(c, block);
2878 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002879 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002880 }
2881
2882 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002883 /* Bind saved result of context.__enter__() to VAR */
2884 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002885 !compiler_nameop(c, tmpvalue, Del))
2886 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002887 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002888 }
2889
2890 /* BLOCK code */
2891 VISIT_SEQ(c, stmt, s->v.With.body);
2892
2893 /* End of try block; start the finally block */
2894 ADDOP(c, POP_BLOCK);
2895 compiler_pop_fblock(c, FINALLY_TRY, block);
2896
2897 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2898 compiler_use_next_block(c, finally);
2899 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002900 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002901
2902 /* Finally block starts; push tmpexit and issue our magic opcode. */
2903 if (!compiler_nameop(c, tmpexit, Load) ||
2904 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002905 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002906 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002907
2908 /* Finally block ends. */
2909 ADDOP(c, END_FINALLY);
2910 compiler_pop_fblock(c, FINALLY_END, finally);
2911 return 1;
2912}
2913
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914static int
2915compiler_visit_expr(struct compiler *c, expr_ty e)
2916{
2917 int i, n;
2918
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919 /* If expr e has a different line number than the last expr/stmt,
2920 set a new line number for the next instruction.
2921 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 if (e->lineno > c->u->u_lineno) {
2923 c->u->u_lineno = e->lineno;
2924 c->u->u_lineno_set = false;
2925 }
2926 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002927 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002929 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930 VISIT(c, expr, e->v.BinOp.left);
2931 VISIT(c, expr, e->v.BinOp.right);
2932 ADDOP(c, binop(c, e->v.BinOp.op));
2933 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002934 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 VISIT(c, expr, e->v.UnaryOp.operand);
2936 ADDOP(c, unaryop(e->v.UnaryOp.op));
2937 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002938 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002940 case IfExp_kind:
2941 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002942 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 /* XXX get rid of arg? */
2944 ADDOP_I(c, BUILD_MAP, 0);
2945 n = asdl_seq_LEN(e->v.Dict.values);
2946 /* We must arrange things just right for STORE_SUBSCR.
2947 It wants the stack to look like (value) (dict) (key) */
2948 for (i = 0; i < n; i++) {
2949 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002950 VISIT(c, expr,
2951 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002953 VISIT(c, expr,
2954 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 ADDOP(c, STORE_SUBSCR);
2956 }
2957 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002958 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002960 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 return compiler_genexp(c, e);
2962 case Yield_kind:
2963 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002964 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965 /*
2966 for (i = 0; i < c->u->u_nfblocks; i++) {
2967 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2968 return compiler_error(
2969 c, "'yield' not allowed in a 'try' "
2970 "block with a 'finally' clause");
2971 }
2972 */
2973 if (e->v.Yield.value) {
2974 VISIT(c, expr, e->v.Yield.value);
2975 }
2976 else {
2977 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2978 }
2979 ADDOP(c, YIELD_VALUE);
2980 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002981 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002983 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002985 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2987 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002988 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2990 break;
2991 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002992 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002993 if (e->v.Attribute.ctx != AugStore)
2994 VISIT(c, expr, e->v.Attribute.value);
2995 switch (e->v.Attribute.ctx) {
2996 case AugLoad:
2997 ADDOP(c, DUP_TOP);
2998 /* Fall through to load */
2999 case Load:
3000 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3001 break;
3002 case AugStore:
3003 ADDOP(c, ROT_TWO);
3004 /* Fall through to save */
3005 case Store:
3006 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3007 break;
3008 case Del:
3009 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3010 break;
3011 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003012 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003013 PyErr_SetString(PyExc_SystemError,
3014 "param invalid in attribute expression");
3015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 }
3017 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003018 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 switch (e->v.Subscript.ctx) {
3020 case AugLoad:
3021 VISIT(c, expr, e->v.Subscript.value);
3022 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3023 break;
3024 case Load:
3025 VISIT(c, expr, e->v.Subscript.value);
3026 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3027 break;
3028 case AugStore:
3029 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3030 break;
3031 case Store:
3032 VISIT(c, expr, e->v.Subscript.value);
3033 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3034 break;
3035 case Del:
3036 VISIT(c, expr, e->v.Subscript.value);
3037 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3038 break;
3039 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003040 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003041 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 }
3045 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003046 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3048 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003051 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 return compiler_tuple(c, e);
3053 }
3054 return 1;
3055}
3056
3057static int
3058compiler_augassign(struct compiler *c, stmt_ty s)
3059{
3060 expr_ty e = s->v.AugAssign.target;
3061 expr_ty auge;
3062
3063 assert(s->kind == AugAssign_kind);
3064
3065 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003066 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
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));
3074 auge->v.Attribute.ctx = AugStore;
3075 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 break;
3077 case Subscript_kind:
3078 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003079 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003080 if (auge == NULL)
3081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 VISIT(c, expr, auge);
3083 VISIT(c, expr, s->v.AugAssign.value);
3084 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003085 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003089 if (!compiler_nameop(c, e->v.Name.id, Load))
3090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 VISIT(c, expr, s->v.AugAssign.value);
3092 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3093 return compiler_nameop(c, e->v.Name.id, Store);
3094 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003095 PyErr_Format(PyExc_SystemError,
3096 "invalid node type (%d) for augmented assignment",
3097 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003099 }
3100 return 1;
3101}
3102
3103static int
3104compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3105{
3106 struct fblockinfo *f;
3107 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3108 return 0;
3109 f = &c->u->u_fblock[c->u->u_nfblocks++];
3110 f->fb_type = t;
3111 f->fb_block = b;
3112 return 1;
3113}
3114
3115static void
3116compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3117{
3118 struct compiler_unit *u = c->u;
3119 assert(u->u_nfblocks > 0);
3120 u->u_nfblocks--;
3121 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3122 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3123}
3124
3125/* Raises a SyntaxError and returns 0.
3126 If something goes wrong, a different exception may be raised.
3127*/
3128
3129static int
3130compiler_error(struct compiler *c, const char *errstr)
3131{
3132 PyObject *loc;
3133 PyObject *u = NULL, *v = NULL;
3134
3135 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3136 if (!loc) {
3137 Py_INCREF(Py_None);
3138 loc = Py_None;
3139 }
3140 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3141 Py_None, loc);
3142 if (!u)
3143 goto exit;
3144 v = Py_BuildValue("(zO)", errstr, u);
3145 if (!v)
3146 goto exit;
3147 PyErr_SetObject(PyExc_SyntaxError, v);
3148 exit:
3149 Py_DECREF(loc);
3150 Py_XDECREF(u);
3151 Py_XDECREF(v);
3152 return 0;
3153}
3154
3155static int
3156compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 /* XXX this code is duplicated */
3162 switch (ctx) {
3163 case AugLoad: /* fall through to Load */
3164 case Load: op = BINARY_SUBSCR; break;
3165 case AugStore:/* fall through to Store */
3166 case Store: op = STORE_SUBSCR; break;
3167 case Del: op = DELETE_SUBSCR; break;
3168 case Param:
3169 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003170 "invalid %s kind %d in subscript\n",
3171 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172 return 0;
3173 }
3174 if (ctx == AugLoad) {
3175 ADDOP_I(c, DUP_TOPX, 2);
3176 }
3177 else if (ctx == AugStore) {
3178 ADDOP(c, ROT_THREE);
3179 }
3180 ADDOP(c, op);
3181 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182}
3183
3184static int
3185compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3186{
3187 int n = 2;
3188 assert(s->kind == Slice_kind);
3189
3190 /* only handles the cases where BUILD_SLICE is emitted */
3191 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193 }
3194 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003199 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200 }
3201 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 }
3204
3205 if (s->v.Slice.step) {
3206 n++;
3207 VISIT(c, expr, s->v.Slice.step);
3208 }
3209 ADDOP_I(c, BUILD_SLICE, n);
3210 return 1;
3211}
3212
3213static int
3214compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3215{
3216 int op = 0, slice_offset = 0, stack_count = 0;
3217
3218 assert(s->v.Slice.step == NULL);
3219 if (s->v.Slice.lower) {
3220 slice_offset++;
3221 stack_count++;
3222 if (ctx != AugStore)
3223 VISIT(c, expr, s->v.Slice.lower);
3224 }
3225 if (s->v.Slice.upper) {
3226 slice_offset += 2;
3227 stack_count++;
3228 if (ctx != AugStore)
3229 VISIT(c, expr, s->v.Slice.upper);
3230 }
3231
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003232 if (ctx == AugLoad) {
3233 switch (stack_count) {
3234 case 0: ADDOP(c, DUP_TOP); break;
3235 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3236 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3237 }
3238 }
3239 else if (ctx == AugStore) {
3240 switch (stack_count) {
3241 case 0: ADDOP(c, ROT_TWO); break;
3242 case 1: ADDOP(c, ROT_THREE); break;
3243 case 2: ADDOP(c, ROT_FOUR); break;
3244 }
3245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246
3247 switch (ctx) {
3248 case AugLoad: /* fall through to Load */
3249 case Load: op = SLICE; break;
3250 case AugStore:/* fall through to Store */
3251 case Store: op = STORE_SLICE; break;
3252 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003253 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003254 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003255 PyErr_SetString(PyExc_SystemError,
3256 "param invalid in simple slice");
3257 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 }
3259
3260 ADDOP(c, op + slice_offset);
3261 return 1;
3262}
3263
3264static int
3265compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3266 expr_context_ty ctx)
3267{
3268 switch (s->kind) {
3269 case Ellipsis_kind:
3270 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3271 break;
3272 case Slice_kind:
3273 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274 case Index_kind:
3275 VISIT(c, expr, s->v.Index.value);
3276 break;
3277 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003278 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003279 PyErr_SetString(PyExc_SystemError,
3280 "extended slice invalid in nested slice");
3281 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282 }
3283 return 1;
3284}
3285
3286
3287static int
3288compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3289{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003290 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003292 case Index_kind:
3293 kindname = "index";
3294 if (ctx != AugStore) {
3295 VISIT(c, expr, s->v.Index.value);
3296 }
3297 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003299 kindname = "ellipsis";
3300 if (ctx != AugStore) {
3301 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 break;
3304 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003305 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306 if (!s->v.Slice.step)
3307 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003308 if (ctx != AugStore) {
3309 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 return 0;
3311 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003312 break;
3313 case ExtSlice_kind:
3314 kindname = "extended slice";
3315 if (ctx != AugStore) {
3316 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3317 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003318 slice_ty sub = (slice_ty)asdl_seq_GET(
3319 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003320 if (!compiler_visit_nested_slice(c, sub, ctx))
3321 return 0;
3322 }
3323 ADDOP_I(c, BUILD_TUPLE, n);
3324 }
3325 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003326 default:
3327 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003328 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003329 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003331 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332}
3333
3334/* do depth-first search of basic block graph, starting with block.
3335 post records the block indices in post-order.
3336
3337 XXX must handle implicit jumps from one block to next
3338*/
3339
3340static void
3341dfs(struct compiler *c, basicblock *b, struct assembler *a)
3342{
3343 int i;
3344 struct instr *instr = NULL;
3345
3346 if (b->b_seen)
3347 return;
3348 b->b_seen = 1;
3349 if (b->b_next != NULL)
3350 dfs(c, b->b_next, a);
3351 for (i = 0; i < b->b_iused; i++) {
3352 instr = &b->b_instr[i];
3353 if (instr->i_jrel || instr->i_jabs)
3354 dfs(c, instr->i_target, a);
3355 }
3356 a->a_postorder[a->a_nblocks++] = b;
3357}
3358
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003359static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003360stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3361{
3362 int i;
3363 struct instr *instr;
3364 if (b->b_seen || b->b_startdepth >= depth)
3365 return maxdepth;
3366 b->b_seen = 1;
3367 b->b_startdepth = depth;
3368 for (i = 0; i < b->b_iused; i++) {
3369 instr = &b->b_instr[i];
3370 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3371 if (depth > maxdepth)
3372 maxdepth = depth;
3373 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3374 if (instr->i_jrel || instr->i_jabs) {
3375 maxdepth = stackdepth_walk(c, instr->i_target,
3376 depth, maxdepth);
3377 if (instr->i_opcode == JUMP_ABSOLUTE ||
3378 instr->i_opcode == JUMP_FORWARD) {
3379 goto out; /* remaining code is dead */
3380 }
3381 }
3382 }
3383 if (b->b_next)
3384 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3385out:
3386 b->b_seen = 0;
3387 return maxdepth;
3388}
3389
3390/* Find the flow path that needs the largest stack. We assume that
3391 * cycles in the flow graph have no net effect on the stack depth.
3392 */
3393static int
3394stackdepth(struct compiler *c)
3395{
3396 basicblock *b, *entryblock;
3397 entryblock = NULL;
3398 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3399 b->b_seen = 0;
3400 b->b_startdepth = INT_MIN;
3401 entryblock = b;
3402 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003403 if (!entryblock)
3404 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 return stackdepth_walk(c, entryblock, 0, 0);
3406}
3407
3408static int
3409assemble_init(struct assembler *a, int nblocks, int firstlineno)
3410{
3411 memset(a, 0, sizeof(struct assembler));
3412 a->a_lineno = firstlineno;
3413 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3414 if (!a->a_bytecode)
3415 return 0;
3416 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3417 if (!a->a_lnotab)
3418 return 0;
3419 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003420 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003421 if (!a->a_postorder) {
3422 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003423 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003425 return 1;
3426}
3427
3428static void
3429assemble_free(struct assembler *a)
3430{
3431 Py_XDECREF(a->a_bytecode);
3432 Py_XDECREF(a->a_lnotab);
3433 if (a->a_postorder)
3434 PyObject_Free(a->a_postorder);
3435}
3436
3437/* Return the size of a basic block in bytes. */
3438
3439static int
3440instrsize(struct instr *instr)
3441{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003442 if (!instr->i_hasarg)
3443 return 1;
3444 if (instr->i_oparg > 0xffff)
3445 return 6;
3446 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447}
3448
3449static int
3450blocksize(basicblock *b)
3451{
3452 int i;
3453 int size = 0;
3454
3455 for (i = 0; i < b->b_iused; i++)
3456 size += instrsize(&b->b_instr[i]);
3457 return size;
3458}
3459
3460/* All about a_lnotab.
3461
3462c_lnotab is an array of unsigned bytes disguised as a Python string.
3463It is used to map bytecode offsets to source code line #s (when needed
3464for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003465
Tim Peters2a7f3842001-06-09 09:26:21 +00003466The array is conceptually a list of
3467 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003469
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 byte code offset source code line number
3471 0 1
3472 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003473 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003474 350 307
3475 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003476
3477The first trick is that these numbers aren't stored, only the increments
3478from one row to the next (this doesn't really work, but it's a start):
3479
3480 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3481
3482The second trick is that an unsigned byte can't hold negative values, or
3483values larger than 255, so (a) there's a deep assumption that byte code
3484offsets and their corresponding line #s both increase monotonically, and (b)
3485if at least one column jumps by more than 255 from one row to the next, more
3486than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003488part. A user of c_lnotab desiring to find the source line number
3489corresponding to a bytecode address A should do something like this
3490
3491 lineno = addr = 0
3492 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 addr += addr_incr
3494 if addr > A:
3495 return lineno
3496 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003497
3498In order for this to work, when the addr field increments by more than 255,
3499the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003500increment is < 256. So, in the example above, assemble_lnotab (it used
3501to be called com_set_lineno) should not (as was actually done until 2.2)
3502expand 300, 300 to 255, 255, 45, 45,
3503 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003504*/
3505
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003506static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003508{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 int d_bytecode, d_lineno;
3510 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003511 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512
3513 d_bytecode = a->a_offset - a->a_lineno_off;
3514 d_lineno = i->i_lineno - a->a_lineno;
3515
3516 assert(d_bytecode >= 0);
3517 assert(d_lineno >= 0);
3518
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003519 /* XXX(nnorwitz): is there a better way to handle this?
3520 for loops are special, we want to be able to trace them
3521 each time around, so we need to set an extra line number. */
3522 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003523 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003526 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 nbytes = a->a_lnotab_off + 2 * ncodes;
3528 len = PyString_GET_SIZE(a->a_lnotab);
3529 if (nbytes >= len) {
3530 if (len * 2 < nbytes)
3531 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003532 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 len *= 2;
3534 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3535 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003536 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003537 lnotab = (unsigned char *)
3538 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003539 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540 *lnotab++ = 255;
3541 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003542 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 d_bytecode -= ncodes * 255;
3544 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003545 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 assert(d_bytecode <= 255);
3547 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003548 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 nbytes = a->a_lnotab_off + 2 * ncodes;
3550 len = PyString_GET_SIZE(a->a_lnotab);
3551 if (nbytes >= len) {
3552 if (len * 2 < nbytes)
3553 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003554 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 len *= 2;
3556 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3557 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003558 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003559 lnotab = (unsigned char *)
3560 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003562 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003564 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003566 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003567 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 d_lineno -= ncodes * 255;
3569 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003570 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003571
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 len = PyString_GET_SIZE(a->a_lnotab);
3573 if (a->a_lnotab_off + 2 >= len) {
3574 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003575 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003576 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003577 lnotab = (unsigned char *)
3578 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 a->a_lnotab_off += 2;
3581 if (d_bytecode) {
3582 *lnotab++ = d_bytecode;
3583 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003584 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003585 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 *lnotab++ = 0;
3587 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 a->a_lineno = i->i_lineno;
3590 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003591 return 1;
3592}
3593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594/* assemble_emit()
3595 Extend the bytecode with a new instruction.
3596 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003597*/
3598
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003599static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003601{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003602 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003603 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604 char *code;
3605
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003606 size = instrsize(i);
3607 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003609 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003610 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 if (a->a_offset + size >= len) {
3614 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003615 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3618 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003619 if (size == 6) {
3620 assert(i->i_hasarg);
3621 *code++ = (char)EXTENDED_ARG;
3622 *code++ = ext & 0xff;
3623 *code++ = ext >> 8;
3624 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003627 if (i->i_hasarg) {
3628 assert(size == 3 || size == 6);
3629 *code++ = arg & 0xff;
3630 *code++ = arg >> 8;
3631 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003633}
3634
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003635static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003637{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003639 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003640 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003641
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 /* Compute the size of each block and fixup jump args.
3643 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003644start:
3645 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003647 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 bsize = blocksize(b);
3649 b->b_offset = totsize;
3650 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003651 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003652 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3654 bsize = b->b_offset;
3655 for (i = 0; i < b->b_iused; i++) {
3656 struct instr *instr = &b->b_instr[i];
3657 /* Relative jumps are computed relative to
3658 the instruction pointer after fetching
3659 the jump instruction.
3660 */
3661 bsize += instrsize(instr);
3662 if (instr->i_jabs)
3663 instr->i_oparg = instr->i_target->b_offset;
3664 else if (instr->i_jrel) {
3665 int delta = instr->i_target->b_offset - bsize;
3666 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003667 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003668 else
3669 continue;
3670 if (instr->i_oparg > 0xffff)
3671 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003672 }
3673 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003674
3675 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003676 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003677 with a better solution.
3678
3679 In the meantime, should the goto be dropped in favor
3680 of a loop?
3681
3682 The issue is that in the first loop blocksize() is called
3683 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003684 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003685 i_oparg is calculated in the second loop above.
3686
3687 So we loop until we stop seeing new EXTENDED_ARGs.
3688 The only EXTENDED_ARGs that could be popping up are
3689 ones in jump instructions. So this should converge
3690 fairly quickly.
3691 */
3692 if (last_extended_arg_count != extended_arg_count) {
3693 last_extended_arg_count = extended_arg_count;
3694 goto start;
3695 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003696}
3697
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003698static PyObject *
3699dict_keys_inorder(PyObject *dict, int offset)
3700{
3701 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003702 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003703
3704 tuple = PyTuple_New(size);
3705 if (tuple == NULL)
3706 return NULL;
3707 while (PyDict_Next(dict, &pos, &k, &v)) {
3708 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003709 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003710 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003711 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003712 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003713 PyTuple_SET_ITEM(tuple, i - offset, k);
3714 }
3715 return tuple;
3716}
3717
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003718static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003720{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003721 PySTEntryObject *ste = c->u->u_ste;
3722 int flags = 0, n;
3723 if (ste->ste_type != ModuleBlock)
3724 flags |= CO_NEWLOCALS;
3725 if (ste->ste_type == FunctionBlock) {
3726 if (!ste->ste_unoptimized)
3727 flags |= CO_OPTIMIZED;
3728 if (ste->ste_nested)
3729 flags |= CO_NESTED;
3730 if (ste->ste_generator)
3731 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003732 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733 if (ste->ste_varargs)
3734 flags |= CO_VARARGS;
3735 if (ste->ste_varkeywords)
3736 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003737 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003739
3740 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003741 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 n = PyDict_Size(c->u->u_freevars);
3744 if (n < 0)
3745 return -1;
3746 if (n == 0) {
3747 n = PyDict_Size(c->u->u_cellvars);
3748 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003749 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 if (n == 0) {
3751 flags |= CO_NOFREE;
3752 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003753 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003754
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003755 return flags;
3756}
3757
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003758static PyCodeObject *
3759makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003760{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 PyObject *tmp;
3762 PyCodeObject *co = NULL;
3763 PyObject *consts = NULL;
3764 PyObject *names = NULL;
3765 PyObject *varnames = NULL;
3766 PyObject *filename = NULL;
3767 PyObject *name = NULL;
3768 PyObject *freevars = NULL;
3769 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003770 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003773 tmp = dict_keys_inorder(c->u->u_consts, 0);
3774 if (!tmp)
3775 goto error;
3776 consts = PySequence_List(tmp); /* optimize_code requires a list */
3777 Py_DECREF(tmp);
3778
3779 names = dict_keys_inorder(c->u->u_names, 0);
3780 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3781 if (!consts || !names || !varnames)
3782 goto error;
3783
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003784 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3785 if (!cellvars)
3786 goto error;
3787 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3788 if (!freevars)
3789 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790 filename = PyString_FromString(c->c_filename);
3791 if (!filename)
3792 goto error;
3793
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003794 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003795 flags = compute_code_flags(c);
3796 if (flags < 0)
3797 goto error;
3798
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003799 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 if (!bytecode)
3801 goto error;
3802
3803 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3804 if (!tmp)
3805 goto error;
3806 Py_DECREF(consts);
3807 consts = tmp;
3808
3809 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3810 bytecode, consts, names, varnames,
3811 freevars, cellvars,
3812 filename, c->u->u_name,
3813 c->u->u_firstlineno,
3814 a->a_lnotab);
3815 error:
3816 Py_XDECREF(consts);
3817 Py_XDECREF(names);
3818 Py_XDECREF(varnames);
3819 Py_XDECREF(filename);
3820 Py_XDECREF(name);
3821 Py_XDECREF(freevars);
3822 Py_XDECREF(cellvars);
3823 Py_XDECREF(bytecode);
3824 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003825}
3826
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003827
3828/* For debugging purposes only */
3829#if 0
3830static void
3831dump_instr(const struct instr *i)
3832{
3833 const char *jrel = i->i_jrel ? "jrel " : "";
3834 const char *jabs = i->i_jabs ? "jabs " : "";
3835 char arg[128];
3836
3837 *arg = '\0';
3838 if (i->i_hasarg)
3839 sprintf(arg, "arg: %d ", i->i_oparg);
3840
3841 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3842 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3843}
3844
3845static void
3846dump_basicblock(const basicblock *b)
3847{
3848 const char *seen = b->b_seen ? "seen " : "";
3849 const char *b_return = b->b_return ? "return " : "";
3850 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3851 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3852 if (b->b_instr) {
3853 int i;
3854 for (i = 0; i < b->b_iused; i++) {
3855 fprintf(stderr, " [%02d] ", i);
3856 dump_instr(b->b_instr + i);
3857 }
3858 }
3859}
3860#endif
3861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862static PyCodeObject *
3863assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003864{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 basicblock *b, *entryblock;
3866 struct assembler a;
3867 int i, j, nblocks;
3868 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 /* Make sure every block that falls off the end returns None.
3871 XXX NEXT_BLOCK() isn't quite right, because if the last
3872 block ends with a jump or return b_next shouldn't set.
3873 */
3874 if (!c->u->u_curblock->b_return) {
3875 NEXT_BLOCK(c);
3876 if (addNone)
3877 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3878 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003879 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 nblocks = 0;
3882 entryblock = NULL;
3883 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3884 nblocks++;
3885 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003886 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003887
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003888 /* Set firstlineno if it wasn't explicitly set. */
3889 if (!c->u->u_firstlineno) {
3890 if (entryblock && entryblock->b_instr)
3891 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3892 else
3893 c->u->u_firstlineno = 1;
3894 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3896 goto error;
3897 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003900 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003901
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 /* Emit code in reverse postorder from dfs. */
3903 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003904 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 for (j = 0; j < b->b_iused; j++)
3906 if (!assemble_emit(&a, &b->b_instr[j]))
3907 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003908 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003909
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3911 goto error;
3912 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3913 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 co = makecode(c, &a);
3916 error:
3917 assemble_free(&a);
3918 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003919}