blob: 678a4deee961d102bb45d2cd290449edda24e874 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
190
191static int inplace_binop(struct compiler *, operator_ty);
192static int expr_constant(expr_ty e);
193
Guido van Rossumc2e20742006-02-27 22:32:47 +0000194static int compiler_with(struct compiler *, stmt_ty);
195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static PyCodeObject *assemble(struct compiler *, int addNone);
197static PyObject *__doc__;
198
199PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000207 if (privateobj == NULL || !PyString_Check(privateobj) ||
208 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000305 if (!arena)
306 return NULL;
307 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000308 if (mod)
309 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000310 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000311 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000312}
313
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 if (c->c_st)
318 PySymtable_Free(c->c_st);
319 if (c->c_future)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322}
323
Guido van Rossum79f25d91997-04-29 20:08:16 +0000324static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000326{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 Py_ssize_t i, n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 PyObject *v, *k;
329 PyObject *dict = PyDict_New();
330 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 n = PyList_Size(list);
333 for (i = 0; i < n; i++) {
334 v = PyInt_FromLong(i);
335 if (!v) {
336 Py_DECREF(dict);
337 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000338 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
342 Py_XDECREF(k);
343 Py_DECREF(v);
344 Py_DECREF(dict);
345 return NULL;
346 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000347 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 return dict;
351}
352
353/* Return new dict containing names from src that match scope(s).
354
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355src is a symbol table dictionary. If the scope of a name matches
356either scope_type or flag is set, insert it into the new dict. The
357values are integers, starting at offset and increasing by one for
358each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359*/
360
361static PyObject *
362dictbytype(PyObject *src, int scope_type, int flag, int offset)
363{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365 PyObject *k, *v, *dest = PyDict_New();
366
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 assert(offset >= 0);
368 if (dest == NULL)
369 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
371 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 /* XXX this should probably be a macro in symtable.h */
373 assert(PyInt_Check(v));
374 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
377 PyObject *tuple, *item = PyInt_FromLong(i);
378 if (item == NULL) {
379 Py_DECREF(dest);
380 return NULL;
381 }
382 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
385 Py_DECREF(item);
386 Py_DECREF(dest);
387 Py_XDECREF(tuple);
388 return NULL;
389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 }
394 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000395}
396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000397/*
398
399Leave this debugging code for just a little longer.
400
401static void
402compiler_display_symbols(PyObject *name, PyObject *symbols)
403{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000404PyObject *key, *value;
405int flags;
406Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
409while (PyDict_Next(symbols, &pos, &key, &value)) {
410flags = PyInt_AsLong(value);
411fprintf(stderr, "var %s:", PyString_AS_STRING(key));
412if (flags & DEF_GLOBAL)
413fprintf(stderr, " declared_global");
414if (flags & DEF_LOCAL)
415fprintf(stderr, " local");
416if (flags & DEF_PARAM)
417fprintf(stderr, " param");
418if (flags & DEF_STAR)
419fprintf(stderr, " stararg");
420if (flags & DEF_DOUBLESTAR)
421fprintf(stderr, " starstar");
422if (flags & DEF_INTUPLE)
423fprintf(stderr, " tuple");
424if (flags & DEF_FREE)
425fprintf(stderr, " free");
426if (flags & DEF_FREE_GLOBAL)
427fprintf(stderr, " global");
428if (flags & DEF_FREE_CLASS)
429fprintf(stderr, " free/class");
430if (flags & DEF_IMPORT)
431fprintf(stderr, " import");
432fprintf(stderr, "\n");
433}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000434 fprintf(stderr, "\n");
435}
436*/
437
438static void
439compiler_unit_check(struct compiler_unit *u)
440{
441 basicblock *block;
442 for (block = u->u_blocks; block != NULL; block = block->b_list) {
443 assert(block != (void *)0xcbcbcbcb);
444 assert(block != (void *)0xfbfbfbfb);
445 assert(block != (void *)0xdbdbdbdb);
446 if (block->b_instr != NULL) {
447 assert(block->b_ialloc > 0);
448 assert(block->b_iused > 0);
449 assert(block->b_ialloc >= block->b_iused);
450 }
451 else {
452 assert (block->b_iused == 0);
453 assert (block->b_ialloc == 0);
454 }
455 }
456}
457
458static void
459compiler_unit_free(struct compiler_unit *u)
460{
461 basicblock *b, *next;
462
463 compiler_unit_check(u);
464 b = u->u_blocks;
465 while (b != NULL) {
466 if (b->b_instr)
467 PyObject_Free((void *)b->b_instr);
468 next = b->b_list;
469 PyObject_Free((void *)b);
470 b = next;
471 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472 Py_CLEAR(u->u_ste);
473 Py_CLEAR(u->u_name);
474 Py_CLEAR(u->u_consts);
475 Py_CLEAR(u->u_names);
476 Py_CLEAR(u->u_varnames);
477 Py_CLEAR(u->u_freevars);
478 Py_CLEAR(u->u_cellvars);
479 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000480 PyObject_Free(u);
481}
482
483static int
484compiler_enter_scope(struct compiler *c, identifier name, void *key,
485 int lineno)
486{
487 struct compiler_unit *u;
488
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
490 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000491 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000492 PyErr_NoMemory();
493 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000494 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000495 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496 u->u_argcount = 0;
497 u->u_ste = PySymtable_Lookup(c->c_st, key);
498 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000499 compiler_unit_free(u);
500 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501 }
502 Py_INCREF(name);
503 u->u_name = name;
504 u->u_varnames = list2dict(u->u_ste->ste_varnames);
505 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 if (!u->u_varnames || !u->u_cellvars) {
507 compiler_unit_free(u);
508 return 0;
509 }
510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000511 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000512 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000513 if (!u->u_freevars) {
514 compiler_unit_free(u);
515 return 0;
516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517
518 u->u_blocks = NULL;
519 u->u_tmpname = 0;
520 u->u_nfblocks = 0;
521 u->u_firstlineno = lineno;
522 u->u_lineno = 0;
523 u->u_lineno_set = false;
524 u->u_consts = PyDict_New();
525 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000526 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000527 return 0;
528 }
529 u->u_names = PyDict_New();
530 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000531 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532 return 0;
533 }
534
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000535 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
537 /* Push the old compiler_unit on the stack. */
538 if (c->u) {
539 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
541 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000542 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543 return 0;
544 }
545 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000546 u->u_private = c->u->u_private;
547 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548 }
549 c->u = u;
550
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000551 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +0000552 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553 return 0;
554
555 return 1;
556}
557
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000558static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559compiler_exit_scope(struct compiler *c)
560{
561 int n;
562 PyObject *wrapper;
563
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000564 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565 compiler_unit_free(c->u);
566 /* Restore c->u to the parent unit. */
567 n = PyList_GET_SIZE(c->c_stack) - 1;
568 if (n >= 0) {
569 wrapper = PyList_GET_ITEM(c->c_stack, n);
570 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000571 assert(c->u);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000572 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000574 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575 compiler_unit_check(c->u);
576 }
577 else
578 c->u = NULL;
579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000580}
581
Guido van Rossumc2e20742006-02-27 22:32:47 +0000582/* Allocate a new "anonymous" local variable.
583 Used by list comprehensions and with statements.
584*/
585
586static PyObject *
587compiler_new_tmpname(struct compiler *c)
588{
589 char tmpname[256];
590 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
591 return PyString_FromString(tmpname);
592}
593
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594/* Allocate a new block and return a pointer to it.
595 Returns NULL on error.
596*/
597
598static basicblock *
599compiler_new_block(struct compiler *c)
600{
601 basicblock *b;
602 struct compiler_unit *u;
603
604 u = c->u;
605 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +0000606 if (b == NULL) {
607 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +0000609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000610 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612 b->b_list = u->u_blocks;
613 u->u_blocks = b;
614 return b;
615}
616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000617static basicblock *
618compiler_use_new_block(struct compiler *c)
619{
620 basicblock *block = compiler_new_block(c);
621 if (block == NULL)
622 return NULL;
623 c->u->u_curblock = block;
624 return block;
625}
626
627static basicblock *
628compiler_next_block(struct compiler *c)
629{
630 basicblock *block = compiler_new_block(c);
631 if (block == NULL)
632 return NULL;
633 c->u->u_curblock->b_next = block;
634 c->u->u_curblock = block;
635 return block;
636}
637
638static basicblock *
639compiler_use_next_block(struct compiler *c, basicblock *block)
640{
641 assert(block != NULL);
642 c->u->u_curblock->b_next = block;
643 c->u->u_curblock = block;
644 return block;
645}
646
647/* Returns the offset of the next instruction in the current block's
648 b_instr array. Resizes the b_instr as necessary.
649 Returns -1 on failure.
650 */
651
652static int
653compiler_next_instr(struct compiler *c, basicblock *b)
654{
655 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 b->b_instr = (struct instr *)PyObject_Malloc(
658 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659 if (b->b_instr == NULL) {
660 PyErr_NoMemory();
661 return -1;
662 }
663 b->b_ialloc = DEFAULT_BLOCK_SIZE;
664 memset((char *)b->b_instr, 0,
665 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000669 size_t oldsize, newsize;
670 oldsize = b->b_ialloc * sizeof(struct instr);
671 newsize = oldsize << 1;
672 if (newsize == 0) {
673 PyErr_NoMemory();
674 return -1;
675 }
676 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000678 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 if (tmp == NULL) {
680 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000681 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682 }
683 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
685 }
686 return b->b_iused++;
687}
688
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689/* Set the i_lineno member of the instruction at offse off if the
690 line number for the current expression/statement (?) has not
691 already been set. If it has been set, the call has no effect.
692
693 Every time a new node is b
694 */
695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000696static void
697compiler_set_lineno(struct compiler *c, int off)
698{
699 basicblock *b;
700 if (c->u->u_lineno_set)
701 return;
702 c->u->u_lineno_set = true;
703 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000704 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000705}
706
707static int
708opcode_stack_effect(int opcode, int oparg)
709{
710 switch (opcode) {
711 case POP_TOP:
712 return -1;
713 case ROT_TWO:
714 case ROT_THREE:
715 return 0;
716 case DUP_TOP:
717 return 1;
718 case ROT_FOUR:
719 return 0;
720
721 case UNARY_POSITIVE:
722 case UNARY_NEGATIVE:
723 case UNARY_NOT:
724 case UNARY_CONVERT:
725 case UNARY_INVERT:
726 return 0;
727
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000728 case LIST_APPEND:
729 return -2;
730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000731 case BINARY_POWER:
732 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733 case BINARY_MODULO:
734 case BINARY_ADD:
735 case BINARY_SUBTRACT:
736 case BINARY_SUBSCR:
737 case BINARY_FLOOR_DIVIDE:
738 case BINARY_TRUE_DIVIDE:
739 return -1;
740 case INPLACE_FLOOR_DIVIDE:
741 case INPLACE_TRUE_DIVIDE:
742 return -1;
743
744 case SLICE+0:
745 return 1;
746 case SLICE+1:
747 return 0;
748 case SLICE+2:
749 return 0;
750 case SLICE+3:
751 return -1;
752
753 case STORE_SLICE+0:
754 return -2;
755 case STORE_SLICE+1:
756 return -3;
757 case STORE_SLICE+2:
758 return -3;
759 case STORE_SLICE+3:
760 return -4;
761
762 case DELETE_SLICE+0:
763 return -1;
764 case DELETE_SLICE+1:
765 return -2;
766 case DELETE_SLICE+2:
767 return -2;
768 case DELETE_SLICE+3:
769 return -3;
770
771 case INPLACE_ADD:
772 case INPLACE_SUBTRACT:
773 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774 case INPLACE_MODULO:
775 return -1;
776 case STORE_SUBSCR:
777 return -3;
778 case DELETE_SUBSCR:
779 return -2;
780
781 case BINARY_LSHIFT:
782 case BINARY_RSHIFT:
783 case BINARY_AND:
784 case BINARY_XOR:
785 case BINARY_OR:
786 return -1;
787 case INPLACE_POWER:
788 return -1;
789 case GET_ITER:
790 return 0;
791
792 case PRINT_EXPR:
793 return -1;
794 case PRINT_ITEM:
795 return -1;
796 case PRINT_NEWLINE:
797 return 0;
798 case PRINT_ITEM_TO:
799 return -2;
800 case PRINT_NEWLINE_TO:
801 return -1;
802 case INPLACE_LSHIFT:
803 case INPLACE_RSHIFT:
804 case INPLACE_AND:
805 case INPLACE_XOR:
806 case INPLACE_OR:
807 return -1;
808 case BREAK_LOOP:
809 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +0000810 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +0000811 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812 case LOAD_LOCALS:
813 return 1;
814 case RETURN_VALUE:
815 return -1;
816 case IMPORT_STAR:
817 return -1;
818 case EXEC_STMT:
819 return -3;
820 case YIELD_VALUE:
821 return 0;
822
823 case POP_BLOCK:
824 return 0;
825 case END_FINALLY:
826 return -1; /* or -2 or -3 if exception occurred */
827 case BUILD_CLASS:
828 return -2;
829
830 case STORE_NAME:
831 return -1;
832 case DELETE_NAME:
833 return 0;
834 case UNPACK_SEQUENCE:
835 return oparg-1;
836 case FOR_ITER:
837 return 1;
838
839 case STORE_ATTR:
840 return -2;
841 case DELETE_ATTR:
842 return -1;
843 case STORE_GLOBAL:
844 return -1;
845 case DELETE_GLOBAL:
846 return 0;
847 case DUP_TOPX:
848 return oparg;
849 case LOAD_CONST:
850 return 1;
851 case LOAD_NAME:
852 return 1;
853 case BUILD_TUPLE:
854 case BUILD_LIST:
855 return 1-oparg;
856 case BUILD_MAP:
857 return 1;
858 case LOAD_ATTR:
859 return 0;
860 case COMPARE_OP:
861 return -1;
862 case IMPORT_NAME:
863 return 0;
864 case IMPORT_FROM:
865 return 1;
866
867 case JUMP_FORWARD:
868 case JUMP_IF_FALSE:
869 case JUMP_IF_TRUE:
870 case JUMP_ABSOLUTE:
871 return 0;
872
873 case LOAD_GLOBAL:
874 return 1;
875
876 case CONTINUE_LOOP:
877 return 0;
878 case SETUP_LOOP:
879 return 0;
880 case SETUP_EXCEPT:
881 case SETUP_FINALLY:
882 return 3; /* actually pushed by an exception */
883
884 case LOAD_FAST:
885 return 1;
886 case STORE_FAST:
887 return -1;
888 case DELETE_FAST:
889 return 0;
890
891 case RAISE_VARARGS:
892 return -oparg;
893#define NARGS(o) (((o) % 256) + 2*((o) / 256))
894 case CALL_FUNCTION:
895 return -NARGS(oparg);
896 case CALL_FUNCTION_VAR:
897 case CALL_FUNCTION_KW:
898 return -NARGS(oparg)-1;
899 case CALL_FUNCTION_VAR_KW:
900 return -NARGS(oparg)-2;
901#undef NARGS
902 case MAKE_FUNCTION:
903 return -oparg;
904 case BUILD_SLICE:
905 if (oparg == 3)
906 return -2;
907 else
908 return -1;
909
910 case MAKE_CLOSURE:
911 return -oparg;
912 case LOAD_CLOSURE:
913 return 1;
914 case LOAD_DEREF:
915 return 1;
916 case STORE_DEREF:
917 return -1;
918 default:
919 fprintf(stderr, "opcode = %d\n", opcode);
920 Py_FatalError("opcode_stack_effect()");
921
922 }
923 return 0; /* not reachable */
924}
925
926/* Add an opcode with no argument.
927 Returns 0 on failure, 1 on success.
928*/
929
930static int
931compiler_addop(struct compiler *c, int opcode)
932{
933 basicblock *b;
934 struct instr *i;
935 int off;
936 off = compiler_next_instr(c, c->u->u_curblock);
937 if (off < 0)
938 return 0;
939 b = c->u->u_curblock;
940 i = &b->b_instr[off];
941 i->i_opcode = opcode;
942 i->i_hasarg = 0;
943 if (opcode == RETURN_VALUE)
944 b->b_return = 1;
945 compiler_set_lineno(c, off);
946 return 1;
947}
948
949static int
950compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
951{
952 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000953 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000955 /* necessary to make sure types aren't coerced (e.g., int and long) */
956 t = PyTuple_Pack(2, o, o->ob_type);
957 if (t == NULL)
958 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
960 v = PyDict_GetItem(dict, t);
961 if (!v) {
962 arg = PyDict_Size(dict);
963 v = PyInt_FromLong(arg);
964 if (!v) {
965 Py_DECREF(t);
966 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000967 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (PyDict_SetItem(dict, t, v) < 0) {
969 Py_DECREF(t);
970 Py_DECREF(v);
971 return -1;
972 }
973 Py_DECREF(v);
974 }
975 else
976 arg = PyInt_AsLong(v);
977 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000978 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979}
980
981static int
982compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
983 PyObject *o)
984{
985 int arg = compiler_add_o(c, dict, o);
986 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000987 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 return compiler_addop_i(c, opcode, arg);
989}
990
991static int
992compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000993 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994{
995 int arg;
996 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
997 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999 arg = compiler_add_o(c, dict, mangled);
1000 Py_DECREF(mangled);
1001 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003 return compiler_addop_i(c, opcode, arg);
1004}
1005
1006/* Add an opcode with an integer argument.
1007 Returns 0 on failure, 1 on success.
1008*/
1009
1010static int
1011compiler_addop_i(struct compiler *c, int opcode, int oparg)
1012{
1013 struct instr *i;
1014 int off;
1015 off = compiler_next_instr(c, c->u->u_curblock);
1016 if (off < 0)
1017 return 0;
1018 i = &c->u->u_curblock->b_instr[off];
1019 i->i_opcode = opcode;
1020 i->i_oparg = oparg;
1021 i->i_hasarg = 1;
1022 compiler_set_lineno(c, off);
1023 return 1;
1024}
1025
1026static int
1027compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1028{
1029 struct instr *i;
1030 int off;
1031
1032 assert(b != NULL);
1033 off = compiler_next_instr(c, c->u->u_curblock);
1034 if (off < 0)
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 i = &c->u->u_curblock->b_instr[off];
1037 i->i_opcode = opcode;
1038 i->i_target = b;
1039 i->i_hasarg = 1;
1040 if (absolute)
1041 i->i_jabs = 1;
1042 else
1043 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001045 return 1;
1046}
1047
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001048/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1049 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001050 it as the current block. NEXT_BLOCK() also creates an implicit jump
1051 from the current block to the new block.
1052*/
1053
1054/* XXX The returns inside these macros make it impossible to decref
1055 objects created in the local function.
1056*/
1057
1058
1059#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001060 if (compiler_use_new_block((C)) == NULL) \
1061 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062}
1063
1064#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001065 if (compiler_next_block((C)) == NULL) \
1066 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067}
1068
1069#define ADDOP(C, OP) { \
1070 if (!compiler_addop((C), (OP))) \
1071 return 0; \
1072}
1073
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001074#define ADDOP_IN_SCOPE(C, OP) { \
1075 if (!compiler_addop((C), (OP))) { \
1076 compiler_exit_scope(c); \
1077 return 0; \
1078 } \
1079}
1080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081#define ADDOP_O(C, OP, O, TYPE) { \
1082 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1083 return 0; \
1084}
1085
1086#define ADDOP_NAME(C, OP, O, TYPE) { \
1087 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1088 return 0; \
1089}
1090
1091#define ADDOP_I(C, OP, O) { \
1092 if (!compiler_addop_i((C), (OP), (O))) \
1093 return 0; \
1094}
1095
1096#define ADDOP_JABS(C, OP, O) { \
1097 if (!compiler_addop_j((C), (OP), (O), 1)) \
1098 return 0; \
1099}
1100
1101#define ADDOP_JREL(C, OP, O) { \
1102 if (!compiler_addop_j((C), (OP), (O), 0)) \
1103 return 0; \
1104}
1105
1106/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1107 the ASDL name to synthesize the name of the C type and the visit function.
1108*/
1109
1110#define VISIT(C, TYPE, V) {\
1111 if (!compiler_visit_ ## TYPE((C), (V))) \
1112 return 0; \
1113}
1114
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001115#define VISIT_IN_SCOPE(C, TYPE, V) {\
1116 if (!compiler_visit_ ## TYPE((C), (V))) { \
1117 compiler_exit_scope(c); \
1118 return 0; \
1119 } \
1120}
1121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122#define VISIT_SLICE(C, V, CTX) {\
1123 if (!compiler_visit_slice((C), (V), (CTX))) \
1124 return 0; \
1125}
1126
1127#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001128 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001130 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132 if (!compiler_visit_ ## TYPE((C), elt)) \
1133 return 0; \
1134 } \
1135}
1136
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001137#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001138 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001139 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001140 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001141 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001142 if (!compiler_visit_ ## TYPE((C), elt)) { \
1143 compiler_exit_scope(c); \
1144 return 0; \
1145 } \
1146 } \
1147}
1148
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149static int
1150compiler_isdocstring(stmt_ty s)
1151{
1152 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return s->v.Expr.value->kind == Str_kind;
1155}
1156
1157/* Compile a sequence of statements, checking for a docstring. */
1158
1159static int
1160compiler_body(struct compiler *c, asdl_seq *stmts)
1161{
1162 int i = 0;
1163 stmt_ty st;
1164
1165 if (!asdl_seq_LEN(stmts))
1166 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001168 if (compiler_isdocstring(st)) {
1169 i = 1;
1170 VISIT(c, expr, st->v.Expr.value);
1171 if (!compiler_nameop(c, __doc__, Store))
1172 return 0;
1173 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001174 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 return 1;
1177}
1178
1179static PyCodeObject *
1180compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001181{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 static PyObject *module;
1185 if (!module) {
1186 module = PyString_FromString("<module>");
1187 if (!module)
1188 return NULL;
1189 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1191 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001192 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 switch (mod->kind) {
1194 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001195 if (!compiler_body(c, mod->v.Module.body)) {
1196 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 break;
1200 case Interactive_kind:
1201 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001202 VISIT_SEQ_IN_SCOPE(c, stmt,
1203 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204 break;
1205 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001206 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001207 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 break;
1209 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001210 PyErr_SetString(PyExc_SystemError,
1211 "suite should not be possible");
1212 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001213 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001214 PyErr_Format(PyExc_SystemError,
1215 "module kind %d should not be possible",
1216 mod->kind);
1217 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001219 co = assemble(c, addNone);
1220 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001221 return co;
1222}
1223
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224/* The test for LOCAL must come before the test for FREE in order to
1225 handle classes where name is both local and free. The local var is
1226 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001227*/
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229static int
1230get_ref_type(struct compiler *c, PyObject *name)
1231{
1232 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001233 if (scope == 0) {
1234 char buf[350];
1235 PyOS_snprintf(buf, sizeof(buf),
1236 "unknown scope for %.100s in %.100s(%s) in %s\n"
1237 "symbols: %s\nlocals: %s\nglobals: %s\n",
1238 PyString_AS_STRING(name),
1239 PyString_AS_STRING(c->u->u_name),
1240 PyObject_REPR(c->u->u_ste->ste_id),
1241 c->c_filename,
1242 PyObject_REPR(c->u->u_ste->ste_symbols),
1243 PyObject_REPR(c->u->u_varnames),
1244 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001246 Py_FatalError(buf);
1247 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001248
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001249 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250}
1251
1252static int
1253compiler_lookup_arg(PyObject *dict, PyObject *name)
1254{
1255 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001257 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001258 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001260 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001261 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001263 return PyInt_AS_LONG(v);
1264}
1265
1266static int
1267compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1268{
1269 int i, free = PyCode_GetNumFree(co);
1270 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1272 ADDOP_I(c, MAKE_FUNCTION, args);
1273 return 1;
1274 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 for (i = 0; i < free; ++i) {
1276 /* Bypass com_addop_varname because it will generate
1277 LOAD_DEREF but LOAD_CLOSURE is needed.
1278 */
1279 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1280 int arg, reftype;
1281
1282 /* Special case: If a class contains a method with a
1283 free variable that has the same name as a method,
1284 the name will be considered free *and* local in the
1285 class. It should be handled by the closure, as
1286 well as by the normal name loookup logic.
1287 */
1288 reftype = get_ref_type(c, name);
1289 if (reftype == CELL)
1290 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1291 else /* (reftype == FREE) */
1292 arg = compiler_lookup_arg(c->u->u_freevars, name);
1293 if (arg == -1) {
1294 printf("lookup %s in %s %d %d\n"
1295 "freevars of %s: %s\n",
1296 PyObject_REPR(name),
1297 PyString_AS_STRING(c->u->u_name),
1298 reftype, arg,
1299 PyString_AS_STRING(co->co_name),
1300 PyObject_REPR(co->co_freevars));
1301 Py_FatalError("compiler_make_closure()");
1302 }
1303 ADDOP_I(c, LOAD_CLOSURE, arg);
1304 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001305 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001307 ADDOP_I(c, MAKE_CLOSURE, args);
1308 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001309}
1310
1311static int
1312compiler_decorators(struct compiler *c, asdl_seq* decos)
1313{
1314 int i;
1315
1316 if (!decos)
1317 return 1;
1318
1319 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001320 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001321 }
1322 return 1;
1323}
1324
1325static int
1326compiler_arguments(struct compiler *c, arguments_ty args)
1327{
1328 int i;
1329 int n = asdl_seq_LEN(args->args);
1330 /* Correctly handle nested argument lists */
1331 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001332 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001333 if (arg->kind == Tuple_kind) {
1334 PyObject *id = PyString_FromFormat(".%d", i);
1335 if (id == NULL) {
1336 return 0;
1337 }
1338 if (!compiler_nameop(c, id, Load)) {
1339 Py_DECREF(id);
1340 return 0;
1341 }
1342 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001343 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001344 }
1345 }
1346 return 1;
1347}
1348
1349static int
1350compiler_function(struct compiler *c, stmt_ty s)
1351{
1352 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001353 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 arguments_ty args = s->v.FunctionDef.args;
1355 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001356 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 int i, n, docstring;
1358
1359 assert(s->kind == FunctionDef_kind);
1360
1361 if (!compiler_decorators(c, decos))
1362 return 0;
1363 if (args->defaults)
1364 VISIT_SEQ(c, expr, args->defaults);
1365 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1366 s->lineno))
1367 return 0;
1368
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001369 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001370 docstring = compiler_isdocstring(st);
1371 if (docstring)
1372 first_const = st->v.Expr.value->v.Str.s;
1373 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001374 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001375 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001376 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001378 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 compiler_arguments(c, args);
1380
1381 c->u->u_argcount = asdl_seq_LEN(args->args);
1382 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001383 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001385 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1386 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387 }
1388 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001389 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 if (co == NULL)
1391 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001392
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001393 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001394 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395
1396 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1397 ADDOP_I(c, CALL_FUNCTION, 1);
1398 }
1399
1400 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1401}
1402
1403static int
1404compiler_class(struct compiler *c, stmt_ty s)
1405{
1406 int n;
1407 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001408 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001409 /* push class name on stack, needed by BUILD_CLASS */
1410 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1411 /* push the tuple of base classes on the stack */
1412 n = asdl_seq_LEN(s->v.ClassDef.bases);
1413 if (n > 0)
1414 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1415 ADDOP_I(c, BUILD_TUPLE, n);
1416 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1417 s->lineno))
1418 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001419 c->u->u_private = s->v.ClassDef.name;
1420 Py_INCREF(c->u->u_private);
1421 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001422 if (!str || !compiler_nameop(c, str, Load)) {
1423 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001424 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001426 }
1427
1428 Py_DECREF(str);
1429 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430 if (!str || !compiler_nameop(c, str, Store)) {
1431 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001432 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001434 }
1435 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001437 if (!compiler_body(c, s->v.ClassDef.body)) {
1438 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001439 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001440 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001442 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
1443 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001445 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446 if (co == NULL)
1447 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001449 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00001450 Py_DECREF(co);
1451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452 ADDOP_I(c, CALL_FUNCTION, 0);
1453 ADDOP(c, BUILD_CLASS);
1454 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
1455 return 0;
1456 return 1;
1457}
1458
1459static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001460compiler_ifexp(struct compiler *c, expr_ty e)
1461{
1462 basicblock *end, *next;
1463
1464 assert(e->kind == IfExp_kind);
1465 end = compiler_new_block(c);
1466 if (end == NULL)
1467 return 0;
1468 next = compiler_new_block(c);
1469 if (next == NULL)
1470 return 0;
1471 VISIT(c, expr, e->v.IfExp.test);
1472 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1473 ADDOP(c, POP_TOP);
1474 VISIT(c, expr, e->v.IfExp.body);
1475 ADDOP_JREL(c, JUMP_FORWARD, end);
1476 compiler_use_next_block(c, next);
1477 ADDOP(c, POP_TOP);
1478 VISIT(c, expr, e->v.IfExp.orelse);
1479 compiler_use_next_block(c, end);
1480 return 1;
1481}
1482
1483static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484compiler_lambda(struct compiler *c, expr_ty e)
1485{
1486 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001487 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001488 arguments_ty args = e->v.Lambda.args;
1489 assert(e->kind == Lambda_kind);
1490
Nick Coghlan944d3eb2005-11-16 12:46:55 +00001491 if (!name) {
1492 name = PyString_InternFromString("<lambda>");
1493 if (!name)
1494 return 0;
1495 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496
1497 if (args->defaults)
1498 VISIT_SEQ(c, expr, args->defaults);
1499 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
1500 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00001501
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001502 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 compiler_arguments(c, args);
1504
1505 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001506 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
1507 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001509 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510 if (co == NULL)
1511 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001513 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001514 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515
1516 return 1;
1517}
1518
1519static int
1520compiler_print(struct compiler *c, stmt_ty s)
1521{
1522 int i, n;
1523 bool dest;
1524
1525 assert(s->kind == Print_kind);
1526 n = asdl_seq_LEN(s->v.Print.values);
1527 dest = false;
1528 if (s->v.Print.dest) {
1529 VISIT(c, expr, s->v.Print.dest);
1530 dest = true;
1531 }
1532 for (i = 0; i < n; i++) {
1533 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
1534 if (dest) {
1535 ADDOP(c, DUP_TOP);
1536 VISIT(c, expr, e);
1537 ADDOP(c, ROT_TWO);
1538 ADDOP(c, PRINT_ITEM_TO);
1539 }
1540 else {
1541 VISIT(c, expr, e);
1542 ADDOP(c, PRINT_ITEM);
1543 }
1544 }
1545 if (s->v.Print.nl) {
1546 if (dest)
1547 ADDOP(c, PRINT_NEWLINE_TO)
1548 else
1549 ADDOP(c, PRINT_NEWLINE)
1550 }
1551 else if (dest)
1552 ADDOP(c, POP_TOP);
1553 return 1;
1554}
1555
1556static int
1557compiler_if(struct compiler *c, stmt_ty s)
1558{
1559 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001560 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561 assert(s->kind == If_kind);
1562 end = compiler_new_block(c);
1563 if (end == NULL)
1564 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001565 next = compiler_new_block(c);
1566 if (next == NULL)
1567 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001568
1569 constant = expr_constant(s->v.If.test);
1570 /* constant = 0: "if 0"
1571 * constant = 1: "if 1", "if 2", ...
1572 * constant = -1: rest */
1573 if (constant == 0) {
1574 if (s->v.If.orelse)
1575 VISIT_SEQ(c, stmt, s->v.If.orelse);
1576 } else if (constant == 1) {
1577 VISIT_SEQ(c, stmt, s->v.If.body);
1578 } else {
1579 VISIT(c, expr, s->v.If.test);
1580 ADDOP_JREL(c, JUMP_IF_FALSE, next);
1581 ADDOP(c, POP_TOP);
1582 VISIT_SEQ(c, stmt, s->v.If.body);
1583 ADDOP_JREL(c, JUMP_FORWARD, end);
1584 compiler_use_next_block(c, next);
1585 ADDOP(c, POP_TOP);
1586 if (s->v.If.orelse)
1587 VISIT_SEQ(c, stmt, s->v.If.orelse);
1588 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589 compiler_use_next_block(c, end);
1590 return 1;
1591}
1592
1593static int
1594compiler_for(struct compiler *c, stmt_ty s)
1595{
1596 basicblock *start, *cleanup, *end;
1597
1598 start = compiler_new_block(c);
1599 cleanup = compiler_new_block(c);
1600 end = compiler_new_block(c);
1601 if (start == NULL || end == NULL || cleanup == NULL)
1602 return 0;
1603 ADDOP_JREL(c, SETUP_LOOP, end);
1604 if (!compiler_push_fblock(c, LOOP, start))
1605 return 0;
1606 VISIT(c, expr, s->v.For.iter);
1607 ADDOP(c, GET_ITER);
1608 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001609 /* XXX(nnorwitz): is there a better way to handle this?
1610 for loops are special, we want to be able to trace them
1611 each time around, so we need to set an extra line number. */
1612 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613 ADDOP_JREL(c, FOR_ITER, cleanup);
1614 VISIT(c, expr, s->v.For.target);
1615 VISIT_SEQ(c, stmt, s->v.For.body);
1616 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
1617 compiler_use_next_block(c, cleanup);
1618 ADDOP(c, POP_BLOCK);
1619 compiler_pop_fblock(c, LOOP, start);
1620 VISIT_SEQ(c, stmt, s->v.For.orelse);
1621 compiler_use_next_block(c, end);
1622 return 1;
1623}
1624
1625static int
1626compiler_while(struct compiler *c, stmt_ty s)
1627{
1628 basicblock *loop, *orelse, *end, *anchor = NULL;
1629 int constant = expr_constant(s->v.While.test);
1630
1631 if (constant == 0)
1632 return 1;
1633 loop = compiler_new_block(c);
1634 end = compiler_new_block(c);
1635 if (constant == -1) {
1636 anchor = compiler_new_block(c);
1637 if (anchor == NULL)
1638 return 0;
1639 }
1640 if (loop == NULL || end == NULL)
1641 return 0;
1642 if (s->v.While.orelse) {
1643 orelse = compiler_new_block(c);
1644 if (orelse == NULL)
1645 return 0;
1646 }
1647 else
1648 orelse = NULL;
1649
1650 ADDOP_JREL(c, SETUP_LOOP, end);
1651 compiler_use_next_block(c, loop);
1652 if (!compiler_push_fblock(c, LOOP, loop))
1653 return 0;
1654 if (constant == -1) {
1655 VISIT(c, expr, s->v.While.test);
1656 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
1657 ADDOP(c, POP_TOP);
1658 }
1659 VISIT_SEQ(c, stmt, s->v.While.body);
1660 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
1661
1662 /* XXX should the two POP instructions be in a separate block
1663 if there is no else clause ?
1664 */
1665
1666 if (constant == -1) {
1667 compiler_use_next_block(c, anchor);
1668 ADDOP(c, POP_TOP);
1669 ADDOP(c, POP_BLOCK);
1670 }
1671 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001672 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673 VISIT_SEQ(c, stmt, s->v.While.orelse);
1674 compiler_use_next_block(c, end);
1675
1676 return 1;
1677}
1678
1679static int
1680compiler_continue(struct compiler *c)
1681{
1682 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
1683 int i;
1684
1685 if (!c->u->u_nfblocks)
1686 return compiler_error(c, LOOP_ERROR_MSG);
1687 i = c->u->u_nfblocks - 1;
1688 switch (c->u->u_fblock[i].fb_type) {
1689 case LOOP:
1690 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
1691 break;
1692 case EXCEPT:
1693 case FINALLY_TRY:
1694 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
1695 ;
1696 if (i == -1)
1697 return compiler_error(c, LOOP_ERROR_MSG);
1698 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
1699 break;
1700 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001701 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 "'continue' not supported inside 'finally' clause");
1703 }
1704
1705 return 1;
1706}
1707
1708/* Code generated for "try: <body> finally: <finalbody>" is as follows:
1709
1710 SETUP_FINALLY L
1711 <code for body>
1712 POP_BLOCK
1713 LOAD_CONST <None>
1714 L: <code for finalbody>
1715 END_FINALLY
1716
1717 The special instructions use the block stack. Each block
1718 stack entry contains the instruction that created it (here
1719 SETUP_FINALLY), the level of the value stack at the time the
1720 block stack entry was created, and a label (here L).
1721
1722 SETUP_FINALLY:
1723 Pushes the current value stack level and the label
1724 onto the block stack.
1725 POP_BLOCK:
1726 Pops en entry from the block stack, and pops the value
1727 stack until its level is the same as indicated on the
1728 block stack. (The label is ignored.)
1729 END_FINALLY:
1730 Pops a variable number of entries from the *value* stack
1731 and re-raises the exception they specify. The number of
1732 entries popped depends on the (pseudo) exception type.
1733
1734 The block stack is unwound when an exception is raised:
1735 when a SETUP_FINALLY entry is found, the exception is pushed
1736 onto the value stack (and the exception condition is cleared),
1737 and the interpreter jumps to the label gotten from the block
1738 stack.
1739*/
1740
1741static int
1742compiler_try_finally(struct compiler *c, stmt_ty s)
1743{
1744 basicblock *body, *end;
1745 body = compiler_new_block(c);
1746 end = compiler_new_block(c);
1747 if (body == NULL || end == NULL)
1748 return 0;
1749
1750 ADDOP_JREL(c, SETUP_FINALLY, end);
1751 compiler_use_next_block(c, body);
1752 if (!compiler_push_fblock(c, FINALLY_TRY, body))
1753 return 0;
1754 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
1755 ADDOP(c, POP_BLOCK);
1756 compiler_pop_fblock(c, FINALLY_TRY, body);
1757
1758 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1759 compiler_use_next_block(c, end);
1760 if (!compiler_push_fblock(c, FINALLY_END, end))
1761 return 0;
1762 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
1763 ADDOP(c, END_FINALLY);
1764 compiler_pop_fblock(c, FINALLY_END, end);
1765
1766 return 1;
1767}
1768
1769/*
1770 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
1771 (The contents of the value stack is shown in [], with the top
1772 at the right; 'tb' is trace-back info, 'val' the exception's
1773 associated value, and 'exc' the exception.)
1774
1775 Value stack Label Instruction Argument
1776 [] SETUP_EXCEPT L1
1777 [] <code for S>
1778 [] POP_BLOCK
1779 [] JUMP_FORWARD L0
1780
1781 [tb, val, exc] L1: DUP )
1782 [tb, val, exc, exc] <evaluate E1> )
1783 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
1784 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
1785 [tb, val, exc, 1] POP )
1786 [tb, val, exc] POP
1787 [tb, val] <assign to V1> (or POP if no V1)
1788 [tb] POP
1789 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001790 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791
1792 [tb, val, exc, 0] L2: POP
1793 [tb, val, exc] DUP
1794 .............................etc.......................
1795
1796 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001797 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798
1799 [] L0: <next statement>
1800
1801 Of course, parts are not generated if Vi or Ei is not present.
1802*/
1803static int
1804compiler_try_except(struct compiler *c, stmt_ty s)
1805{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001806 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 int i, n;
1808
1809 body = compiler_new_block(c);
1810 except = compiler_new_block(c);
1811 orelse = compiler_new_block(c);
1812 end = compiler_new_block(c);
1813 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
1814 return 0;
1815 ADDOP_JREL(c, SETUP_EXCEPT, except);
1816 compiler_use_next_block(c, body);
1817 if (!compiler_push_fblock(c, EXCEPT, body))
1818 return 0;
1819 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
1820 ADDOP(c, POP_BLOCK);
1821 compiler_pop_fblock(c, EXCEPT, body);
1822 ADDOP_JREL(c, JUMP_FORWARD, orelse);
1823 n = asdl_seq_LEN(s->v.TryExcept.handlers);
1824 compiler_use_next_block(c, except);
1825 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001826 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 s->v.TryExcept.handlers, i);
1828 if (!handler->type && i < n-1)
1829 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001830 c->u->u_lineno_set = false;
1831 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 except = compiler_new_block(c);
1833 if (except == NULL)
1834 return 0;
1835 if (handler->type) {
1836 ADDOP(c, DUP_TOP);
1837 VISIT(c, expr, handler->type);
1838 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
1839 ADDOP_JREL(c, JUMP_IF_FALSE, except);
1840 ADDOP(c, POP_TOP);
1841 }
1842 ADDOP(c, POP_TOP);
1843 if (handler->name) {
1844 VISIT(c, expr, handler->name);
1845 }
1846 else {
1847 ADDOP(c, POP_TOP);
1848 }
1849 ADDOP(c, POP_TOP);
1850 VISIT_SEQ(c, stmt, handler->body);
1851 ADDOP_JREL(c, JUMP_FORWARD, end);
1852 compiler_use_next_block(c, except);
1853 if (handler->type)
1854 ADDOP(c, POP_TOP);
1855 }
1856 ADDOP(c, END_FINALLY);
1857 compiler_use_next_block(c, orelse);
1858 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
1859 compiler_use_next_block(c, end);
1860 return 1;
1861}
1862
1863static int
1864compiler_import_as(struct compiler *c, identifier name, identifier asname)
1865{
1866 /* The IMPORT_NAME opcode was already generated. This function
1867 merely needs to bind the result to a name.
1868
1869 If there is a dot in name, we need to split it and emit a
1870 LOAD_ATTR for each name.
1871 */
1872 const char *src = PyString_AS_STRING(name);
1873 const char *dot = strchr(src, '.');
1874 if (dot) {
1875 /* Consume the base module name to get the first attribute */
1876 src = dot + 1;
1877 while (dot) {
1878 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00001879 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00001881 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001883 if (!attr)
1884 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00001886 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 src = dot + 1;
1888 }
1889 }
1890 return compiler_nameop(c, asname, Store);
1891}
1892
1893static int
1894compiler_import(struct compiler *c, stmt_ty s)
1895{
1896 /* The Import node stores a module name like a.b.c as a single
1897 string. This is convenient for all cases except
1898 import a.b.c as d
1899 where we need to parse that string to extract the individual
1900 module names.
1901 XXX Perhaps change the representation to make this case simpler?
1902 */
1903 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001906 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001908 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909
Guido van Rossum45aecf42006-03-15 04:58:47 +00001910 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001911 if (level == NULL)
1912 return 0;
1913
1914 ADDOP_O(c, LOAD_CONST, level, consts);
1915 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1917 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
1918
1919 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00001920 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001921 if (!r)
1922 return r;
1923 }
1924 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925 identifier tmp = alias->name;
1926 const char *base = PyString_AS_STRING(alias->name);
1927 char *dot = strchr(base, '.');
1928 if (dot)
1929 tmp = PyString_FromStringAndSize(base,
1930 dot - base);
1931 r = compiler_nameop(c, tmp, Store);
1932 if (dot) {
1933 Py_DECREF(tmp);
1934 }
1935 if (!r)
1936 return r;
1937 }
1938 }
1939 return 1;
1940}
1941
1942static int
1943compiler_from_import(struct compiler *c, stmt_ty s)
1944{
1945 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
1947 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001948 PyObject *level;
1949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950 if (!names)
1951 return 0;
1952
Guido van Rossum45aecf42006-03-15 04:58:47 +00001953 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001954 if (!level) {
1955 Py_DECREF(names);
1956 return 0;
1957 }
1958
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 /* build up the names */
1960 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001961 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 Py_INCREF(alias->name);
1963 PyTuple_SET_ITEM(names, i, alias->name);
1964 }
1965
1966 if (s->lineno > c->c_future->ff_lineno) {
1967 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
1968 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00001969 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970 Py_DECREF(names);
1971 return compiler_error(c,
1972 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001973 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974
1975 }
1976 }
1977
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001978 ADDOP_O(c, LOAD_CONST, level, consts);
1979 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001981 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
1983 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001984 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 identifier store_name;
1986
1987 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
1988 assert(n == 1);
1989 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00001990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 }
1992
1993 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
1994 store_name = alias->name;
1995 if (alias->asname)
1996 store_name = alias->asname;
1997
1998 if (!compiler_nameop(c, store_name, Store)) {
1999 Py_DECREF(names);
2000 return 0;
2001 }
2002 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002003 /* remove imported module */
2004 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 return 1;
2006}
2007
2008static int
2009compiler_assert(struct compiler *c, stmt_ty s)
2010{
2011 static PyObject *assertion_error = NULL;
2012 basicblock *end;
2013
2014 if (Py_OptimizeFlag)
2015 return 1;
2016 if (assertion_error == NULL) {
2017 assertion_error = PyString_FromString("AssertionError");
2018 if (assertion_error == NULL)
2019 return 0;
2020 }
2021 VISIT(c, expr, s->v.Assert.test);
2022 end = compiler_new_block(c);
2023 if (end == NULL)
2024 return 0;
2025 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2026 ADDOP(c, POP_TOP);
2027 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2028 if (s->v.Assert.msg) {
2029 VISIT(c, expr, s->v.Assert.msg);
2030 ADDOP_I(c, RAISE_VARARGS, 2);
2031 }
2032 else {
2033 ADDOP_I(c, RAISE_VARARGS, 1);
2034 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002035 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 ADDOP(c, POP_TOP);
2037 return 1;
2038}
2039
2040static int
2041compiler_visit_stmt(struct compiler *c, stmt_ty s)
2042{
2043 int i, n;
2044
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002045 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002046 c->u->u_lineno = s->lineno;
2047 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002048
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002050 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002051 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002054 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 if (c->u->u_ste->ste_type != FunctionBlock)
2056 return compiler_error(c, "'return' outside function");
2057 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 VISIT(c, expr, s->v.Return.value);
2059 }
2060 else
2061 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2062 ADDOP(c, RETURN_VALUE);
2063 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002064 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 VISIT_SEQ(c, expr, s->v.Delete.targets)
2066 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 n = asdl_seq_LEN(s->v.Assign.targets);
2069 VISIT(c, expr, s->v.Assign.value);
2070 for (i = 0; i < n; i++) {
2071 if (i < n - 1)
2072 ADDOP(c, DUP_TOP);
2073 VISIT(c, expr,
2074 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2075 }
2076 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002083 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002086 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002087 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088 n = 0;
2089 if (s->v.Raise.type) {
2090 VISIT(c, expr, s->v.Raise.type);
2091 n++;
2092 if (s->v.Raise.inst) {
2093 VISIT(c, expr, s->v.Raise.inst);
2094 n++;
2095 if (s->v.Raise.tback) {
2096 VISIT(c, expr, s->v.Raise.tback);
2097 n++;
2098 }
2099 }
2100 }
2101 ADDOP_I(c, RAISE_VARARGS, n);
2102 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002107 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002108 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002109 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002111 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002113 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002114 VISIT(c, expr, s->v.Exec.body);
2115 if (s->v.Exec.globals) {
2116 VISIT(c, expr, s->v.Exec.globals);
2117 if (s->v.Exec.locals) {
2118 VISIT(c, expr, s->v.Exec.locals);
2119 } else {
2120 ADDOP(c, DUP_TOP);
2121 }
2122 } else {
2123 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2124 ADDOP(c, DUP_TOP);
2125 }
2126 ADDOP(c, EXEC_STMT);
2127 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002128 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002130 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002131 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002132 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133 ADDOP(c, PRINT_EXPR);
2134 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002135 else if (s->v.Expr.value->kind != Str_kind &&
2136 s->v.Expr.value->kind != Num_kind) {
2137 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002138 ADDOP(c, POP_TOP);
2139 }
2140 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002141 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002142 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002143 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002144 if (!c->u->u_nfblocks)
2145 return compiler_error(c, "'break' outside loop");
2146 ADDOP(c, BREAK_LOOP);
2147 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002148 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002150 case With_kind:
2151 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 }
2153 return 1;
2154}
2155
2156static int
2157unaryop(unaryop_ty op)
2158{
2159 switch (op) {
2160 case Invert:
2161 return UNARY_INVERT;
2162 case Not:
2163 return UNARY_NOT;
2164 case UAdd:
2165 return UNARY_POSITIVE;
2166 case USub:
2167 return UNARY_NEGATIVE;
2168 }
2169 return 0;
2170}
2171
2172static int
2173binop(struct compiler *c, operator_ty op)
2174{
2175 switch (op) {
2176 case Add:
2177 return BINARY_ADD;
2178 case Sub:
2179 return BINARY_SUBTRACT;
2180 case Mult:
2181 return BINARY_MULTIPLY;
2182 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002183 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002184 case Mod:
2185 return BINARY_MODULO;
2186 case Pow:
2187 return BINARY_POWER;
2188 case LShift:
2189 return BINARY_LSHIFT;
2190 case RShift:
2191 return BINARY_RSHIFT;
2192 case BitOr:
2193 return BINARY_OR;
2194 case BitXor:
2195 return BINARY_XOR;
2196 case BitAnd:
2197 return BINARY_AND;
2198 case FloorDiv:
2199 return BINARY_FLOOR_DIVIDE;
2200 }
2201 return 0;
2202}
2203
2204static int
2205cmpop(cmpop_ty op)
2206{
2207 switch (op) {
2208 case Eq:
2209 return PyCmp_EQ;
2210 case NotEq:
2211 return PyCmp_NE;
2212 case Lt:
2213 return PyCmp_LT;
2214 case LtE:
2215 return PyCmp_LE;
2216 case Gt:
2217 return PyCmp_GT;
2218 case GtE:
2219 return PyCmp_GE;
2220 case Is:
2221 return PyCmp_IS;
2222 case IsNot:
2223 return PyCmp_IS_NOT;
2224 case In:
2225 return PyCmp_IN;
2226 case NotIn:
2227 return PyCmp_NOT_IN;
2228 }
2229 return PyCmp_BAD;
2230}
2231
2232static int
2233inplace_binop(struct compiler *c, operator_ty op)
2234{
2235 switch (op) {
2236 case Add:
2237 return INPLACE_ADD;
2238 case Sub:
2239 return INPLACE_SUBTRACT;
2240 case Mult:
2241 return INPLACE_MULTIPLY;
2242 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002243 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 case Mod:
2245 return INPLACE_MODULO;
2246 case Pow:
2247 return INPLACE_POWER;
2248 case LShift:
2249 return INPLACE_LSHIFT;
2250 case RShift:
2251 return INPLACE_RSHIFT;
2252 case BitOr:
2253 return INPLACE_OR;
2254 case BitXor:
2255 return INPLACE_XOR;
2256 case BitAnd:
2257 return INPLACE_AND;
2258 case FloorDiv:
2259 return INPLACE_FLOOR_DIVIDE;
2260 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002261 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002262 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 return 0;
2264}
2265
2266static int
2267compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2268{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002269 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2271
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002272 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002273 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 /* XXX AugStore isn't used anywhere! */
2275
2276 /* First check for assignment to __debug__. Param? */
2277 if ((ctx == Store || ctx == AugStore || ctx == Del)
2278 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2279 return compiler_error(c, "can not assign to __debug__");
2280 }
2281
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002282 mangled = _Py_Mangle(c->u->u_private, name);
2283 if (!mangled)
2284 return 0;
2285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286 op = 0;
2287 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002288 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289 switch (scope) {
2290 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002291 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292 optype = OP_DEREF;
2293 break;
2294 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002295 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296 optype = OP_DEREF;
2297 break;
2298 case LOCAL:
2299 if (c->u->u_ste->ste_type == FunctionBlock)
2300 optype = OP_FAST;
2301 break;
2302 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002303 if (c->u->u_ste->ste_type == FunctionBlock &&
2304 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305 optype = OP_GLOBAL;
2306 break;
2307 case GLOBAL_EXPLICIT:
2308 optype = OP_GLOBAL;
2309 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002310 default:
2311 /* scope can be 0 */
2312 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313 }
2314
2315 /* XXX Leave assert here, but handle __doc__ and the like better */
2316 assert(scope || PyString_AS_STRING(name)[0] == '_');
2317
2318 switch (optype) {
2319 case OP_DEREF:
2320 switch (ctx) {
2321 case Load: op = LOAD_DEREF; break;
2322 case Store: op = STORE_DEREF; break;
2323 case AugLoad:
2324 case AugStore:
2325 break;
2326 case Del:
2327 PyErr_Format(PyExc_SyntaxError,
2328 "can not delete variable '%s' referenced "
2329 "in nested scope",
2330 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002331 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002334 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002335 PyErr_SetString(PyExc_SystemError,
2336 "param invalid for deref variable");
2337 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338 }
2339 break;
2340 case OP_FAST:
2341 switch (ctx) {
2342 case Load: op = LOAD_FAST; break;
2343 case Store: op = STORE_FAST; break;
2344 case Del: op = DELETE_FAST; break;
2345 case AugLoad:
2346 case AugStore:
2347 break;
2348 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002349 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002350 PyErr_SetString(PyExc_SystemError,
2351 "param invalid for local variable");
2352 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002354 ADDOP_O(c, op, mangled, varnames);
2355 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356 return 1;
2357 case OP_GLOBAL:
2358 switch (ctx) {
2359 case Load: op = LOAD_GLOBAL; break;
2360 case Store: op = STORE_GLOBAL; break;
2361 case Del: op = DELETE_GLOBAL; break;
2362 case AugLoad:
2363 case AugStore:
2364 break;
2365 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002366 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002367 PyErr_SetString(PyExc_SystemError,
2368 "param invalid for global variable");
2369 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370 }
2371 break;
2372 case OP_NAME:
2373 switch (ctx) {
2374 case Load: op = LOAD_NAME; break;
2375 case Store: op = STORE_NAME; break;
2376 case Del: op = DELETE_NAME; break;
2377 case AugLoad:
2378 case AugStore:
2379 break;
2380 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002381 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002382 PyErr_SetString(PyExc_SystemError,
2383 "param invalid for name variable");
2384 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385 }
2386 break;
2387 }
2388
2389 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002390 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002391 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002392 if (arg < 0)
2393 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002394 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395}
2396
2397static int
2398compiler_boolop(struct compiler *c, expr_ty e)
2399{
2400 basicblock *end;
2401 int jumpi, i, n;
2402 asdl_seq *s;
2403
2404 assert(e->kind == BoolOp_kind);
2405 if (e->v.BoolOp.op == And)
2406 jumpi = JUMP_IF_FALSE;
2407 else
2408 jumpi = JUMP_IF_TRUE;
2409 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002410 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002411 return 0;
2412 s = e->v.BoolOp.values;
2413 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002414 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002416 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 ADDOP_JREL(c, jumpi, end);
2418 ADDOP(c, POP_TOP)
2419 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002420 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421 compiler_use_next_block(c, end);
2422 return 1;
2423}
2424
2425static int
2426compiler_list(struct compiler *c, expr_ty e)
2427{
2428 int n = asdl_seq_LEN(e->v.List.elts);
2429 if (e->v.List.ctx == Store) {
2430 ADDOP_I(c, UNPACK_SEQUENCE, n);
2431 }
2432 VISIT_SEQ(c, expr, e->v.List.elts);
2433 if (e->v.List.ctx == Load) {
2434 ADDOP_I(c, BUILD_LIST, n);
2435 }
2436 return 1;
2437}
2438
2439static int
2440compiler_tuple(struct compiler *c, expr_ty e)
2441{
2442 int n = asdl_seq_LEN(e->v.Tuple.elts);
2443 if (e->v.Tuple.ctx == Store) {
2444 ADDOP_I(c, UNPACK_SEQUENCE, n);
2445 }
2446 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2447 if (e->v.Tuple.ctx == Load) {
2448 ADDOP_I(c, BUILD_TUPLE, n);
2449 }
2450 return 1;
2451}
2452
2453static int
2454compiler_compare(struct compiler *c, expr_ty e)
2455{
2456 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002457 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458
2459 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
2460 VISIT(c, expr, e->v.Compare.left);
2461 n = asdl_seq_LEN(e->v.Compare.ops);
2462 assert(n > 0);
2463 if (n > 1) {
2464 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002465 if (cleanup == NULL)
2466 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002467 VISIT(c, expr,
2468 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469 }
2470 for (i = 1; i < n; i++) {
2471 ADDOP(c, DUP_TOP);
2472 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002474 cmpop((cmpop_ty)(asdl_seq_GET(
2475 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
2477 NEXT_BLOCK(c);
2478 ADDOP(c, POP_TOP);
2479 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480 VISIT(c, expr,
2481 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002483 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002485 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 if (n > 1) {
2487 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002488 if (end == NULL)
2489 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490 ADDOP_JREL(c, JUMP_FORWARD, end);
2491 compiler_use_next_block(c, cleanup);
2492 ADDOP(c, ROT_TWO);
2493 ADDOP(c, POP_TOP);
2494 compiler_use_next_block(c, end);
2495 }
2496 return 1;
2497}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002498#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499
2500static int
2501compiler_call(struct compiler *c, expr_ty e)
2502{
2503 int n, code = 0;
2504
2505 VISIT(c, expr, e->v.Call.func);
2506 n = asdl_seq_LEN(e->v.Call.args);
2507 VISIT_SEQ(c, expr, e->v.Call.args);
2508 if (e->v.Call.keywords) {
2509 VISIT_SEQ(c, keyword, e->v.Call.keywords);
2510 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
2511 }
2512 if (e->v.Call.starargs) {
2513 VISIT(c, expr, e->v.Call.starargs);
2514 code |= 1;
2515 }
2516 if (e->v.Call.kwargs) {
2517 VISIT(c, expr, e->v.Call.kwargs);
2518 code |= 2;
2519 }
2520 switch (code) {
2521 case 0:
2522 ADDOP_I(c, CALL_FUNCTION, n);
2523 break;
2524 case 1:
2525 ADDOP_I(c, CALL_FUNCTION_VAR, n);
2526 break;
2527 case 2:
2528 ADDOP_I(c, CALL_FUNCTION_KW, n);
2529 break;
2530 case 3:
2531 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
2532 break;
2533 }
2534 return 1;
2535}
2536
2537static int
2538compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 asdl_seq *generators, int gen_index,
2540 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541{
2542 /* generate code for the iterator, then each of the ifs,
2543 and then write to the element */
2544
2545 comprehension_ty l;
2546 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002547 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548
2549 start = compiler_new_block(c);
2550 skip = compiler_new_block(c);
2551 if_cleanup = compiler_new_block(c);
2552 anchor = compiler_new_block(c);
2553
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002554 if (start == NULL || skip == NULL || if_cleanup == NULL ||
2555 anchor == NULL)
2556 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002558 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 VISIT(c, expr, l->iter);
2560 ADDOP(c, GET_ITER);
2561 compiler_use_next_block(c, start);
2562 ADDOP_JREL(c, FOR_ITER, anchor);
2563 NEXT_BLOCK(c);
2564 VISIT(c, expr, l->target);
2565
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002566 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 n = asdl_seq_LEN(l->ifs);
2568 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002569 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570 VISIT(c, expr, e);
2571 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2572 NEXT_BLOCK(c);
2573 ADDOP(c, POP_TOP);
2574 }
2575
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002576 if (++gen_index < asdl_seq_LEN(generators))
2577 if (!compiler_listcomp_generator(c, tmpname,
2578 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002581 /* only append after the last for generator */
2582 if (gen_index >= asdl_seq_LEN(generators)) {
2583 if (!compiler_nameop(c, tmpname, Load))
2584 return 0;
2585 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00002586 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002587
2588 compiler_use_next_block(c, skip);
2589 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002590 for (i = 0; i < n; i++) {
2591 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002592 if (i == 0)
2593 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594 ADDOP(c, POP_TOP);
2595 }
2596 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2597 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002598 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 return 0;
2602
2603 return 1;
2604}
2605
2606static int
2607compiler_listcomp(struct compiler *c, expr_ty e)
2608{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002610 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 static identifier append;
2612 asdl_seq *generators = e->v.ListComp.generators;
2613
2614 assert(e->kind == ListComp_kind);
2615 if (!append) {
2616 append = PyString_InternFromString("append");
2617 if (!append)
2618 return 0;
2619 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00002620 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 if (!tmp)
2622 return 0;
2623 ADDOP_I(c, BUILD_LIST, 0);
2624 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002626 rc = compiler_listcomp_generator(c, tmp, generators, 0,
2627 e->v.ListComp.elt);
2628 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 return rc;
2630}
2631
2632static int
2633compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 asdl_seq *generators, int gen_index,
2635 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636{
2637 /* generate code for the iterator, then each of the ifs,
2638 and then write to the element */
2639
2640 comprehension_ty ge;
2641 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002642 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643
2644 start = compiler_new_block(c);
2645 skip = compiler_new_block(c);
2646 if_cleanup = compiler_new_block(c);
2647 anchor = compiler_new_block(c);
2648 end = compiler_new_block(c);
2649
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002650 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 anchor == NULL || end == NULL)
2652 return 0;
2653
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002654 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 ADDOP_JREL(c, SETUP_LOOP, end);
2656 if (!compiler_push_fblock(c, LOOP, start))
2657 return 0;
2658
2659 if (gen_index == 0) {
2660 /* Receive outermost iter as an implicit argument */
2661 c->u->u_argcount = 1;
2662 ADDOP_I(c, LOAD_FAST, 0);
2663 }
2664 else {
2665 /* Sub-iter - calculate on the fly */
2666 VISIT(c, expr, ge->iter);
2667 ADDOP(c, GET_ITER);
2668 }
2669 compiler_use_next_block(c, start);
2670 ADDOP_JREL(c, FOR_ITER, anchor);
2671 NEXT_BLOCK(c);
2672 VISIT(c, expr, ge->target);
2673
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 n = asdl_seq_LEN(ge->ifs);
2676 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002677 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 VISIT(c, expr, e);
2679 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
2680 NEXT_BLOCK(c);
2681 ADDOP(c, POP_TOP);
2682 }
2683
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002684 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685 if (!compiler_genexp_generator(c, generators, gen_index, elt))
2686 return 0;
2687
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002688 /* only append after the last 'for' generator */
2689 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 VISIT(c, expr, elt);
2691 ADDOP(c, YIELD_VALUE);
2692 ADDOP(c, POP_TOP);
2693
2694 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 for (i = 0; i < n; i++) {
2697 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002698 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 compiler_use_next_block(c, if_cleanup);
2700
2701 ADDOP(c, POP_TOP);
2702 }
2703 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2704 compiler_use_next_block(c, anchor);
2705 ADDOP(c, POP_BLOCK);
2706 compiler_pop_fblock(c, LOOP, start);
2707 compiler_use_next_block(c, end);
2708
2709 return 1;
2710}
2711
2712static int
2713compiler_genexp(struct compiler *c, expr_ty e)
2714{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002715 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 PyCodeObject *co;
2717 expr_ty outermost_iter = ((comprehension_ty)
2718 (asdl_seq_GET(e->v.GeneratorExp.generators,
2719 0)))->iter;
2720
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002721 if (!name) {
2722 name = PyString_FromString("<genexpr>");
2723 if (!name)
2724 return 0;
2725 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726
2727 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2728 return 0;
2729 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
2730 e->v.GeneratorExp.elt);
2731 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002732 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 if (co == NULL)
2734 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002736 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002737 Py_DECREF(co);
2738
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 VISIT(c, expr, outermost_iter);
2740 ADDOP(c, GET_ITER);
2741 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002742
2743 return 1;
2744}
2745
2746static int
2747compiler_visit_keyword(struct compiler *c, keyword_ty k)
2748{
2749 ADDOP_O(c, LOAD_CONST, k->arg, consts);
2750 VISIT(c, expr, k->value);
2751 return 1;
2752}
2753
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002754/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002755 whether they are true or false.
2756
2757 Return values: 1 for true, 0 for false, -1 for non-constant.
2758 */
2759
2760static int
2761expr_constant(expr_ty e)
2762{
2763 switch (e->kind) {
2764 case Num_kind:
2765 return PyObject_IsTrue(e->v.Num.n);
2766 case Str_kind:
2767 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002768 case Name_kind:
2769 /* __debug__ is not assignable, so we can optimize
2770 * it away in if and while statements */
2771 if (strcmp(PyString_AS_STRING(e->v.Name.id),
2772 "__debug__") == 0)
2773 return ! Py_OptimizeFlag;
2774 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775 default:
2776 return -1;
2777 }
2778}
2779
Guido van Rossumc2e20742006-02-27 22:32:47 +00002780/*
2781 Implements the with statement from PEP 343.
2782
2783 The semantics outlined in that PEP are as follows:
2784
2785 with EXPR as VAR:
2786 BLOCK
2787
2788 It is implemented roughly as:
2789
Thomas Wouters477c8d52006-05-27 19:21:47 +00002790 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00002791 exit = context.__exit__ # not calling it
2792 value = context.__enter__()
2793 try:
2794 VAR = value # if VAR present in the syntax
2795 BLOCK
2796 finally:
2797 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002798 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002799 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002800 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00002801 exit(*exc)
2802 */
2803static int
2804compiler_with(struct compiler *c, stmt_ty s)
2805{
Thomas Wouters477c8d52006-05-27 19:21:47 +00002806 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002807 basicblock *block, *finally;
2808 identifier tmpexit, tmpvalue = NULL;
2809
2810 assert(s->kind == With_kind);
2811
Guido van Rossumc2e20742006-02-27 22:32:47 +00002812 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002813 enter_attr = PyString_InternFromString("__enter__");
2814 if (!enter_attr)
2815 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002816 }
2817 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002818 exit_attr = PyString_InternFromString("__exit__");
2819 if (!exit_attr)
2820 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002821 }
2822
2823 block = compiler_new_block(c);
2824 finally = compiler_new_block(c);
2825 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002826 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002827
2828 /* Create a temporary variable to hold context.__exit__ */
2829 tmpexit = compiler_new_tmpname(c);
2830 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002831 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002832 PyArena_AddPyObject(c->c_arena, tmpexit);
2833
2834 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002835 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00002836 We need to do this rather than preserving it on the stack
2837 because SETUP_FINALLY remembers the stack level.
2838 We need to do the assignment *inside* the try/finally
2839 so that context.__exit__() is called when the assignment
2840 fails. But we need to call context.__enter__() *before*
2841 the try/finally so that if it fails we won't call
2842 context.__exit__().
2843 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002845 if (tmpvalue == NULL)
2846 return 0;
2847 PyArena_AddPyObject(c->c_arena, tmpvalue);
2848 }
2849
Thomas Wouters477c8d52006-05-27 19:21:47 +00002850 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00002851 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002852
2853 /* Squirrel away context.__exit__ */
2854 ADDOP(c, DUP_TOP);
2855 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
2856 if (!compiler_nameop(c, tmpexit, Store))
2857 return 0;
2858
2859 /* Call context.__enter__() */
2860 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
2861 ADDOP_I(c, CALL_FUNCTION, 0);
2862
2863 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002864 /* Store it in tmpvalue */
2865 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00002866 return 0;
2867 }
2868 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002869 /* Discard result from context.__enter__() */
2870 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002871 }
2872
2873 /* Start the try block */
2874 ADDOP_JREL(c, SETUP_FINALLY, finally);
2875
2876 compiler_use_next_block(c, block);
2877 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002878 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002879 }
2880
2881 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 /* Bind saved result of context.__enter__() to VAR */
2883 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00002884 !compiler_nameop(c, tmpvalue, Del))
2885 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002886 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002887 }
2888
2889 /* BLOCK code */
2890 VISIT_SEQ(c, stmt, s->v.With.body);
2891
2892 /* End of try block; start the finally block */
2893 ADDOP(c, POP_BLOCK);
2894 compiler_pop_fblock(c, FINALLY_TRY, block);
2895
2896 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2897 compiler_use_next_block(c, finally);
2898 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002899 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002900
2901 /* Finally block starts; push tmpexit and issue our magic opcode. */
2902 if (!compiler_nameop(c, tmpexit, Load) ||
2903 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002904 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00002905 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00002906
2907 /* Finally block ends. */
2908 ADDOP(c, END_FINALLY);
2909 compiler_pop_fblock(c, FINALLY_END, finally);
2910 return 1;
2911}
2912
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002913static int
2914compiler_visit_expr(struct compiler *c, expr_ty e)
2915{
2916 int i, n;
2917
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002918 /* If expr e has a different line number than the last expr/stmt,
2919 set a new line number for the next instruction.
2920 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 if (e->lineno > c->u->u_lineno) {
2922 c->u->u_lineno = e->lineno;
2923 c->u->u_lineno_set = false;
2924 }
2925 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002926 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002928 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 VISIT(c, expr, e->v.BinOp.left);
2930 VISIT(c, expr, e->v.BinOp.right);
2931 ADDOP(c, binop(c, e->v.BinOp.op));
2932 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002933 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 VISIT(c, expr, e->v.UnaryOp.operand);
2935 ADDOP(c, unaryop(e->v.UnaryOp.op));
2936 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002937 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002939 case IfExp_kind:
2940 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002941 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 /* XXX get rid of arg? */
2943 ADDOP_I(c, BUILD_MAP, 0);
2944 n = asdl_seq_LEN(e->v.Dict.values);
2945 /* We must arrange things just right for STORE_SUBSCR.
2946 It wants the stack to look like (value) (dict) (key) */
2947 for (i = 0; i < n; i++) {
2948 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002949 VISIT(c, expr,
2950 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002952 VISIT(c, expr,
2953 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 ADDOP(c, STORE_SUBSCR);
2955 }
2956 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002957 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002959 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960 return compiler_genexp(c, e);
2961 case Yield_kind:
2962 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002963 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 /*
2965 for (i = 0; i < c->u->u_nfblocks; i++) {
2966 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
2967 return compiler_error(
2968 c, "'yield' not allowed in a 'try' "
2969 "block with a 'finally' clause");
2970 }
2971 */
2972 if (e->v.Yield.value) {
2973 VISIT(c, expr, e->v.Yield.value);
2974 }
2975 else {
2976 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2977 }
2978 ADDOP(c, YIELD_VALUE);
2979 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002980 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002982 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002984 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 VISIT(c, expr, e->v.Repr.value);
2986 ADDOP(c, UNARY_CONVERT);
2987 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002988 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
2990 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002991 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
2993 break;
2994 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002995 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996 if (e->v.Attribute.ctx != AugStore)
2997 VISIT(c, expr, e->v.Attribute.value);
2998 switch (e->v.Attribute.ctx) {
2999 case AugLoad:
3000 ADDOP(c, DUP_TOP);
3001 /* Fall through to load */
3002 case Load:
3003 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3004 break;
3005 case AugStore:
3006 ADDOP(c, ROT_TWO);
3007 /* Fall through to save */
3008 case Store:
3009 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3010 break;
3011 case Del:
3012 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3013 break;
3014 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003015 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003016 PyErr_SetString(PyExc_SystemError,
3017 "param invalid in attribute expression");
3018 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 }
3020 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003021 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 switch (e->v.Subscript.ctx) {
3023 case AugLoad:
3024 VISIT(c, expr, e->v.Subscript.value);
3025 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3026 break;
3027 case Load:
3028 VISIT(c, expr, e->v.Subscript.value);
3029 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3030 break;
3031 case AugStore:
3032 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3033 break;
3034 case Store:
3035 VISIT(c, expr, e->v.Subscript.value);
3036 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3037 break;
3038 case Del:
3039 VISIT(c, expr, e->v.Subscript.value);
3040 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3041 break;
3042 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003043 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003044 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003045 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003046 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 }
3048 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003049 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3051 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003052 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003054 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 return compiler_tuple(c, e);
3056 }
3057 return 1;
3058}
3059
3060static int
3061compiler_augassign(struct compiler *c, stmt_ty s)
3062{
3063 expr_ty e = s->v.AugAssign.target;
3064 expr_ty auge;
3065
3066 assert(s->kind == AugAssign_kind);
3067
3068 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003069 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003071 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 if (auge == NULL)
3073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 VISIT(c, expr, auge);
3075 VISIT(c, expr, s->v.AugAssign.value);
3076 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3077 auge->v.Attribute.ctx = AugStore;
3078 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003079 break;
3080 case Subscript_kind:
3081 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003082 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003083 if (auge == NULL)
3084 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085 VISIT(c, expr, auge);
3086 VISIT(c, expr, s->v.AugAssign.value);
3087 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003088 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003090 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003092 if (!compiler_nameop(c, e->v.Name.id, Load))
3093 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003094 VISIT(c, expr, s->v.AugAssign.value);
3095 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3096 return compiler_nameop(c, e->v.Name.id, Store);
3097 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003098 PyErr_Format(PyExc_SystemError,
3099 "invalid node type (%d) for augmented assignment",
3100 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102 }
3103 return 1;
3104}
3105
3106static int
3107compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3108{
3109 struct fblockinfo *f;
3110 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3111 return 0;
3112 f = &c->u->u_fblock[c->u->u_nfblocks++];
3113 f->fb_type = t;
3114 f->fb_block = b;
3115 return 1;
3116}
3117
3118static void
3119compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3120{
3121 struct compiler_unit *u = c->u;
3122 assert(u->u_nfblocks > 0);
3123 u->u_nfblocks--;
3124 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3125 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3126}
3127
3128/* Raises a SyntaxError and returns 0.
3129 If something goes wrong, a different exception may be raised.
3130*/
3131
3132static int
3133compiler_error(struct compiler *c, const char *errstr)
3134{
3135 PyObject *loc;
3136 PyObject *u = NULL, *v = NULL;
3137
3138 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3139 if (!loc) {
3140 Py_INCREF(Py_None);
3141 loc = Py_None;
3142 }
3143 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3144 Py_None, loc);
3145 if (!u)
3146 goto exit;
3147 v = Py_BuildValue("(zO)", errstr, u);
3148 if (!v)
3149 goto exit;
3150 PyErr_SetObject(PyExc_SyntaxError, v);
3151 exit:
3152 Py_DECREF(loc);
3153 Py_XDECREF(u);
3154 Py_XDECREF(v);
3155 return 0;
3156}
3157
3158static int
3159compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003162 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 /* XXX this code is duplicated */
3165 switch (ctx) {
3166 case AugLoad: /* fall through to Load */
3167 case Load: op = BINARY_SUBSCR; break;
3168 case AugStore:/* fall through to Store */
3169 case Store: op = STORE_SUBSCR; break;
3170 case Del: op = DELETE_SUBSCR; break;
3171 case Param:
3172 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003173 "invalid %s kind %d in subscript\n",
3174 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 return 0;
3176 }
3177 if (ctx == AugLoad) {
3178 ADDOP_I(c, DUP_TOPX, 2);
3179 }
3180 else if (ctx == AugStore) {
3181 ADDOP(c, ROT_THREE);
3182 }
3183 ADDOP(c, op);
3184 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185}
3186
3187static int
3188compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3189{
3190 int n = 2;
3191 assert(s->kind == Slice_kind);
3192
3193 /* only handles the cases where BUILD_SLICE is emitted */
3194 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 }
3197 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 }
3204 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 }
3207
3208 if (s->v.Slice.step) {
3209 n++;
3210 VISIT(c, expr, s->v.Slice.step);
3211 }
3212 ADDOP_I(c, BUILD_SLICE, n);
3213 return 1;
3214}
3215
3216static int
3217compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3218{
3219 int op = 0, slice_offset = 0, stack_count = 0;
3220
3221 assert(s->v.Slice.step == NULL);
3222 if (s->v.Slice.lower) {
3223 slice_offset++;
3224 stack_count++;
3225 if (ctx != AugStore)
3226 VISIT(c, expr, s->v.Slice.lower);
3227 }
3228 if (s->v.Slice.upper) {
3229 slice_offset += 2;
3230 stack_count++;
3231 if (ctx != AugStore)
3232 VISIT(c, expr, s->v.Slice.upper);
3233 }
3234
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 if (ctx == AugLoad) {
3236 switch (stack_count) {
3237 case 0: ADDOP(c, DUP_TOP); break;
3238 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3239 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3240 }
3241 }
3242 else if (ctx == AugStore) {
3243 switch (stack_count) {
3244 case 0: ADDOP(c, ROT_TWO); break;
3245 case 1: ADDOP(c, ROT_THREE); break;
3246 case 2: ADDOP(c, ROT_FOUR); break;
3247 }
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249
3250 switch (ctx) {
3251 case AugLoad: /* fall through to Load */
3252 case Load: op = SLICE; break;
3253 case AugStore:/* fall through to Store */
3254 case Store: op = STORE_SLICE; break;
3255 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003256 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003257 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003258 PyErr_SetString(PyExc_SystemError,
3259 "param invalid in simple slice");
3260 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 }
3262
3263 ADDOP(c, op + slice_offset);
3264 return 1;
3265}
3266
3267static int
3268compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3269 expr_context_ty ctx)
3270{
3271 switch (s->kind) {
3272 case Ellipsis_kind:
3273 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3274 break;
3275 case Slice_kind:
3276 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003277 case Index_kind:
3278 VISIT(c, expr, s->v.Index.value);
3279 break;
3280 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003281 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003282 PyErr_SetString(PyExc_SystemError,
3283 "extended slice invalid in nested slice");
3284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 }
3286 return 1;
3287}
3288
3289
3290static int
3291compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3292{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003293 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003295 case Index_kind:
3296 kindname = "index";
3297 if (ctx != AugStore) {
3298 VISIT(c, expr, s->v.Index.value);
3299 }
3300 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003302 kindname = "ellipsis";
3303 if (ctx != AugStore) {
3304 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306 break;
3307 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003308 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309 if (!s->v.Slice.step)
3310 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003311 if (ctx != AugStore) {
3312 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313 return 0;
3314 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003315 break;
3316 case ExtSlice_kind:
3317 kindname = "extended slice";
3318 if (ctx != AugStore) {
3319 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3320 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003321 slice_ty sub = (slice_ty)asdl_seq_GET(
3322 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003323 if (!compiler_visit_nested_slice(c, sub, ctx))
3324 return 0;
3325 }
3326 ADDOP_I(c, BUILD_TUPLE, n);
3327 }
3328 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003329 default:
3330 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003331 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003332 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003334 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335}
3336
3337/* do depth-first search of basic block graph, starting with block.
3338 post records the block indices in post-order.
3339
3340 XXX must handle implicit jumps from one block to next
3341*/
3342
3343static void
3344dfs(struct compiler *c, basicblock *b, struct assembler *a)
3345{
3346 int i;
3347 struct instr *instr = NULL;
3348
3349 if (b->b_seen)
3350 return;
3351 b->b_seen = 1;
3352 if (b->b_next != NULL)
3353 dfs(c, b->b_next, a);
3354 for (i = 0; i < b->b_iused; i++) {
3355 instr = &b->b_instr[i];
3356 if (instr->i_jrel || instr->i_jabs)
3357 dfs(c, instr->i_target, a);
3358 }
3359 a->a_postorder[a->a_nblocks++] = b;
3360}
3361
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003362static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3364{
3365 int i;
3366 struct instr *instr;
3367 if (b->b_seen || b->b_startdepth >= depth)
3368 return maxdepth;
3369 b->b_seen = 1;
3370 b->b_startdepth = depth;
3371 for (i = 0; i < b->b_iused; i++) {
3372 instr = &b->b_instr[i];
3373 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3374 if (depth > maxdepth)
3375 maxdepth = depth;
3376 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3377 if (instr->i_jrel || instr->i_jabs) {
3378 maxdepth = stackdepth_walk(c, instr->i_target,
3379 depth, maxdepth);
3380 if (instr->i_opcode == JUMP_ABSOLUTE ||
3381 instr->i_opcode == JUMP_FORWARD) {
3382 goto out; /* remaining code is dead */
3383 }
3384 }
3385 }
3386 if (b->b_next)
3387 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3388out:
3389 b->b_seen = 0;
3390 return maxdepth;
3391}
3392
3393/* Find the flow path that needs the largest stack. We assume that
3394 * cycles in the flow graph have no net effect on the stack depth.
3395 */
3396static int
3397stackdepth(struct compiler *c)
3398{
3399 basicblock *b, *entryblock;
3400 entryblock = NULL;
3401 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3402 b->b_seen = 0;
3403 b->b_startdepth = INT_MIN;
3404 entryblock = b;
3405 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003406 if (!entryblock)
3407 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003408 return stackdepth_walk(c, entryblock, 0, 0);
3409}
3410
3411static int
3412assemble_init(struct assembler *a, int nblocks, int firstlineno)
3413{
3414 memset(a, 0, sizeof(struct assembler));
3415 a->a_lineno = firstlineno;
3416 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3417 if (!a->a_bytecode)
3418 return 0;
3419 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3420 if (!a->a_lnotab)
3421 return 0;
3422 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003423 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003424 if (!a->a_postorder) {
3425 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003426 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003427 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003428 return 1;
3429}
3430
3431static void
3432assemble_free(struct assembler *a)
3433{
3434 Py_XDECREF(a->a_bytecode);
3435 Py_XDECREF(a->a_lnotab);
3436 if (a->a_postorder)
3437 PyObject_Free(a->a_postorder);
3438}
3439
3440/* Return the size of a basic block in bytes. */
3441
3442static int
3443instrsize(struct instr *instr)
3444{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003445 if (!instr->i_hasarg)
3446 return 1;
3447 if (instr->i_oparg > 0xffff)
3448 return 6;
3449 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003450}
3451
3452static int
3453blocksize(basicblock *b)
3454{
3455 int i;
3456 int size = 0;
3457
3458 for (i = 0; i < b->b_iused; i++)
3459 size += instrsize(&b->b_instr[i]);
3460 return size;
3461}
3462
3463/* All about a_lnotab.
3464
3465c_lnotab is an array of unsigned bytes disguised as a Python string.
3466It is used to map bytecode offsets to source code line #s (when needed
3467for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00003468
Tim Peters2a7f3842001-06-09 09:26:21 +00003469The array is conceptually a list of
3470 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00003472
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 byte code offset source code line number
3474 0 1
3475 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00003476 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003477 350 307
3478 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00003479
3480The first trick is that these numbers aren't stored, only the increments
3481from one row to the next (this doesn't really work, but it's a start):
3482
3483 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
3484
3485The second trick is that an unsigned byte can't hold negative values, or
3486values larger than 255, so (a) there's a deep assumption that byte code
3487offsets and their corresponding line #s both increase monotonically, and (b)
3488if at least one column jumps by more than 255 from one row to the next, more
3489than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003490from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00003491part. A user of c_lnotab desiring to find the source line number
3492corresponding to a bytecode address A should do something like this
3493
3494 lineno = addr = 0
3495 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003496 addr += addr_incr
3497 if addr > A:
3498 return lineno
3499 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00003500
3501In order for this to work, when the addr field increments by more than 255,
3502the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003503increment is < 256. So, in the example above, assemble_lnotab (it used
3504to be called com_set_lineno) should not (as was actually done until 2.2)
3505expand 300, 300 to 255, 255, 45, 45,
3506 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00003507*/
3508
Guido van Rossumf68d8e52001-04-14 17:55:09 +00003509static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003511{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 int d_bytecode, d_lineno;
3513 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003514 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515
3516 d_bytecode = a->a_offset - a->a_lineno_off;
3517 d_lineno = i->i_lineno - a->a_lineno;
3518
3519 assert(d_bytecode >= 0);
3520 assert(d_lineno >= 0);
3521
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003522 /* XXX(nnorwitz): is there a better way to handle this?
3523 for loops are special, we want to be able to trace them
3524 each time around, so we need to set an extra line number. */
3525 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003526 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00003527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003529 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 nbytes = a->a_lnotab_off + 2 * ncodes;
3531 len = PyString_GET_SIZE(a->a_lnotab);
3532 if (nbytes >= len) {
3533 if (len * 2 < nbytes)
3534 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00003535 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536 len *= 2;
3537 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3538 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00003539 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003540 lnotab = (unsigned char *)
3541 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003542 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 *lnotab++ = 255;
3544 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003545 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 d_bytecode -= ncodes * 255;
3547 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003548 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 assert(d_bytecode <= 255);
3550 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003551 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 nbytes = a->a_lnotab_off + 2 * ncodes;
3553 len = PyString_GET_SIZE(a->a_lnotab);
3554 if (nbytes >= len) {
3555 if (len * 2 < nbytes)
3556 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00003557 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 len *= 2;
3559 if (_PyString_Resize(&a->a_lnotab, len) < 0)
3560 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003561 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003562 lnotab = (unsigned char *)
3563 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003565 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00003567 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003569 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00003570 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 d_lineno -= ncodes * 255;
3572 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003573 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003574
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 len = PyString_GET_SIZE(a->a_lnotab);
3576 if (a->a_lnotab_off + 2 >= len) {
3577 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00003578 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00003579 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003580 lnotab = (unsigned char *)
3581 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00003582
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 a->a_lnotab_off += 2;
3584 if (d_bytecode) {
3585 *lnotab++ = d_bytecode;
3586 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00003587 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 *lnotab++ = 0;
3590 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003591 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 a->a_lineno = i->i_lineno;
3593 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003594 return 1;
3595}
3596
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597/* assemble_emit()
3598 Extend the bytecode with a new instruction.
3599 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00003600*/
3601
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003602static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003604{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003605 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003606 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607 char *code;
3608
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003609 size = instrsize(i);
3610 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003612 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003615 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 if (a->a_offset + size >= len) {
3617 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00003618 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00003619 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
3621 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003622 if (size == 6) {
3623 assert(i->i_hasarg);
3624 *code++ = (char)EXTENDED_ARG;
3625 *code++ = ext & 0xff;
3626 *code++ = ext >> 8;
3627 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003628 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003630 if (i->i_hasarg) {
3631 assert(size == 3 || size == 6);
3632 *code++ = arg & 0xff;
3633 *code++ = arg >> 8;
3634 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003636}
3637
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003638static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00003640{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00003642 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00003643 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00003644
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 /* Compute the size of each block and fixup jump args.
3646 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00003647start:
3648 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003650 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 bsize = blocksize(b);
3652 b->b_offset = totsize;
3653 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00003654 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003655 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3657 bsize = b->b_offset;
3658 for (i = 0; i < b->b_iused; i++) {
3659 struct instr *instr = &b->b_instr[i];
3660 /* Relative jumps are computed relative to
3661 the instruction pointer after fetching
3662 the jump instruction.
3663 */
3664 bsize += instrsize(instr);
3665 if (instr->i_jabs)
3666 instr->i_oparg = instr->i_target->b_offset;
3667 else if (instr->i_jrel) {
3668 int delta = instr->i_target->b_offset - bsize;
3669 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003670 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003671 else
3672 continue;
3673 if (instr->i_oparg > 0xffff)
3674 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00003675 }
3676 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00003677
3678 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003679 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00003680 with a better solution.
3681
3682 In the meantime, should the goto be dropped in favor
3683 of a loop?
3684
3685 The issue is that in the first loop blocksize() is called
3686 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003687 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00003688 i_oparg is calculated in the second loop above.
3689
3690 So we loop until we stop seeing new EXTENDED_ARGs.
3691 The only EXTENDED_ARGs that could be popping up are
3692 ones in jump instructions. So this should converge
3693 fairly quickly.
3694 */
3695 if (last_extended_arg_count != extended_arg_count) {
3696 last_extended_arg_count = extended_arg_count;
3697 goto start;
3698 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00003699}
3700
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003701static PyObject *
3702dict_keys_inorder(PyObject *dict, int offset)
3703{
3704 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003705 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003706
3707 tuple = PyTuple_New(size);
3708 if (tuple == NULL)
3709 return NULL;
3710 while (PyDict_Next(dict, &pos, &k, &v)) {
3711 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003712 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003713 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00003714 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003715 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003716 PyTuple_SET_ITEM(tuple, i - offset, k);
3717 }
3718 return tuple;
3719}
3720
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003721static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003723{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724 PySTEntryObject *ste = c->u->u_ste;
3725 int flags = 0, n;
3726 if (ste->ste_type != ModuleBlock)
3727 flags |= CO_NEWLOCALS;
3728 if (ste->ste_type == FunctionBlock) {
3729 if (!ste->ste_unoptimized)
3730 flags |= CO_OPTIMIZED;
3731 if (ste->ste_nested)
3732 flags |= CO_NESTED;
3733 if (ste->ste_generator)
3734 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003735 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003736 if (ste->ste_varargs)
3737 flags |= CO_VARARGS;
3738 if (ste->ste_varkeywords)
3739 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00003740 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003742
3743 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003744 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00003745
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746 n = PyDict_Size(c->u->u_freevars);
3747 if (n < 0)
3748 return -1;
3749 if (n == 0) {
3750 n = PyDict_Size(c->u->u_cellvars);
3751 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003752 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753 if (n == 0) {
3754 flags |= CO_NOFREE;
3755 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003756 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00003757
Jeremy Hylton29906ee2001-02-27 04:23:34 +00003758 return flags;
3759}
3760
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761static PyCodeObject *
3762makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003763{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764 PyObject *tmp;
3765 PyCodeObject *co = NULL;
3766 PyObject *consts = NULL;
3767 PyObject *names = NULL;
3768 PyObject *varnames = NULL;
3769 PyObject *filename = NULL;
3770 PyObject *name = NULL;
3771 PyObject *freevars = NULL;
3772 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003775
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 tmp = dict_keys_inorder(c->u->u_consts, 0);
3777 if (!tmp)
3778 goto error;
3779 consts = PySequence_List(tmp); /* optimize_code requires a list */
3780 Py_DECREF(tmp);
3781
3782 names = dict_keys_inorder(c->u->u_names, 0);
3783 varnames = dict_keys_inorder(c->u->u_varnames, 0);
3784 if (!consts || !names || !varnames)
3785 goto error;
3786
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003787 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
3788 if (!cellvars)
3789 goto error;
3790 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
3791 if (!freevars)
3792 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793 filename = PyString_FromString(c->c_filename);
3794 if (!filename)
3795 goto error;
3796
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003797 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003798 flags = compute_code_flags(c);
3799 if (flags < 0)
3800 goto error;
3801
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003802 bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803 if (!bytecode)
3804 goto error;
3805
3806 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
3807 if (!tmp)
3808 goto error;
3809 Py_DECREF(consts);
3810 consts = tmp;
3811
3812 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
3813 bytecode, consts, names, varnames,
3814 freevars, cellvars,
3815 filename, c->u->u_name,
3816 c->u->u_firstlineno,
3817 a->a_lnotab);
3818 error:
3819 Py_XDECREF(consts);
3820 Py_XDECREF(names);
3821 Py_XDECREF(varnames);
3822 Py_XDECREF(filename);
3823 Py_XDECREF(name);
3824 Py_XDECREF(freevars);
3825 Py_XDECREF(cellvars);
3826 Py_XDECREF(bytecode);
3827 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003828}
3829
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003830
3831/* For debugging purposes only */
3832#if 0
3833static void
3834dump_instr(const struct instr *i)
3835{
3836 const char *jrel = i->i_jrel ? "jrel " : "";
3837 const char *jabs = i->i_jabs ? "jabs " : "";
3838 char arg[128];
3839
3840 *arg = '\0';
3841 if (i->i_hasarg)
3842 sprintf(arg, "arg: %d ", i->i_oparg);
3843
3844 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
3845 i->i_lineno, i->i_opcode, arg, jabs, jrel);
3846}
3847
3848static void
3849dump_basicblock(const basicblock *b)
3850{
3851 const char *seen = b->b_seen ? "seen " : "";
3852 const char *b_return = b->b_return ? "return " : "";
3853 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
3854 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
3855 if (b->b_instr) {
3856 int i;
3857 for (i = 0; i < b->b_iused; i++) {
3858 fprintf(stderr, " [%02d] ", i);
3859 dump_instr(b->b_instr + i);
3860 }
3861 }
3862}
3863#endif
3864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865static PyCodeObject *
3866assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003867{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868 basicblock *b, *entryblock;
3869 struct assembler a;
3870 int i, j, nblocks;
3871 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00003872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 /* Make sure every block that falls off the end returns None.
3874 XXX NEXT_BLOCK() isn't quite right, because if the last
3875 block ends with a jump or return b_next shouldn't set.
3876 */
3877 if (!c->u->u_curblock->b_return) {
3878 NEXT_BLOCK(c);
3879 if (addNone)
3880 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3881 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003882 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 nblocks = 0;
3885 entryblock = NULL;
3886 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3887 nblocks++;
3888 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003889 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003890
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003891 /* Set firstlineno if it wasn't explicitly set. */
3892 if (!c->u->u_firstlineno) {
3893 if (entryblock && entryblock->b_instr)
3894 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
3895 else
3896 c->u->u_firstlineno = 1;
3897 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
3899 goto error;
3900 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003901
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003903 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00003904
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003905 /* Emit code in reverse postorder from dfs. */
3906 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00003907 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908 for (j = 0; j < b->b_iused; j++)
3909 if (!assemble_emit(&a, &b->b_instr[j]))
3910 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00003911 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00003912
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
3914 goto error;
3915 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
3916 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003917
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 co = makecode(c, &a);
3919 error:
3920 assemble_free(&a);
3921 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00003922}