blob: ae4c8503f008a951227bb219532852445f29a4d8 [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_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +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 */
Jeremy Hylton12603c42006-04-01 16:18:02 +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
146 int c_interactive;
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 *
200_Py_Mangle(PyObject *private, 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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000207 if (private == NULL || name == NULL || name[0] != '_' ||
208 name[1] != '_') {
209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
212 p = PyString_AsString(private);
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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 mod_ty mod = PyAST_FromNode(n, NULL, filename, arena);
305 if (mod)
306 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000307 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000308 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000309}
310
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000311static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000313{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 if (c->c_st)
315 PySymtable_Free(c->c_st);
316 if (c->c_future)
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000317 PyMem_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319}
320
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000323{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
337 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
380 tuple = Py_BuildValue("(OO)", k, k->ob_type);
381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000394/* Begin: Peephole optimizations ----------------------------------------- */
395
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000396#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000398#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
399#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000400#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define ISBASICBLOCK(blocks, start, bytes) \
403 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000410 Bails out with no change if one or more of the LOAD_CONSTs is missing.
411 Also works for BUILD_LIST when followed by an "in" or "not in" test.
412*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413static int
414tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
415{
416 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418
419 /* Pre-conditions */
420 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000421 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000424 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425
426 /* Buildup new tuple of constants */
427 newconst = PyTuple_New(n);
428 if (newconst == NULL)
429 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 for (i=0 ; i<n ; i++) {
432 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 constant = PyList_GET_ITEM(consts, arg);
435 Py_INCREF(constant);
436 PyTuple_SET_ITEM(newconst, i, constant);
437 }
438
439 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 if (PyList_Append(consts, newconst)) {
441 Py_DECREF(newconst);
442 return 0;
443 }
444 Py_DECREF(newconst);
445
446 /* Write NOPs over old LOAD_CONSTS and
447 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
448 memset(codestr, NOP, n*3);
449 codestr[n*3] = LOAD_CONST;
450 SETARG(codestr, (n*3), len_consts);
451 return 1;
452}
453
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000458 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000459 Abandons the transformation if the folding fails (i.e. 1+'a').
460 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 is below a threshold value. That keeps pyc files from
462 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000463*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000464static int
465fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
466{
467 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t len_consts, size;
469 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000470
471 /* Pre-conditions */
472 assert(PyList_CheckExact(consts));
473 assert(codestr[0] == LOAD_CONST);
474 assert(codestr[3] == LOAD_CONST);
475
476 /* Create new constant */
477 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
478 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
479 opcode = codestr[6];
480 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 case BINARY_POWER:
482 newconst = PyNumber_Power(v, w, Py_None);
483 break;
484 case BINARY_MULTIPLY:
485 newconst = PyNumber_Multiply(v, w);
486 break;
487 case BINARY_DIVIDE:
488 /* Cannot fold this operation statically since
489 the result can depend on the run-time presence
490 of the -Qnew flag */
491 return 0;
492 case BINARY_TRUE_DIVIDE:
493 newconst = PyNumber_TrueDivide(v, w);
494 break;
495 case BINARY_FLOOR_DIVIDE:
496 newconst = PyNumber_FloorDivide(v, w);
497 break;
498 case BINARY_MODULO:
499 newconst = PyNumber_Remainder(v, w);
500 break;
501 case BINARY_ADD:
502 newconst = PyNumber_Add(v, w);
503 break;
504 case BINARY_SUBTRACT:
505 newconst = PyNumber_Subtract(v, w);
506 break;
507 case BINARY_SUBSCR:
508 newconst = PyObject_GetItem(v, w);
509 break;
510 case BINARY_LSHIFT:
511 newconst = PyNumber_Lshift(v, w);
512 break;
513 case BINARY_RSHIFT:
514 newconst = PyNumber_Rshift(v, w);
515 break;
516 case BINARY_AND:
517 newconst = PyNumber_And(v, w);
518 break;
519 case BINARY_XOR:
520 newconst = PyNumber_Xor(v, w);
521 break;
522 case BINARY_OR:
523 newconst = PyNumber_Or(v, w);
524 break;
525 default:
526 /* Called with an unknown opcode */
527 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000528 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000529 opcode);
530 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000531 }
532 if (newconst == NULL) {
533 PyErr_Clear();
534 return 0;
535 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000536 size = PyObject_Size(newconst);
537 if (size == -1)
538 PyErr_Clear();
539 else if (size > 20) {
540 Py_DECREF(newconst);
541 return 0;
542 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000543
544 /* Append folded constant into consts table */
545 len_consts = PyList_GET_SIZE(consts);
546 if (PyList_Append(consts, newconst)) {
547 Py_DECREF(newconst);
548 return 0;
549 }
550 Py_DECREF(newconst);
551
552 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
553 memset(codestr, NOP, 4);
554 codestr[4] = LOAD_CONST;
555 SETARG(codestr, 4, len_consts);
556 return 1;
557}
558
Raymond Hettinger80121492005-02-20 12:41:32 +0000559static int
560fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
561{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000562 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563 Py_ssize_t len_consts;
564 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000565
566 /* Pre-conditions */
567 assert(PyList_CheckExact(consts));
568 assert(codestr[0] == LOAD_CONST);
569
570 /* Create new constant */
571 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
572 opcode = codestr[3];
573 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000574 case UNARY_NEGATIVE:
575 /* Preserve the sign of -0.0 */
576 if (PyObject_IsTrue(v) == 1)
577 newconst = PyNumber_Negative(v);
578 break;
579 case UNARY_CONVERT:
580 newconst = PyObject_Repr(v);
581 break;
582 case UNARY_INVERT:
583 newconst = PyNumber_Invert(v);
584 break;
585 default:
586 /* Called with an unknown opcode */
587 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000588 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000589 opcode);
590 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000591 }
592 if (newconst == NULL) {
593 PyErr_Clear();
594 return 0;
595 }
596
597 /* Append folded constant into consts table */
598 len_consts = PyList_GET_SIZE(consts);
599 if (PyList_Append(consts, newconst)) {
600 Py_DECREF(newconst);
601 return 0;
602 }
603 Py_DECREF(newconst);
604
605 /* Write NOP LOAD_CONST newconst */
606 codestr[0] = NOP;
607 codestr[1] = LOAD_CONST;
608 SETARG(codestr, 1, len_consts);
609 return 1;
610}
611
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612static unsigned int *
613markblocks(unsigned char *code, int len)
614{
615 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000617
618 if (blocks == NULL)
619 return NULL;
620 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000621
622 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000623 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
624 opcode = code[i];
625 switch (opcode) {
626 case FOR_ITER:
627 case JUMP_FORWARD:
628 case JUMP_IF_FALSE:
629 case JUMP_IF_TRUE:
630 case JUMP_ABSOLUTE:
631 case CONTINUE_LOOP:
632 case SETUP_LOOP:
633 case SETUP_EXCEPT:
634 case SETUP_FINALLY:
635 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000636 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000638 }
639 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000640 /* Build block numbers in the second pass */
641 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000642 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000643 blocks[i] = blockcnt;
644 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000645 return blocks;
646}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000647
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000648/* Perform basic peephole optimizations to components of a code object.
649 The consts object should still be in list form to allow new constants
650 to be appended.
651
652 To keep the optimizer simple, it bails out (does nothing) for code
653 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000654 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000655 the lineno table has complex encoding for gaps >= 255.
656
657 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000658 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000659 smaller. For those that reduce size, the gaps are initially filled with
660 NOPs. Later those NOPs are removed and the jump addresses retargeted in
661 a single pass. Line numbering is adjusted accordingly. */
662
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000664optimize_code(PyObject *code, PyObject* consts, PyObject *names,
665 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000666{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000667 Py_ssize_t i, j, codelen;
668 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000669 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000670 unsigned char *codestr = NULL;
671 unsigned char *lineno;
672 int *addrmap = NULL;
673 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000674 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000675 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000676 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000677
Raymond Hettingereffb3932004-10-30 08:55:08 +0000678 /* Bail out if an exception is set */
679 if (PyErr_Occurred())
680 goto exitUnchanged;
681
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000682 /* Bypass optimization when the lineno table is too complex */
683 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000684 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000685 tabsiz = PyString_GET_SIZE(lineno_obj);
686 if (memchr(lineno, 255, tabsiz) != NULL)
687 goto exitUnchanged;
688
Raymond Hettingera12fa142004-08-24 04:34:16 +0000689 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000690 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000692 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000693 goto exitUnchanged;
694
695 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000696 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000697 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000698 goto exitUnchanged;
699 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000700
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000701 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000702 the various transformation patterns to look ahead several
703 instructions without additional checks to make sure they are not
704 looking beyond the end of the code string.
705 */
706 if (codestr[codelen-1] != RETURN_VALUE)
707 goto exitUnchanged;
708
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000709 /* Mapping to new jump targets after NOPs are removed */
710 addrmap = PyMem_Malloc(codelen * sizeof(int));
711 if (addrmap == NULL)
712 goto exitUnchanged;
713
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000714 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000715 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000716 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000717 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000718
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000719 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000720 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000721
722 lastlc = cumlc;
723 cumlc = 0;
724
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000725 switch (opcode) {
726
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000727 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
728 with JUMP_IF_TRUE POP_TOP */
729 case UNARY_NOT:
730 if (codestr[i+1] != JUMP_IF_FALSE ||
731 codestr[i+4] != POP_TOP ||
732 !ISBASICBLOCK(blocks,i,5))
733 continue;
734 tgt = GETJUMPTGT(codestr, (i+1));
735 if (codestr[tgt] != POP_TOP)
736 continue;
737 j = GETARG(codestr, i+1) + 1;
738 codestr[i] = JUMP_IF_TRUE;
739 SETARG(codestr, i, j);
740 codestr[i+3] = POP_TOP;
741 codestr[i+4] = NOP;
742 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000743
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000744 /* not a is b --> a is not b
745 not a in b --> a not in b
746 not a is not b --> a is b
747 not a not in b --> a in b
748 */
749 case COMPARE_OP:
750 j = GETARG(codestr, i);
751 if (j < 6 || j > 9 ||
752 codestr[i+3] != UNARY_NOT ||
753 !ISBASICBLOCK(blocks,i,4))
754 continue;
755 SETARG(codestr, i, (j^1));
756 codestr[i+3] = NOP;
757 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000758
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000759 /* Replace LOAD_GLOBAL/LOAD_NAME None
760 with LOAD_CONST None */
761 case LOAD_NAME:
762 case LOAD_GLOBAL:
763 j = GETARG(codestr, i);
764 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
765 if (name == NULL || strcmp(name, "None") != 0)
766 continue;
767 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
768 if (PyList_GET_ITEM(consts, j) == Py_None) {
769 codestr[i] = LOAD_CONST;
770 SETARG(codestr, i, j);
771 cumlc = lastlc + 1;
772 break;
773 }
774 }
775 break;
776
777 /* Skip over LOAD_CONST trueconst
778 JUMP_IF_FALSE xx POP_TOP */
779 case LOAD_CONST:
780 cumlc = lastlc + 1;
781 j = GETARG(codestr, i);
782 if (codestr[i+3] != JUMP_IF_FALSE ||
783 codestr[i+6] != POP_TOP ||
784 !ISBASICBLOCK(blocks,i,7) ||
785 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
786 continue;
787 memset(codestr+i, NOP, 7);
788 cumlc = 0;
789 break;
790
791 /* Try to fold tuples of constants (includes a case for lists
792 which are only used for "in" and "not in" tests).
793 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
794 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
795 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
796 case BUILD_TUPLE:
797 case BUILD_LIST:
798 j = GETARG(codestr, i);
799 h = i - 3 * j;
800 if (h >= 0 &&
801 j <= lastlc &&
802 ((opcode == BUILD_TUPLE &&
803 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
804 (opcode == BUILD_LIST &&
805 codestr[i+3]==COMPARE_OP &&
806 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
807 (GETARG(codestr,i+3)==6 ||
808 GETARG(codestr,i+3)==7))) &&
809 tuple_of_constants(&codestr[h], j, consts)) {
810 assert(codestr[i] == LOAD_CONST);
811 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000812 break;
813 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000814 if (codestr[i+3] != UNPACK_SEQUENCE ||
815 !ISBASICBLOCK(blocks,i,6) ||
816 j != GETARG(codestr, i+3))
817 continue;
818 if (j == 1) {
819 memset(codestr+i, NOP, 6);
820 } else if (j == 2) {
821 codestr[i] = ROT_TWO;
822 memset(codestr+i+1, NOP, 5);
823 } else if (j == 3) {
824 codestr[i] = ROT_THREE;
825 codestr[i+1] = ROT_TWO;
826 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000827 }
828 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000829
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000830 /* Fold binary ops on constants.
831 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
832 case BINARY_POWER:
833 case BINARY_MULTIPLY:
834 case BINARY_TRUE_DIVIDE:
835 case BINARY_FLOOR_DIVIDE:
836 case BINARY_MODULO:
837 case BINARY_ADD:
838 case BINARY_SUBTRACT:
839 case BINARY_SUBSCR:
840 case BINARY_LSHIFT:
841 case BINARY_RSHIFT:
842 case BINARY_AND:
843 case BINARY_XOR:
844 case BINARY_OR:
845 if (lastlc >= 2 &&
846 ISBASICBLOCK(blocks, i-6, 7) &&
847 fold_binops_on_constants(&codestr[i-6], consts)) {
848 i -= 2;
849 assert(codestr[i] == LOAD_CONST);
850 cumlc = 1;
851 }
852 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000853
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000854 /* Fold unary ops on constants.
855 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
856 case UNARY_NEGATIVE:
857 case UNARY_CONVERT:
858 case UNARY_INVERT:
859 if (lastlc >= 1 &&
860 ISBASICBLOCK(blocks, i-3, 4) &&
861 fold_unaryops_on_constants(&codestr[i-3], consts)) {
862 i -= 2;
863 assert(codestr[i] == LOAD_CONST);
864 cumlc = 1;
865 }
866 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000867
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000868 /* Simplify conditional jump to conditional jump where the
869 result of the first test implies the success of a similar
870 test or the failure of the opposite test.
871 Arises in code like:
872 "if a and b:"
873 "if a or b:"
874 "a and b or c"
875 "(a and b) and c"
876 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
877 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
878 where y+3 is the instruction following the second test.
879 */
880 case JUMP_IF_FALSE:
881 case JUMP_IF_TRUE:
882 tgt = GETJUMPTGT(codestr, i);
883 j = codestr[tgt];
884 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
885 if (j == opcode) {
886 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
887 SETARG(codestr, i, tgttgt);
888 } else {
889 tgt -= i;
890 SETARG(codestr, i, tgt);
891 }
892 break;
893 }
894 /* Intentional fallthrough */
895
896 /* Replace jumps to unconditional jumps */
897 case FOR_ITER:
898 case JUMP_FORWARD:
899 case JUMP_ABSOLUTE:
900 case CONTINUE_LOOP:
901 case SETUP_LOOP:
902 case SETUP_EXCEPT:
903 case SETUP_FINALLY:
904 tgt = GETJUMPTGT(codestr, i);
905 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
906 continue;
907 tgttgt = GETJUMPTGT(codestr, tgt);
908 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
909 opcode = JUMP_ABSOLUTE;
910 if (!ABSOLUTE_JUMP(opcode))
911 tgttgt -= i + 3; /* Calc relative jump addr */
912 if (tgttgt < 0) /* No backward relative jumps */
913 continue;
914 codestr[i] = opcode;
915 SETARG(codestr, i, tgttgt);
916 break;
917
918 case EXTENDED_ARG:
919 goto exitUnchanged;
920
921 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
922 case RETURN_VALUE:
923 if (i+4 >= codelen ||
924 codestr[i+4] != RETURN_VALUE ||
925 !ISBASICBLOCK(blocks,i,5))
926 continue;
927 memset(codestr+i+1, NOP, 4);
928 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000929 }
930 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000931
932 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000933 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
934 addrmap[i] = i - nops;
935 if (codestr[i] == NOP)
936 nops++;
937 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000938 cum_orig_line = 0;
939 last_line = 0;
940 for (i=0 ; i < tabsiz ; i+=2) {
941 cum_orig_line += lineno[i];
942 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000943 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000944 lineno[i] =((unsigned char)(new_line - last_line));
945 last_line = new_line;
946 }
947
948 /* Remove NOPs and fixup jump targets */
949 for (i=0, h=0 ; i<codelen ; ) {
950 opcode = codestr[i];
951 switch (opcode) {
952 case NOP:
953 i++;
954 continue;
955
956 case JUMP_ABSOLUTE:
957 case CONTINUE_LOOP:
958 j = addrmap[GETARG(codestr, i)];
959 SETARG(codestr, i, j);
960 break;
961
962 case FOR_ITER:
963 case JUMP_FORWARD:
964 case JUMP_IF_FALSE:
965 case JUMP_IF_TRUE:
966 case SETUP_LOOP:
967 case SETUP_EXCEPT:
968 case SETUP_FINALLY:
969 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
970 SETARG(codestr, i, j);
971 break;
972 }
973 adj = CODESIZE(opcode);
974 while (adj--)
975 codestr[h++] = codestr[i++];
976 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000977 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000978
979 code = PyString_FromStringAndSize((char *)codestr, h);
980 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000981 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000982 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000983 return code;
984
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000985 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000986 if (blocks != NULL)
987 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000988 if (addrmap != NULL)
989 PyMem_Free(addrmap);
990 if (codestr != NULL)
991 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000992 Py_INCREF(code);
993 return code;
994}
995
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000996/* End: Peephole optimizations ----------------------------------------- */
997
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998/*
999
1000Leave this debugging code for just a little longer.
1001
1002static void
1003compiler_display_symbols(PyObject *name, PyObject *symbols)
1004{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001005PyObject *key, *value;
1006int flags;
1007Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001008
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001009fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1010while (PyDict_Next(symbols, &pos, &key, &value)) {
1011flags = PyInt_AsLong(value);
1012fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1013if (flags & DEF_GLOBAL)
1014fprintf(stderr, " declared_global");
1015if (flags & DEF_LOCAL)
1016fprintf(stderr, " local");
1017if (flags & DEF_PARAM)
1018fprintf(stderr, " param");
1019if (flags & DEF_STAR)
1020fprintf(stderr, " stararg");
1021if (flags & DEF_DOUBLESTAR)
1022fprintf(stderr, " starstar");
1023if (flags & DEF_INTUPLE)
1024fprintf(stderr, " tuple");
1025if (flags & DEF_FREE)
1026fprintf(stderr, " free");
1027if (flags & DEF_FREE_GLOBAL)
1028fprintf(stderr, " global");
1029if (flags & DEF_FREE_CLASS)
1030fprintf(stderr, " free/class");
1031if (flags & DEF_IMPORT)
1032fprintf(stderr, " import");
1033fprintf(stderr, "\n");
1034}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035 fprintf(stderr, "\n");
1036}
1037*/
1038
1039static void
1040compiler_unit_check(struct compiler_unit *u)
1041{
1042 basicblock *block;
1043 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1044 assert(block != (void *)0xcbcbcbcb);
1045 assert(block != (void *)0xfbfbfbfb);
1046 assert(block != (void *)0xdbdbdbdb);
1047 if (block->b_instr != NULL) {
1048 assert(block->b_ialloc > 0);
1049 assert(block->b_iused > 0);
1050 assert(block->b_ialloc >= block->b_iused);
1051 }
1052 else {
1053 assert (block->b_iused == 0);
1054 assert (block->b_ialloc == 0);
1055 }
1056 }
1057}
1058
1059static void
1060compiler_unit_free(struct compiler_unit *u)
1061{
1062 basicblock *b, *next;
1063
1064 compiler_unit_check(u);
1065 b = u->u_blocks;
1066 while (b != NULL) {
1067 if (b->b_instr)
1068 PyObject_Free((void *)b->b_instr);
1069 next = b->b_list;
1070 PyObject_Free((void *)b);
1071 b = next;
1072 }
1073 Py_XDECREF(u->u_ste);
1074 Py_XDECREF(u->u_name);
1075 Py_XDECREF(u->u_consts);
1076 Py_XDECREF(u->u_names);
1077 Py_XDECREF(u->u_varnames);
1078 Py_XDECREF(u->u_freevars);
1079 Py_XDECREF(u->u_cellvars);
1080 Py_XDECREF(u->u_private);
1081 PyObject_Free(u);
1082}
1083
1084static int
1085compiler_enter_scope(struct compiler *c, identifier name, void *key,
1086 int lineno)
1087{
1088 struct compiler_unit *u;
1089
1090 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001091 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001092 PyErr_NoMemory();
1093 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001094 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001095 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096 u->u_argcount = 0;
1097 u->u_ste = PySymtable_Lookup(c->c_st, key);
1098 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001099 compiler_unit_free(u);
1100 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001101 }
1102 Py_INCREF(name);
1103 u->u_name = name;
1104 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1105 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1106 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001107 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108
1109 u->u_blocks = NULL;
1110 u->u_tmpname = 0;
1111 u->u_nfblocks = 0;
1112 u->u_firstlineno = lineno;
1113 u->u_lineno = 0;
1114 u->u_lineno_set = false;
1115 u->u_consts = PyDict_New();
1116 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001117 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 return 0;
1119 }
1120 u->u_names = PyDict_New();
1121 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001122 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123 return 0;
1124 }
1125
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001126 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001127
1128 /* Push the old compiler_unit on the stack. */
1129 if (c->u) {
1130 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1131 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001132 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 return 0;
1134 }
1135 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001136 u->u_private = c->u->u_private;
1137 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 }
1139 c->u = u;
1140
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001141 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001142 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143 return 0;
1144
1145 return 1;
1146}
1147
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001148static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149compiler_exit_scope(struct compiler *c)
1150{
1151 int n;
1152 PyObject *wrapper;
1153
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001154 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 compiler_unit_free(c->u);
1156 /* Restore c->u to the parent unit. */
1157 n = PyList_GET_SIZE(c->c_stack) - 1;
1158 if (n >= 0) {
1159 wrapper = PyList_GET_ITEM(c->c_stack, n);
1160 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001161 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001163 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 compiler_unit_check(c->u);
1165 }
1166 else
1167 c->u = NULL;
1168
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001169}
1170
Guido van Rossumc2e20742006-02-27 22:32:47 +00001171/* Allocate a new "anonymous" local variable.
1172 Used by list comprehensions and with statements.
1173*/
1174
1175static PyObject *
1176compiler_new_tmpname(struct compiler *c)
1177{
1178 char tmpname[256];
1179 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1180 return PyString_FromString(tmpname);
1181}
1182
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183/* Allocate a new block and return a pointer to it.
1184 Returns NULL on error.
1185*/
1186
1187static basicblock *
1188compiler_new_block(struct compiler *c)
1189{
1190 basicblock *b;
1191 struct compiler_unit *u;
1192
1193 u = c->u;
1194 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001195 if (b == NULL) {
1196 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001200 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 b->b_list = u->u_blocks;
1202 u->u_blocks = b;
1203 return b;
1204}
1205
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206static basicblock *
1207compiler_use_new_block(struct compiler *c)
1208{
1209 basicblock *block = compiler_new_block(c);
1210 if (block == NULL)
1211 return NULL;
1212 c->u->u_curblock = block;
1213 return block;
1214}
1215
1216static basicblock *
1217compiler_next_block(struct compiler *c)
1218{
1219 basicblock *block = compiler_new_block(c);
1220 if (block == NULL)
1221 return NULL;
1222 c->u->u_curblock->b_next = block;
1223 c->u->u_curblock = block;
1224 return block;
1225}
1226
1227static basicblock *
1228compiler_use_next_block(struct compiler *c, basicblock *block)
1229{
1230 assert(block != NULL);
1231 c->u->u_curblock->b_next = block;
1232 c->u->u_curblock = block;
1233 return block;
1234}
1235
1236/* Returns the offset of the next instruction in the current block's
1237 b_instr array. Resizes the b_instr as necessary.
1238 Returns -1 on failure.
1239 */
1240
1241static int
1242compiler_next_instr(struct compiler *c, basicblock *b)
1243{
1244 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1247 DEFAULT_BLOCK_SIZE);
1248 if (b->b_instr == NULL) {
1249 PyErr_NoMemory();
1250 return -1;
1251 }
1252 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1253 memset((char *)b->b_instr, 0,
1254 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001255 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001256 else if (b->b_iused == b->b_ialloc) {
1257 size_t oldsize, newsize;
1258 oldsize = b->b_ialloc * sizeof(struct instr);
1259 newsize = oldsize << 1;
1260 if (newsize == 0) {
1261 PyErr_NoMemory();
1262 return -1;
1263 }
1264 b->b_ialloc <<= 1;
1265 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1266 if (b->b_instr == NULL)
1267 return -1;
1268 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1269 }
1270 return b->b_iused++;
1271}
1272
Jeremy Hylton12603c42006-04-01 16:18:02 +00001273/* Set the i_lineno member of the instruction at offse off if the
1274 line number for the current expression/statement (?) has not
1275 already been set. If it has been set, the call has no effect.
1276
1277 Every time a new node is b
1278 */
1279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280static void
1281compiler_set_lineno(struct compiler *c, int off)
1282{
1283 basicblock *b;
1284 if (c->u->u_lineno_set)
1285 return;
1286 c->u->u_lineno_set = true;
1287 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001288 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001289}
1290
1291static int
1292opcode_stack_effect(int opcode, int oparg)
1293{
1294 switch (opcode) {
1295 case POP_TOP:
1296 return -1;
1297 case ROT_TWO:
1298 case ROT_THREE:
1299 return 0;
1300 case DUP_TOP:
1301 return 1;
1302 case ROT_FOUR:
1303 return 0;
1304
1305 case UNARY_POSITIVE:
1306 case UNARY_NEGATIVE:
1307 case UNARY_NOT:
1308 case UNARY_CONVERT:
1309 case UNARY_INVERT:
1310 return 0;
1311
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001312 case LIST_APPEND:
1313 return -2;
1314
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315 case BINARY_POWER:
1316 case BINARY_MULTIPLY:
1317 case BINARY_DIVIDE:
1318 case BINARY_MODULO:
1319 case BINARY_ADD:
1320 case BINARY_SUBTRACT:
1321 case BINARY_SUBSCR:
1322 case BINARY_FLOOR_DIVIDE:
1323 case BINARY_TRUE_DIVIDE:
1324 return -1;
1325 case INPLACE_FLOOR_DIVIDE:
1326 case INPLACE_TRUE_DIVIDE:
1327 return -1;
1328
1329 case SLICE+0:
1330 return 1;
1331 case SLICE+1:
1332 return 0;
1333 case SLICE+2:
1334 return 0;
1335 case SLICE+3:
1336 return -1;
1337
1338 case STORE_SLICE+0:
1339 return -2;
1340 case STORE_SLICE+1:
1341 return -3;
1342 case STORE_SLICE+2:
1343 return -3;
1344 case STORE_SLICE+3:
1345 return -4;
1346
1347 case DELETE_SLICE+0:
1348 return -1;
1349 case DELETE_SLICE+1:
1350 return -2;
1351 case DELETE_SLICE+2:
1352 return -2;
1353 case DELETE_SLICE+3:
1354 return -3;
1355
1356 case INPLACE_ADD:
1357 case INPLACE_SUBTRACT:
1358 case INPLACE_MULTIPLY:
1359 case INPLACE_DIVIDE:
1360 case INPLACE_MODULO:
1361 return -1;
1362 case STORE_SUBSCR:
1363 return -3;
1364 case DELETE_SUBSCR:
1365 return -2;
1366
1367 case BINARY_LSHIFT:
1368 case BINARY_RSHIFT:
1369 case BINARY_AND:
1370 case BINARY_XOR:
1371 case BINARY_OR:
1372 return -1;
1373 case INPLACE_POWER:
1374 return -1;
1375 case GET_ITER:
1376 return 0;
1377
1378 case PRINT_EXPR:
1379 return -1;
1380 case PRINT_ITEM:
1381 return -1;
1382 case PRINT_NEWLINE:
1383 return 0;
1384 case PRINT_ITEM_TO:
1385 return -2;
1386 case PRINT_NEWLINE_TO:
1387 return -1;
1388 case INPLACE_LSHIFT:
1389 case INPLACE_RSHIFT:
1390 case INPLACE_AND:
1391 case INPLACE_XOR:
1392 case INPLACE_OR:
1393 return -1;
1394 case BREAK_LOOP:
1395 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001396 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001397 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 case LOAD_LOCALS:
1399 return 1;
1400 case RETURN_VALUE:
1401 return -1;
1402 case IMPORT_STAR:
1403 return -1;
1404 case EXEC_STMT:
1405 return -3;
1406 case YIELD_VALUE:
1407 return 0;
1408
1409 case POP_BLOCK:
1410 return 0;
1411 case END_FINALLY:
1412 return -1; /* or -2 or -3 if exception occurred */
1413 case BUILD_CLASS:
1414 return -2;
1415
1416 case STORE_NAME:
1417 return -1;
1418 case DELETE_NAME:
1419 return 0;
1420 case UNPACK_SEQUENCE:
1421 return oparg-1;
1422 case FOR_ITER:
1423 return 1;
1424
1425 case STORE_ATTR:
1426 return -2;
1427 case DELETE_ATTR:
1428 return -1;
1429 case STORE_GLOBAL:
1430 return -1;
1431 case DELETE_GLOBAL:
1432 return 0;
1433 case DUP_TOPX:
1434 return oparg;
1435 case LOAD_CONST:
1436 return 1;
1437 case LOAD_NAME:
1438 return 1;
1439 case BUILD_TUPLE:
1440 case BUILD_LIST:
1441 return 1-oparg;
1442 case BUILD_MAP:
1443 return 1;
1444 case LOAD_ATTR:
1445 return 0;
1446 case COMPARE_OP:
1447 return -1;
1448 case IMPORT_NAME:
1449 return 0;
1450 case IMPORT_FROM:
1451 return 1;
1452
1453 case JUMP_FORWARD:
1454 case JUMP_IF_FALSE:
1455 case JUMP_IF_TRUE:
1456 case JUMP_ABSOLUTE:
1457 return 0;
1458
1459 case LOAD_GLOBAL:
1460 return 1;
1461
1462 case CONTINUE_LOOP:
1463 return 0;
1464 case SETUP_LOOP:
1465 return 0;
1466 case SETUP_EXCEPT:
1467 case SETUP_FINALLY:
1468 return 3; /* actually pushed by an exception */
1469
1470 case LOAD_FAST:
1471 return 1;
1472 case STORE_FAST:
1473 return -1;
1474 case DELETE_FAST:
1475 return 0;
1476
1477 case RAISE_VARARGS:
1478 return -oparg;
1479#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1480 case CALL_FUNCTION:
1481 return -NARGS(oparg);
1482 case CALL_FUNCTION_VAR:
1483 case CALL_FUNCTION_KW:
1484 return -NARGS(oparg)-1;
1485 case CALL_FUNCTION_VAR_KW:
1486 return -NARGS(oparg)-2;
1487#undef NARGS
1488 case MAKE_FUNCTION:
1489 return -oparg;
1490 case BUILD_SLICE:
1491 if (oparg == 3)
1492 return -2;
1493 else
1494 return -1;
1495
1496 case MAKE_CLOSURE:
1497 return -oparg;
1498 case LOAD_CLOSURE:
1499 return 1;
1500 case LOAD_DEREF:
1501 return 1;
1502 case STORE_DEREF:
1503 return -1;
1504 default:
1505 fprintf(stderr, "opcode = %d\n", opcode);
1506 Py_FatalError("opcode_stack_effect()");
1507
1508 }
1509 return 0; /* not reachable */
1510}
1511
1512/* Add an opcode with no argument.
1513 Returns 0 on failure, 1 on success.
1514*/
1515
1516static int
1517compiler_addop(struct compiler *c, int opcode)
1518{
1519 basicblock *b;
1520 struct instr *i;
1521 int off;
1522 off = compiler_next_instr(c, c->u->u_curblock);
1523 if (off < 0)
1524 return 0;
1525 b = c->u->u_curblock;
1526 i = &b->b_instr[off];
1527 i->i_opcode = opcode;
1528 i->i_hasarg = 0;
1529 if (opcode == RETURN_VALUE)
1530 b->b_return = 1;
1531 compiler_set_lineno(c, off);
1532 return 1;
1533}
1534
1535static int
1536compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1537{
1538 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001539 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001541 /* necessary to make sure types aren't coerced (e.g., int and long) */
1542 t = PyTuple_Pack(2, o, o->ob_type);
1543 if (t == NULL)
1544 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545
1546 v = PyDict_GetItem(dict, t);
1547 if (!v) {
1548 arg = PyDict_Size(dict);
1549 v = PyInt_FromLong(arg);
1550 if (!v) {
1551 Py_DECREF(t);
1552 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001554 if (PyDict_SetItem(dict, t, v) < 0) {
1555 Py_DECREF(t);
1556 Py_DECREF(v);
1557 return -1;
1558 }
1559 Py_DECREF(v);
1560 }
1561 else
1562 arg = PyInt_AsLong(v);
1563 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001564 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565}
1566
1567static int
1568compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1569 PyObject *o)
1570{
1571 int arg = compiler_add_o(c, dict, o);
1572 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001573 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001574 return compiler_addop_i(c, opcode, arg);
1575}
1576
1577static int
1578compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001579 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580{
1581 int arg;
1582 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1583 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001584 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585 arg = compiler_add_o(c, dict, mangled);
1586 Py_DECREF(mangled);
1587 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001588 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589 return compiler_addop_i(c, opcode, arg);
1590}
1591
1592/* Add an opcode with an integer argument.
1593 Returns 0 on failure, 1 on success.
1594*/
1595
1596static int
1597compiler_addop_i(struct compiler *c, int opcode, int oparg)
1598{
1599 struct instr *i;
1600 int off;
1601 off = compiler_next_instr(c, c->u->u_curblock);
1602 if (off < 0)
1603 return 0;
1604 i = &c->u->u_curblock->b_instr[off];
1605 i->i_opcode = opcode;
1606 i->i_oparg = oparg;
1607 i->i_hasarg = 1;
1608 compiler_set_lineno(c, off);
1609 return 1;
1610}
1611
1612static int
1613compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1614{
1615 struct instr *i;
1616 int off;
1617
1618 assert(b != NULL);
1619 off = compiler_next_instr(c, c->u->u_curblock);
1620 if (off < 0)
1621 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 i = &c->u->u_curblock->b_instr[off];
1623 i->i_opcode = opcode;
1624 i->i_target = b;
1625 i->i_hasarg = 1;
1626 if (absolute)
1627 i->i_jabs = 1;
1628 else
1629 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001630 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631 return 1;
1632}
1633
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001634/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1635 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636 it as the current block. NEXT_BLOCK() also creates an implicit jump
1637 from the current block to the new block.
1638*/
1639
1640/* XXX The returns inside these macros make it impossible to decref
1641 objects created in the local function.
1642*/
1643
1644
1645#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001646 if (compiler_use_new_block((C)) == NULL) \
1647 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648}
1649
1650#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001651 if (compiler_next_block((C)) == NULL) \
1652 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653}
1654
1655#define ADDOP(C, OP) { \
1656 if (!compiler_addop((C), (OP))) \
1657 return 0; \
1658}
1659
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001660#define ADDOP_IN_SCOPE(C, OP) { \
1661 if (!compiler_addop((C), (OP))) { \
1662 compiler_exit_scope(c); \
1663 return 0; \
1664 } \
1665}
1666
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001667#define ADDOP_O(C, OP, O, TYPE) { \
1668 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1669 return 0; \
1670}
1671
1672#define ADDOP_NAME(C, OP, O, TYPE) { \
1673 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1674 return 0; \
1675}
1676
1677#define ADDOP_I(C, OP, O) { \
1678 if (!compiler_addop_i((C), (OP), (O))) \
1679 return 0; \
1680}
1681
1682#define ADDOP_JABS(C, OP, O) { \
1683 if (!compiler_addop_j((C), (OP), (O), 1)) \
1684 return 0; \
1685}
1686
1687#define ADDOP_JREL(C, OP, O) { \
1688 if (!compiler_addop_j((C), (OP), (O), 0)) \
1689 return 0; \
1690}
1691
1692/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1693 the ASDL name to synthesize the name of the C type and the visit function.
1694*/
1695
1696#define VISIT(C, TYPE, V) {\
1697 if (!compiler_visit_ ## TYPE((C), (V))) \
1698 return 0; \
1699}
1700
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001701#define VISIT_IN_SCOPE(C, TYPE, V) {\
1702 if (!compiler_visit_ ## TYPE((C), (V))) { \
1703 compiler_exit_scope(c); \
1704 return 0; \
1705 } \
1706}
1707
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708#define VISIT_SLICE(C, V, CTX) {\
1709 if (!compiler_visit_slice((C), (V), (CTX))) \
1710 return 0; \
1711}
1712
1713#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001714 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001715 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001716 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1717 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718 if (!compiler_visit_ ## TYPE((C), elt)) \
1719 return 0; \
1720 } \
1721}
1722
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001723#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001724 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001725 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001726 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1727 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001728 if (!compiler_visit_ ## TYPE((C), elt)) { \
1729 compiler_exit_scope(c); \
1730 return 0; \
1731 } \
1732 } \
1733}
1734
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735static int
1736compiler_isdocstring(stmt_ty s)
1737{
1738 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001739 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001740 return s->v.Expr.value->kind == Str_kind;
1741}
1742
1743/* Compile a sequence of statements, checking for a docstring. */
1744
1745static int
1746compiler_body(struct compiler *c, asdl_seq *stmts)
1747{
1748 int i = 0;
1749 stmt_ty st;
1750
1751 if (!asdl_seq_LEN(stmts))
1752 return 1;
1753 st = asdl_seq_GET(stmts, 0);
1754 if (compiler_isdocstring(st)) {
1755 i = 1;
1756 VISIT(c, expr, st->v.Expr.value);
1757 if (!compiler_nameop(c, __doc__, Store))
1758 return 0;
1759 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001760 for (; i < asdl_seq_LEN(stmts); i++)
1761 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762 return 1;
1763}
1764
1765static PyCodeObject *
1766compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001767{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001768 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001769 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 static PyObject *module;
1771 if (!module) {
1772 module = PyString_FromString("<module>");
1773 if (!module)
1774 return NULL;
1775 }
1776 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001777 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778 switch (mod->kind) {
1779 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001780 if (!compiler_body(c, mod->v.Module.body)) {
1781 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001783 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 break;
1785 case Interactive_kind:
1786 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001787 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 break;
1789 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001790 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001791 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 break;
1793 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001794 PyErr_SetString(PyExc_SystemError,
1795 "suite should not be possible");
1796 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001797 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001798 PyErr_Format(PyExc_SystemError,
1799 "module kind %d should not be possible",
1800 mod->kind);
1801 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001802 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803 co = assemble(c, addNone);
1804 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001805 return co;
1806}
1807
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808/* The test for LOCAL must come before the test for FREE in order to
1809 handle classes where name is both local and free. The local var is
1810 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001811*/
1812
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813static int
1814get_ref_type(struct compiler *c, PyObject *name)
1815{
1816 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001817 if (scope == 0) {
1818 char buf[350];
1819 PyOS_snprintf(buf, sizeof(buf),
1820 "unknown scope for %.100s in %.100s(%s) in %s\n"
1821 "symbols: %s\nlocals: %s\nglobals: %s\n",
1822 PyString_AS_STRING(name),
1823 PyString_AS_STRING(c->u->u_name),
1824 PyObject_REPR(c->u->u_ste->ste_id),
1825 c->c_filename,
1826 PyObject_REPR(c->u->u_ste->ste_symbols),
1827 PyObject_REPR(c->u->u_varnames),
1828 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001830 Py_FatalError(buf);
1831 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001832
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001833 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834}
1835
1836static int
1837compiler_lookup_arg(PyObject *dict, PyObject *name)
1838{
1839 PyObject *k, *v;
1840 k = Py_BuildValue("(OO)", name, name->ob_type);
1841 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001842 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001844 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001846 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 return PyInt_AS_LONG(v);
1848}
1849
1850static int
1851compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1852{
1853 int i, free = PyCode_GetNumFree(co);
1854 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001855 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1856 ADDOP_I(c, MAKE_FUNCTION, args);
1857 return 1;
1858 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 for (i = 0; i < free; ++i) {
1860 /* Bypass com_addop_varname because it will generate
1861 LOAD_DEREF but LOAD_CLOSURE is needed.
1862 */
1863 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1864 int arg, reftype;
1865
1866 /* Special case: If a class contains a method with a
1867 free variable that has the same name as a method,
1868 the name will be considered free *and* local in the
1869 class. It should be handled by the closure, as
1870 well as by the normal name loookup logic.
1871 */
1872 reftype = get_ref_type(c, name);
1873 if (reftype == CELL)
1874 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1875 else /* (reftype == FREE) */
1876 arg = compiler_lookup_arg(c->u->u_freevars, name);
1877 if (arg == -1) {
1878 printf("lookup %s in %s %d %d\n"
1879 "freevars of %s: %s\n",
1880 PyObject_REPR(name),
1881 PyString_AS_STRING(c->u->u_name),
1882 reftype, arg,
1883 PyString_AS_STRING(co->co_name),
1884 PyObject_REPR(co->co_freevars));
1885 Py_FatalError("compiler_make_closure()");
1886 }
1887 ADDOP_I(c, LOAD_CLOSURE, arg);
1888 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001889 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001891 ADDOP_I(c, MAKE_CLOSURE, args);
1892 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893}
1894
1895static int
1896compiler_decorators(struct compiler *c, asdl_seq* decos)
1897{
1898 int i;
1899
1900 if (!decos)
1901 return 1;
1902
1903 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1904 VISIT(c, expr, asdl_seq_GET(decos, i));
1905 }
1906 return 1;
1907}
1908
1909static int
1910compiler_arguments(struct compiler *c, arguments_ty args)
1911{
1912 int i;
1913 int n = asdl_seq_LEN(args->args);
1914 /* Correctly handle nested argument lists */
1915 for (i = 0; i < n; i++) {
1916 expr_ty arg = asdl_seq_GET(args->args, i);
1917 if (arg->kind == Tuple_kind) {
1918 PyObject *id = PyString_FromFormat(".%d", i);
1919 if (id == NULL) {
1920 return 0;
1921 }
1922 if (!compiler_nameop(c, id, Load)) {
1923 Py_DECREF(id);
1924 return 0;
1925 }
1926 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001927 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928 }
1929 }
1930 return 1;
1931}
1932
1933static int
1934compiler_function(struct compiler *c, stmt_ty s)
1935{
1936 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001937 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 arguments_ty args = s->v.FunctionDef.args;
1939 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001940 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 int i, n, docstring;
1942
1943 assert(s->kind == FunctionDef_kind);
1944
1945 if (!compiler_decorators(c, decos))
1946 return 0;
1947 if (args->defaults)
1948 VISIT_SEQ(c, expr, args->defaults);
1949 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1950 s->lineno))
1951 return 0;
1952
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001953 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1954 docstring = compiler_isdocstring(st);
1955 if (docstring)
1956 first_const = st->v.Expr.value->v.Str.s;
1957 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001958 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001960 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001962 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 compiler_arguments(c, args);
1964
1965 c->u->u_argcount = asdl_seq_LEN(args->args);
1966 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001967 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 for (i = docstring; i < n; i++) {
1969 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1970 if (i == 0 && s2->kind == Expr_kind &&
1971 s2->v.Expr.value->kind == Str_kind)
1972 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001973 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 }
1975 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001976 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 if (co == NULL)
1978 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001980 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001981 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982
1983 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1984 ADDOP_I(c, CALL_FUNCTION, 1);
1985 }
1986
1987 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1988}
1989
1990static int
1991compiler_class(struct compiler *c, stmt_ty s)
1992{
1993 int n;
1994 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001995 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 /* push class name on stack, needed by BUILD_CLASS */
1997 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1998 /* push the tuple of base classes on the stack */
1999 n = asdl_seq_LEN(s->v.ClassDef.bases);
2000 if (n > 0)
2001 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
2002 ADDOP_I(c, BUILD_TUPLE, n);
2003 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2004 s->lineno))
2005 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002006 c->u->u_private = s->v.ClassDef.name;
2007 Py_INCREF(c->u->u_private);
2008 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 if (!str || !compiler_nameop(c, str, Load)) {
2010 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002011 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002013 }
2014
2015 Py_DECREF(str);
2016 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 if (!str || !compiler_nameop(c, str, Store)) {
2018 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002019 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002021 }
2022 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002024 if (!compiler_body(c, s->v.ClassDef.body)) {
2025 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002027 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002029 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2030 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002032 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 if (co == NULL)
2034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002036 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002037 Py_DECREF(co);
2038
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002039 ADDOP_I(c, CALL_FUNCTION, 0);
2040 ADDOP(c, BUILD_CLASS);
2041 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2042 return 0;
2043 return 1;
2044}
2045
2046static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002047compiler_ifexp(struct compiler *c, expr_ty e)
2048{
2049 basicblock *end, *next;
2050
2051 assert(e->kind == IfExp_kind);
2052 end = compiler_new_block(c);
2053 if (end == NULL)
2054 return 0;
2055 next = compiler_new_block(c);
2056 if (next == NULL)
2057 return 0;
2058 VISIT(c, expr, e->v.IfExp.test);
2059 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2060 ADDOP(c, POP_TOP);
2061 VISIT(c, expr, e->v.IfExp.body);
2062 ADDOP_JREL(c, JUMP_FORWARD, end);
2063 compiler_use_next_block(c, next);
2064 ADDOP(c, POP_TOP);
2065 VISIT(c, expr, e->v.IfExp.orelse);
2066 compiler_use_next_block(c, end);
2067 return 1;
2068}
2069
2070static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071compiler_lambda(struct compiler *c, expr_ty e)
2072{
2073 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002074 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 arguments_ty args = e->v.Lambda.args;
2076 assert(e->kind == Lambda_kind);
2077
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002078 if (!name) {
2079 name = PyString_InternFromString("<lambda>");
2080 if (!name)
2081 return 0;
2082 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083
2084 if (args->defaults)
2085 VISIT_SEQ(c, expr, args->defaults);
2086 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2087 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002088
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002089 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 compiler_arguments(c, args);
2091
2092 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002093 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2094 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002096 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097 if (co == NULL)
2098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002100 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002101 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102
2103 return 1;
2104}
2105
2106static int
2107compiler_print(struct compiler *c, stmt_ty s)
2108{
2109 int i, n;
2110 bool dest;
2111
2112 assert(s->kind == Print_kind);
2113 n = asdl_seq_LEN(s->v.Print.values);
2114 dest = false;
2115 if (s->v.Print.dest) {
2116 VISIT(c, expr, s->v.Print.dest);
2117 dest = true;
2118 }
2119 for (i = 0; i < n; i++) {
2120 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2121 if (dest) {
2122 ADDOP(c, DUP_TOP);
2123 VISIT(c, expr, e);
2124 ADDOP(c, ROT_TWO);
2125 ADDOP(c, PRINT_ITEM_TO);
2126 }
2127 else {
2128 VISIT(c, expr, e);
2129 ADDOP(c, PRINT_ITEM);
2130 }
2131 }
2132 if (s->v.Print.nl) {
2133 if (dest)
2134 ADDOP(c, PRINT_NEWLINE_TO)
2135 else
2136 ADDOP(c, PRINT_NEWLINE)
2137 }
2138 else if (dest)
2139 ADDOP(c, POP_TOP);
2140 return 1;
2141}
2142
2143static int
2144compiler_if(struct compiler *c, stmt_ty s)
2145{
2146 basicblock *end, *next;
2147
2148 assert(s->kind == If_kind);
2149 end = compiler_new_block(c);
2150 if (end == NULL)
2151 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002152 next = compiler_new_block(c);
2153 if (next == NULL)
2154 return 0;
2155 VISIT(c, expr, s->v.If.test);
2156 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2157 ADDOP(c, POP_TOP);
2158 VISIT_SEQ(c, stmt, s->v.If.body);
2159 ADDOP_JREL(c, JUMP_FORWARD, end);
2160 compiler_use_next_block(c, next);
2161 ADDOP(c, POP_TOP);
2162 if (s->v.If.orelse)
2163 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002164 compiler_use_next_block(c, end);
2165 return 1;
2166}
2167
2168static int
2169compiler_for(struct compiler *c, stmt_ty s)
2170{
2171 basicblock *start, *cleanup, *end;
2172
2173 start = compiler_new_block(c);
2174 cleanup = compiler_new_block(c);
2175 end = compiler_new_block(c);
2176 if (start == NULL || end == NULL || cleanup == NULL)
2177 return 0;
2178 ADDOP_JREL(c, SETUP_LOOP, end);
2179 if (!compiler_push_fblock(c, LOOP, start))
2180 return 0;
2181 VISIT(c, expr, s->v.For.iter);
2182 ADDOP(c, GET_ITER);
2183 compiler_use_next_block(c, start);
2184 ADDOP_JREL(c, FOR_ITER, cleanup);
2185 VISIT(c, expr, s->v.For.target);
2186 VISIT_SEQ(c, stmt, s->v.For.body);
2187 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2188 compiler_use_next_block(c, cleanup);
2189 ADDOP(c, POP_BLOCK);
2190 compiler_pop_fblock(c, LOOP, start);
2191 VISIT_SEQ(c, stmt, s->v.For.orelse);
2192 compiler_use_next_block(c, end);
2193 return 1;
2194}
2195
2196static int
2197compiler_while(struct compiler *c, stmt_ty s)
2198{
2199 basicblock *loop, *orelse, *end, *anchor = NULL;
2200 int constant = expr_constant(s->v.While.test);
2201
2202 if (constant == 0)
2203 return 1;
2204 loop = compiler_new_block(c);
2205 end = compiler_new_block(c);
2206 if (constant == -1) {
2207 anchor = compiler_new_block(c);
2208 if (anchor == NULL)
2209 return 0;
2210 }
2211 if (loop == NULL || end == NULL)
2212 return 0;
2213 if (s->v.While.orelse) {
2214 orelse = compiler_new_block(c);
2215 if (orelse == NULL)
2216 return 0;
2217 }
2218 else
2219 orelse = NULL;
2220
2221 ADDOP_JREL(c, SETUP_LOOP, end);
2222 compiler_use_next_block(c, loop);
2223 if (!compiler_push_fblock(c, LOOP, loop))
2224 return 0;
2225 if (constant == -1) {
2226 VISIT(c, expr, s->v.While.test);
2227 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2228 ADDOP(c, POP_TOP);
2229 }
2230 VISIT_SEQ(c, stmt, s->v.While.body);
2231 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2232
2233 /* XXX should the two POP instructions be in a separate block
2234 if there is no else clause ?
2235 */
2236
2237 if (constant == -1) {
2238 compiler_use_next_block(c, anchor);
2239 ADDOP(c, POP_TOP);
2240 ADDOP(c, POP_BLOCK);
2241 }
2242 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002243 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002244 VISIT_SEQ(c, stmt, s->v.While.orelse);
2245 compiler_use_next_block(c, end);
2246
2247 return 1;
2248}
2249
2250static int
2251compiler_continue(struct compiler *c)
2252{
2253 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2254 int i;
2255
2256 if (!c->u->u_nfblocks)
2257 return compiler_error(c, LOOP_ERROR_MSG);
2258 i = c->u->u_nfblocks - 1;
2259 switch (c->u->u_fblock[i].fb_type) {
2260 case LOOP:
2261 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2262 break;
2263 case EXCEPT:
2264 case FINALLY_TRY:
2265 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2266 ;
2267 if (i == -1)
2268 return compiler_error(c, LOOP_ERROR_MSG);
2269 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2270 break;
2271 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002272 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002273 "'continue' not supported inside 'finally' clause");
2274 }
2275
2276 return 1;
2277}
2278
2279/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2280
2281 SETUP_FINALLY L
2282 <code for body>
2283 POP_BLOCK
2284 LOAD_CONST <None>
2285 L: <code for finalbody>
2286 END_FINALLY
2287
2288 The special instructions use the block stack. Each block
2289 stack entry contains the instruction that created it (here
2290 SETUP_FINALLY), the level of the value stack at the time the
2291 block stack entry was created, and a label (here L).
2292
2293 SETUP_FINALLY:
2294 Pushes the current value stack level and the label
2295 onto the block stack.
2296 POP_BLOCK:
2297 Pops en entry from the block stack, and pops the value
2298 stack until its level is the same as indicated on the
2299 block stack. (The label is ignored.)
2300 END_FINALLY:
2301 Pops a variable number of entries from the *value* stack
2302 and re-raises the exception they specify. The number of
2303 entries popped depends on the (pseudo) exception type.
2304
2305 The block stack is unwound when an exception is raised:
2306 when a SETUP_FINALLY entry is found, the exception is pushed
2307 onto the value stack (and the exception condition is cleared),
2308 and the interpreter jumps to the label gotten from the block
2309 stack.
2310*/
2311
2312static int
2313compiler_try_finally(struct compiler *c, stmt_ty s)
2314{
2315 basicblock *body, *end;
2316 body = compiler_new_block(c);
2317 end = compiler_new_block(c);
2318 if (body == NULL || end == NULL)
2319 return 0;
2320
2321 ADDOP_JREL(c, SETUP_FINALLY, end);
2322 compiler_use_next_block(c, body);
2323 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2324 return 0;
2325 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2326 ADDOP(c, POP_BLOCK);
2327 compiler_pop_fblock(c, FINALLY_TRY, body);
2328
2329 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2330 compiler_use_next_block(c, end);
2331 if (!compiler_push_fblock(c, FINALLY_END, end))
2332 return 0;
2333 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2334 ADDOP(c, END_FINALLY);
2335 compiler_pop_fblock(c, FINALLY_END, end);
2336
2337 return 1;
2338}
2339
2340/*
2341 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2342 (The contents of the value stack is shown in [], with the top
2343 at the right; 'tb' is trace-back info, 'val' the exception's
2344 associated value, and 'exc' the exception.)
2345
2346 Value stack Label Instruction Argument
2347 [] SETUP_EXCEPT L1
2348 [] <code for S>
2349 [] POP_BLOCK
2350 [] JUMP_FORWARD L0
2351
2352 [tb, val, exc] L1: DUP )
2353 [tb, val, exc, exc] <evaluate E1> )
2354 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2355 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2356 [tb, val, exc, 1] POP )
2357 [tb, val, exc] POP
2358 [tb, val] <assign to V1> (or POP if no V1)
2359 [tb] POP
2360 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002361 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
2363 [tb, val, exc, 0] L2: POP
2364 [tb, val, exc] DUP
2365 .............................etc.......................
2366
2367 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002368 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369
2370 [] L0: <next statement>
2371
2372 Of course, parts are not generated if Vi or Ei is not present.
2373*/
2374static int
2375compiler_try_except(struct compiler *c, stmt_ty s)
2376{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002377 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378 int i, n;
2379
2380 body = compiler_new_block(c);
2381 except = compiler_new_block(c);
2382 orelse = compiler_new_block(c);
2383 end = compiler_new_block(c);
2384 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2385 return 0;
2386 ADDOP_JREL(c, SETUP_EXCEPT, except);
2387 compiler_use_next_block(c, body);
2388 if (!compiler_push_fblock(c, EXCEPT, body))
2389 return 0;
2390 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2391 ADDOP(c, POP_BLOCK);
2392 compiler_pop_fblock(c, EXCEPT, body);
2393 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2394 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2395 compiler_use_next_block(c, except);
2396 for (i = 0; i < n; i++) {
2397 excepthandler_ty handler = asdl_seq_GET(
2398 s->v.TryExcept.handlers, i);
2399 if (!handler->type && i < n-1)
2400 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00002401 c->u->u_lineno_set = false;
2402 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002403 except = compiler_new_block(c);
2404 if (except == NULL)
2405 return 0;
2406 if (handler->type) {
2407 ADDOP(c, DUP_TOP);
2408 VISIT(c, expr, handler->type);
2409 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2410 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2411 ADDOP(c, POP_TOP);
2412 }
2413 ADDOP(c, POP_TOP);
2414 if (handler->name) {
2415 VISIT(c, expr, handler->name);
2416 }
2417 else {
2418 ADDOP(c, POP_TOP);
2419 }
2420 ADDOP(c, POP_TOP);
2421 VISIT_SEQ(c, stmt, handler->body);
2422 ADDOP_JREL(c, JUMP_FORWARD, end);
2423 compiler_use_next_block(c, except);
2424 if (handler->type)
2425 ADDOP(c, POP_TOP);
2426 }
2427 ADDOP(c, END_FINALLY);
2428 compiler_use_next_block(c, orelse);
2429 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2430 compiler_use_next_block(c, end);
2431 return 1;
2432}
2433
2434static int
2435compiler_import_as(struct compiler *c, identifier name, identifier asname)
2436{
2437 /* The IMPORT_NAME opcode was already generated. This function
2438 merely needs to bind the result to a name.
2439
2440 If there is a dot in name, we need to split it and emit a
2441 LOAD_ATTR for each name.
2442 */
2443 const char *src = PyString_AS_STRING(name);
2444 const char *dot = strchr(src, '.');
2445 if (dot) {
2446 /* Consume the base module name to get the first attribute */
2447 src = dot + 1;
2448 while (dot) {
2449 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002450 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002452 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002454 if (!attr)
2455 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002457 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002458 src = dot + 1;
2459 }
2460 }
2461 return compiler_nameop(c, asname, Store);
2462}
2463
2464static int
2465compiler_import(struct compiler *c, stmt_ty s)
2466{
2467 /* The Import node stores a module name like a.b.c as a single
2468 string. This is convenient for all cases except
2469 import a.b.c as d
2470 where we need to parse that string to extract the individual
2471 module names.
2472 XXX Perhaps change the representation to make this case simpler?
2473 */
2474 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 for (i = 0; i < n; i++) {
2477 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2478 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002479 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002480
Neal Norwitzcbce2802006-04-03 06:26:32 +00002481 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002482 level = PyInt_FromLong(0);
2483 else
2484 level = PyInt_FromLong(-1);
2485
2486 if (level == NULL)
2487 return 0;
2488
2489 ADDOP_O(c, LOAD_CONST, level, consts);
2490 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002491 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2492 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2493
2494 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002495 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002496 if (!r)
2497 return r;
2498 }
2499 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 identifier tmp = alias->name;
2501 const char *base = PyString_AS_STRING(alias->name);
2502 char *dot = strchr(base, '.');
2503 if (dot)
2504 tmp = PyString_FromStringAndSize(base,
2505 dot - base);
2506 r = compiler_nameop(c, tmp, Store);
2507 if (dot) {
2508 Py_DECREF(tmp);
2509 }
2510 if (!r)
2511 return r;
2512 }
2513 }
2514 return 1;
2515}
2516
2517static int
2518compiler_from_import(struct compiler *c, stmt_ty s)
2519{
2520 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521
2522 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002523 PyObject *level;
2524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 if (!names)
2526 return 0;
2527
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002528 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002529 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002530 level = PyInt_FromLong(-1);
2531 else
2532 level = PyInt_FromLong(s->v.ImportFrom.level);
2533
2534 if (!level) {
2535 Py_DECREF(names);
2536 return 0;
2537 }
2538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 /* build up the names */
2540 for (i = 0; i < n; i++) {
2541 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2542 Py_INCREF(alias->name);
2543 PyTuple_SET_ITEM(names, i, alias->name);
2544 }
2545
2546 if (s->lineno > c->c_future->ff_lineno) {
2547 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2548 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002549 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 Py_DECREF(names);
2551 return compiler_error(c,
2552 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002553 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554
2555 }
2556 }
2557
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002558 ADDOP_O(c, LOAD_CONST, level, consts);
2559 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002561 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2563 for (i = 0; i < n; i++) {
2564 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2565 identifier store_name;
2566
2567 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2568 assert(n == 1);
2569 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 }
2572
2573 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2574 store_name = alias->name;
2575 if (alias->asname)
2576 store_name = alias->asname;
2577
2578 if (!compiler_nameop(c, store_name, Store)) {
2579 Py_DECREF(names);
2580 return 0;
2581 }
2582 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002583 /* remove imported module */
2584 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 return 1;
2586}
2587
2588static int
2589compiler_assert(struct compiler *c, stmt_ty s)
2590{
2591 static PyObject *assertion_error = NULL;
2592 basicblock *end;
2593
2594 if (Py_OptimizeFlag)
2595 return 1;
2596 if (assertion_error == NULL) {
2597 assertion_error = PyString_FromString("AssertionError");
2598 if (assertion_error == NULL)
2599 return 0;
2600 }
2601 VISIT(c, expr, s->v.Assert.test);
2602 end = compiler_new_block(c);
2603 if (end == NULL)
2604 return 0;
2605 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2606 ADDOP(c, POP_TOP);
2607 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2608 if (s->v.Assert.msg) {
2609 VISIT(c, expr, s->v.Assert.msg);
2610 ADDOP_I(c, RAISE_VARARGS, 2);
2611 }
2612 else {
2613 ADDOP_I(c, RAISE_VARARGS, 1);
2614 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002615 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 ADDOP(c, POP_TOP);
2617 return 1;
2618}
2619
2620static int
2621compiler_visit_stmt(struct compiler *c, stmt_ty s)
2622{
2623 int i, n;
2624
Jeremy Hylton12603c42006-04-01 16:18:02 +00002625 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 c->u->u_lineno = s->lineno;
2627 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002628
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 if (c->u->u_ste->ste_type != FunctionBlock)
2636 return compiler_error(c, "'return' outside function");
2637 if (s->v.Return.value) {
2638 if (c->u->u_ste->ste_generator) {
2639 return compiler_error(c,
2640 "'return' with argument inside generator");
2641 }
2642 VISIT(c, expr, s->v.Return.value);
2643 }
2644 else
2645 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2646 ADDOP(c, RETURN_VALUE);
2647 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002648 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 VISIT_SEQ(c, expr, s->v.Delete.targets)
2650 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 n = asdl_seq_LEN(s->v.Assign.targets);
2653 VISIT(c, expr, s->v.Assign.value);
2654 for (i = 0; i < n; i++) {
2655 if (i < n - 1)
2656 ADDOP(c, DUP_TOP);
2657 VISIT(c, expr,
2658 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2659 }
2660 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002671 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 n = 0;
2673 if (s->v.Raise.type) {
2674 VISIT(c, expr, s->v.Raise.type);
2675 n++;
2676 if (s->v.Raise.inst) {
2677 VISIT(c, expr, s->v.Raise.inst);
2678 n++;
2679 if (s->v.Raise.tback) {
2680 VISIT(c, expr, s->v.Raise.tback);
2681 n++;
2682 }
2683 }
2684 }
2685 ADDOP_I(c, RAISE_VARARGS, n);
2686 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 VISIT(c, expr, s->v.Exec.body);
2699 if (s->v.Exec.globals) {
2700 VISIT(c, expr, s->v.Exec.globals);
2701 if (s->v.Exec.locals) {
2702 VISIT(c, expr, s->v.Exec.locals);
2703 } else {
2704 ADDOP(c, DUP_TOP);
2705 }
2706 } else {
2707 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2708 ADDOP(c, DUP_TOP);
2709 }
2710 ADDOP(c, EXEC_STMT);
2711 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002714 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 VISIT(c, expr, s->v.Expr.value);
2716 if (c->c_interactive && c->c_nestlevel <= 1) {
2717 ADDOP(c, PRINT_EXPR);
2718 }
2719 else {
2720 ADDOP(c, POP_TOP);
2721 }
2722 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002723 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002725 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726 if (!c->u->u_nfblocks)
2727 return compiler_error(c, "'break' outside loop");
2728 ADDOP(c, BREAK_LOOP);
2729 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002732 case With_kind:
2733 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 }
2735 return 1;
2736}
2737
2738static int
2739unaryop(unaryop_ty op)
2740{
2741 switch (op) {
2742 case Invert:
2743 return UNARY_INVERT;
2744 case Not:
2745 return UNARY_NOT;
2746 case UAdd:
2747 return UNARY_POSITIVE;
2748 case USub:
2749 return UNARY_NEGATIVE;
2750 }
2751 return 0;
2752}
2753
2754static int
2755binop(struct compiler *c, operator_ty op)
2756{
2757 switch (op) {
2758 case Add:
2759 return BINARY_ADD;
2760 case Sub:
2761 return BINARY_SUBTRACT;
2762 case Mult:
2763 return BINARY_MULTIPLY;
2764 case Div:
2765 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2766 return BINARY_TRUE_DIVIDE;
2767 else
2768 return BINARY_DIVIDE;
2769 case Mod:
2770 return BINARY_MODULO;
2771 case Pow:
2772 return BINARY_POWER;
2773 case LShift:
2774 return BINARY_LSHIFT;
2775 case RShift:
2776 return BINARY_RSHIFT;
2777 case BitOr:
2778 return BINARY_OR;
2779 case BitXor:
2780 return BINARY_XOR;
2781 case BitAnd:
2782 return BINARY_AND;
2783 case FloorDiv:
2784 return BINARY_FLOOR_DIVIDE;
2785 }
2786 return 0;
2787}
2788
2789static int
2790cmpop(cmpop_ty op)
2791{
2792 switch (op) {
2793 case Eq:
2794 return PyCmp_EQ;
2795 case NotEq:
2796 return PyCmp_NE;
2797 case Lt:
2798 return PyCmp_LT;
2799 case LtE:
2800 return PyCmp_LE;
2801 case Gt:
2802 return PyCmp_GT;
2803 case GtE:
2804 return PyCmp_GE;
2805 case Is:
2806 return PyCmp_IS;
2807 case IsNot:
2808 return PyCmp_IS_NOT;
2809 case In:
2810 return PyCmp_IN;
2811 case NotIn:
2812 return PyCmp_NOT_IN;
2813 }
2814 return PyCmp_BAD;
2815}
2816
2817static int
2818inplace_binop(struct compiler *c, operator_ty op)
2819{
2820 switch (op) {
2821 case Add:
2822 return INPLACE_ADD;
2823 case Sub:
2824 return INPLACE_SUBTRACT;
2825 case Mult:
2826 return INPLACE_MULTIPLY;
2827 case Div:
2828 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2829 return INPLACE_TRUE_DIVIDE;
2830 else
2831 return INPLACE_DIVIDE;
2832 case Mod:
2833 return INPLACE_MODULO;
2834 case Pow:
2835 return INPLACE_POWER;
2836 case LShift:
2837 return INPLACE_LSHIFT;
2838 case RShift:
2839 return INPLACE_RSHIFT;
2840 case BitOr:
2841 return INPLACE_OR;
2842 case BitXor:
2843 return INPLACE_XOR;
2844 case BitAnd:
2845 return INPLACE_AND;
2846 case FloorDiv:
2847 return INPLACE_FLOOR_DIVIDE;
2848 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002849 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002850 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851 return 0;
2852}
2853
2854static int
2855compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2856{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002857 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2859
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002861 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 /* XXX AugStore isn't used anywhere! */
2863
2864 /* First check for assignment to __debug__. Param? */
2865 if ((ctx == Store || ctx == AugStore || ctx == Del)
2866 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2867 return compiler_error(c, "can not assign to __debug__");
2868 }
2869
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002870 mangled = _Py_Mangle(c->u->u_private, name);
2871 if (!mangled)
2872 return 0;
2873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 op = 0;
2875 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002876 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877 switch (scope) {
2878 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002879 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880 optype = OP_DEREF;
2881 break;
2882 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002883 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 optype = OP_DEREF;
2885 break;
2886 case LOCAL:
2887 if (c->u->u_ste->ste_type == FunctionBlock)
2888 optype = OP_FAST;
2889 break;
2890 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002891 if (c->u->u_ste->ste_type == FunctionBlock &&
2892 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 optype = OP_GLOBAL;
2894 break;
2895 case GLOBAL_EXPLICIT:
2896 optype = OP_GLOBAL;
2897 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002898 default:
2899 /* scope can be 0 */
2900 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 }
2902
2903 /* XXX Leave assert here, but handle __doc__ and the like better */
2904 assert(scope || PyString_AS_STRING(name)[0] == '_');
2905
2906 switch (optype) {
2907 case OP_DEREF:
2908 switch (ctx) {
2909 case Load: op = LOAD_DEREF; break;
2910 case Store: op = STORE_DEREF; break;
2911 case AugLoad:
2912 case AugStore:
2913 break;
2914 case Del:
2915 PyErr_Format(PyExc_SyntaxError,
2916 "can not delete variable '%s' referenced "
2917 "in nested scope",
2918 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002919 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002922 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002923 PyErr_SetString(PyExc_SystemError,
2924 "param invalid for deref variable");
2925 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926 }
2927 break;
2928 case OP_FAST:
2929 switch (ctx) {
2930 case Load: op = LOAD_FAST; break;
2931 case Store: op = STORE_FAST; break;
2932 case Del: op = DELETE_FAST; break;
2933 case AugLoad:
2934 case AugStore:
2935 break;
2936 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002937 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002938 PyErr_SetString(PyExc_SystemError,
2939 "param invalid for local variable");
2940 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002942 ADDOP_O(c, op, mangled, varnames);
2943 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 return 1;
2945 case OP_GLOBAL:
2946 switch (ctx) {
2947 case Load: op = LOAD_GLOBAL; break;
2948 case Store: op = STORE_GLOBAL; break;
2949 case Del: op = DELETE_GLOBAL; break;
2950 case AugLoad:
2951 case AugStore:
2952 break;
2953 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002954 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002955 PyErr_SetString(PyExc_SystemError,
2956 "param invalid for global variable");
2957 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 }
2959 break;
2960 case OP_NAME:
2961 switch (ctx) {
2962 case Load: op = LOAD_NAME; break;
2963 case Store: op = STORE_NAME; break;
2964 case Del: op = DELETE_NAME; break;
2965 case AugLoad:
2966 case AugStore:
2967 break;
2968 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002969 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002970 PyErr_SetString(PyExc_SystemError,
2971 "param invalid for name variable");
2972 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973 }
2974 break;
2975 }
2976
2977 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002978 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002979 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002980 if (arg < 0)
2981 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002982 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983}
2984
2985static int
2986compiler_boolop(struct compiler *c, expr_ty e)
2987{
2988 basicblock *end;
2989 int jumpi, i, n;
2990 asdl_seq *s;
2991
2992 assert(e->kind == BoolOp_kind);
2993 if (e->v.BoolOp.op == And)
2994 jumpi = JUMP_IF_FALSE;
2995 else
2996 jumpi = JUMP_IF_TRUE;
2997 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002998 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 return 0;
3000 s = e->v.BoolOp.values;
3001 n = asdl_seq_LEN(s) - 1;
3002 for (i = 0; i < n; ++i) {
3003 VISIT(c, expr, asdl_seq_GET(s, i));
3004 ADDOP_JREL(c, jumpi, end);
3005 ADDOP(c, POP_TOP)
3006 }
3007 VISIT(c, expr, asdl_seq_GET(s, n));
3008 compiler_use_next_block(c, end);
3009 return 1;
3010}
3011
3012static int
3013compiler_list(struct compiler *c, expr_ty e)
3014{
3015 int n = asdl_seq_LEN(e->v.List.elts);
3016 if (e->v.List.ctx == Store) {
3017 ADDOP_I(c, UNPACK_SEQUENCE, n);
3018 }
3019 VISIT_SEQ(c, expr, e->v.List.elts);
3020 if (e->v.List.ctx == Load) {
3021 ADDOP_I(c, BUILD_LIST, n);
3022 }
3023 return 1;
3024}
3025
3026static int
3027compiler_tuple(struct compiler *c, expr_ty e)
3028{
3029 int n = asdl_seq_LEN(e->v.Tuple.elts);
3030 if (e->v.Tuple.ctx == Store) {
3031 ADDOP_I(c, UNPACK_SEQUENCE, n);
3032 }
3033 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3034 if (e->v.Tuple.ctx == Load) {
3035 ADDOP_I(c, BUILD_TUPLE, n);
3036 }
3037 return 1;
3038}
3039
3040static int
3041compiler_compare(struct compiler *c, expr_ty e)
3042{
3043 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003044 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045
3046 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3047 VISIT(c, expr, e->v.Compare.left);
3048 n = asdl_seq_LEN(e->v.Compare.ops);
3049 assert(n > 0);
3050 if (n > 1) {
3051 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003052 if (cleanup == NULL)
3053 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3055 }
3056 for (i = 1; i < n; i++) {
3057 ADDOP(c, DUP_TOP);
3058 ADDOP(c, ROT_THREE);
3059 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3060 ADDOP_I(c, COMPARE_OP,
3061 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3062 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3063 NEXT_BLOCK(c);
3064 ADDOP(c, POP_TOP);
3065 if (i < (n - 1))
3066 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3067 }
3068 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3069 ADDOP_I(c, COMPARE_OP,
3070 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3071 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3072 if (n > 1) {
3073 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 if (end == NULL)
3075 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 ADDOP_JREL(c, JUMP_FORWARD, end);
3077 compiler_use_next_block(c, cleanup);
3078 ADDOP(c, ROT_TWO);
3079 ADDOP(c, POP_TOP);
3080 compiler_use_next_block(c, end);
3081 }
3082 return 1;
3083}
3084
3085static int
3086compiler_call(struct compiler *c, expr_ty e)
3087{
3088 int n, code = 0;
3089
3090 VISIT(c, expr, e->v.Call.func);
3091 n = asdl_seq_LEN(e->v.Call.args);
3092 VISIT_SEQ(c, expr, e->v.Call.args);
3093 if (e->v.Call.keywords) {
3094 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3095 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3096 }
3097 if (e->v.Call.starargs) {
3098 VISIT(c, expr, e->v.Call.starargs);
3099 code |= 1;
3100 }
3101 if (e->v.Call.kwargs) {
3102 VISIT(c, expr, e->v.Call.kwargs);
3103 code |= 2;
3104 }
3105 switch (code) {
3106 case 0:
3107 ADDOP_I(c, CALL_FUNCTION, n);
3108 break;
3109 case 1:
3110 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3111 break;
3112 case 2:
3113 ADDOP_I(c, CALL_FUNCTION_KW, n);
3114 break;
3115 case 3:
3116 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3117 break;
3118 }
3119 return 1;
3120}
3121
3122static int
3123compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003124 asdl_seq *generators, int gen_index,
3125 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126{
3127 /* generate code for the iterator, then each of the ifs,
3128 and then write to the element */
3129
3130 comprehension_ty l;
3131 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003132 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133
3134 start = compiler_new_block(c);
3135 skip = compiler_new_block(c);
3136 if_cleanup = compiler_new_block(c);
3137 anchor = compiler_new_block(c);
3138
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3140 anchor == NULL)
3141 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142
3143 l = asdl_seq_GET(generators, gen_index);
3144 VISIT(c, expr, l->iter);
3145 ADDOP(c, GET_ITER);
3146 compiler_use_next_block(c, start);
3147 ADDOP_JREL(c, FOR_ITER, anchor);
3148 NEXT_BLOCK(c);
3149 VISIT(c, expr, l->target);
3150
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003151 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003152 n = asdl_seq_LEN(l->ifs);
3153 for (i = 0; i < n; i++) {
3154 expr_ty e = asdl_seq_GET(l->ifs, i);
3155 VISIT(c, expr, e);
3156 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3157 NEXT_BLOCK(c);
3158 ADDOP(c, POP_TOP);
3159 }
3160
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 if (++gen_index < asdl_seq_LEN(generators))
3162 if (!compiler_listcomp_generator(c, tmpname,
3163 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003166 /* only append after the last for generator */
3167 if (gen_index >= asdl_seq_LEN(generators)) {
3168 if (!compiler_nameop(c, tmpname, Load))
3169 return 0;
3170 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003171 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003172
3173 compiler_use_next_block(c, skip);
3174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175 for (i = 0; i < n; i++) {
3176 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 if (i == 0)
3178 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 ADDOP(c, POP_TOP);
3180 }
3181 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3182 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 return 0;
3187
3188 return 1;
3189}
3190
3191static int
3192compiler_listcomp(struct compiler *c, expr_ty e)
3193{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 static identifier append;
3197 asdl_seq *generators = e->v.ListComp.generators;
3198
3199 assert(e->kind == ListComp_kind);
3200 if (!append) {
3201 append = PyString_InternFromString("append");
3202 if (!append)
3203 return 0;
3204 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003205 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 if (!tmp)
3207 return 0;
3208 ADDOP_I(c, BUILD_LIST, 0);
3209 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3212 e->v.ListComp.elt);
3213 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214 return rc;
3215}
3216
3217static int
3218compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 asdl_seq *generators, int gen_index,
3220 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221{
3222 /* generate code for the iterator, then each of the ifs,
3223 and then write to the element */
3224
3225 comprehension_ty ge;
3226 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228
3229 start = compiler_new_block(c);
3230 skip = compiler_new_block(c);
3231 if_cleanup = compiler_new_block(c);
3232 anchor = compiler_new_block(c);
3233 end = compiler_new_block(c);
3234
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236 anchor == NULL || end == NULL)
3237 return 0;
3238
3239 ge = asdl_seq_GET(generators, gen_index);
3240 ADDOP_JREL(c, SETUP_LOOP, end);
3241 if (!compiler_push_fblock(c, LOOP, start))
3242 return 0;
3243
3244 if (gen_index == 0) {
3245 /* Receive outermost iter as an implicit argument */
3246 c->u->u_argcount = 1;
3247 ADDOP_I(c, LOAD_FAST, 0);
3248 }
3249 else {
3250 /* Sub-iter - calculate on the fly */
3251 VISIT(c, expr, ge->iter);
3252 ADDOP(c, GET_ITER);
3253 }
3254 compiler_use_next_block(c, start);
3255 ADDOP_JREL(c, FOR_ITER, anchor);
3256 NEXT_BLOCK(c);
3257 VISIT(c, expr, ge->target);
3258
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 n = asdl_seq_LEN(ge->ifs);
3261 for (i = 0; i < n; i++) {
3262 expr_ty e = asdl_seq_GET(ge->ifs, i);
3263 VISIT(c, expr, e);
3264 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3265 NEXT_BLOCK(c);
3266 ADDOP(c, POP_TOP);
3267 }
3268
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3271 return 0;
3272
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003273 /* only append after the last 'for' generator */
3274 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 VISIT(c, expr, elt);
3276 ADDOP(c, YIELD_VALUE);
3277 ADDOP(c, POP_TOP);
3278
3279 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003280 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 for (i = 0; i < n; i++) {
3282 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 compiler_use_next_block(c, if_cleanup);
3285
3286 ADDOP(c, POP_TOP);
3287 }
3288 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3289 compiler_use_next_block(c, anchor);
3290 ADDOP(c, POP_BLOCK);
3291 compiler_pop_fblock(c, LOOP, start);
3292 compiler_use_next_block(c, end);
3293
3294 return 1;
3295}
3296
3297static int
3298compiler_genexp(struct compiler *c, expr_ty e)
3299{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003300 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 PyCodeObject *co;
3302 expr_ty outermost_iter = ((comprehension_ty)
3303 (asdl_seq_GET(e->v.GeneratorExp.generators,
3304 0)))->iter;
3305
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003306 if (!name) {
3307 name = PyString_FromString("<genexpr>");
3308 if (!name)
3309 return 0;
3310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311
3312 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3313 return 0;
3314 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3315 e->v.GeneratorExp.elt);
3316 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003317 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318 if (co == NULL)
3319 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003320
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003321 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003322 Py_DECREF(co);
3323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 VISIT(c, expr, outermost_iter);
3325 ADDOP(c, GET_ITER);
3326 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327
3328 return 1;
3329}
3330
3331static int
3332compiler_visit_keyword(struct compiler *c, keyword_ty k)
3333{
3334 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3335 VISIT(c, expr, k->value);
3336 return 1;
3337}
3338
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003339/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 whether they are true or false.
3341
3342 Return values: 1 for true, 0 for false, -1 for non-constant.
3343 */
3344
3345static int
3346expr_constant(expr_ty e)
3347{
3348 switch (e->kind) {
3349 case Num_kind:
3350 return PyObject_IsTrue(e->v.Num.n);
3351 case Str_kind:
3352 return PyObject_IsTrue(e->v.Str.s);
3353 default:
3354 return -1;
3355 }
3356}
3357
Guido van Rossumc2e20742006-02-27 22:32:47 +00003358/*
3359 Implements the with statement from PEP 343.
3360
3361 The semantics outlined in that PEP are as follows:
3362
3363 with EXPR as VAR:
3364 BLOCK
3365
3366 It is implemented roughly as:
3367
3368 context = (EXPR).__context__()
3369 exit = context.__exit__ # not calling it
3370 value = context.__enter__()
3371 try:
3372 VAR = value # if VAR present in the syntax
3373 BLOCK
3374 finally:
3375 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003376 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003377 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003378 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003379 exit(*exc)
3380 */
3381static int
3382compiler_with(struct compiler *c, stmt_ty s)
3383{
3384 static identifier context_attr, enter_attr, exit_attr;
3385 basicblock *block, *finally;
3386 identifier tmpexit, tmpvalue = NULL;
3387
3388 assert(s->kind == With_kind);
3389
3390 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003391 context_attr = PyString_InternFromString("__context__");
3392 if (!context_attr)
3393 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003394 }
3395 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003396 enter_attr = PyString_InternFromString("__enter__");
3397 if (!enter_attr)
3398 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003399 }
3400 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003401 exit_attr = PyString_InternFromString("__exit__");
3402 if (!exit_attr)
3403 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003404 }
3405
3406 block = compiler_new_block(c);
3407 finally = compiler_new_block(c);
3408 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003409 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003410
3411 /* Create a temporary variable to hold context.__exit__ */
3412 tmpexit = compiler_new_tmpname(c);
3413 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003414 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003415 PyArena_AddPyObject(c->c_arena, tmpexit);
3416
3417 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003418 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003419 We need to do this rather than preserving it on the stack
3420 because SETUP_FINALLY remembers the stack level.
3421 We need to do the assignment *inside* the try/finally
3422 so that context.__exit__() is called when the assignment
3423 fails. But we need to call context.__enter__() *before*
3424 the try/finally so that if it fails we won't call
3425 context.__exit__().
3426 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003427 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003428 if (tmpvalue == NULL)
3429 return 0;
3430 PyArena_AddPyObject(c->c_arena, tmpvalue);
3431 }
3432
3433 /* Evaluate (EXPR).__context__() */
3434 VISIT(c, expr, s->v.With.context_expr);
3435 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3436 ADDOP_I(c, CALL_FUNCTION, 0);
3437
3438 /* Squirrel away context.__exit__ */
3439 ADDOP(c, DUP_TOP);
3440 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3441 if (!compiler_nameop(c, tmpexit, Store))
3442 return 0;
3443
3444 /* Call context.__enter__() */
3445 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3446 ADDOP_I(c, CALL_FUNCTION, 0);
3447
3448 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003449 /* Store it in tmpvalue */
3450 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003451 return 0;
3452 }
3453 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003454 /* Discard result from context.__enter__() */
3455 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003456 }
3457
3458 /* Start the try block */
3459 ADDOP_JREL(c, SETUP_FINALLY, finally);
3460
3461 compiler_use_next_block(c, block);
3462 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003464 }
3465
3466 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003467 /* Bind saved result of context.__enter__() to VAR */
3468 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003469 !compiler_nameop(c, tmpvalue, Del))
3470 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003472 }
3473
3474 /* BLOCK code */
3475 VISIT_SEQ(c, stmt, s->v.With.body);
3476
3477 /* End of try block; start the finally block */
3478 ADDOP(c, POP_BLOCK);
3479 compiler_pop_fblock(c, FINALLY_TRY, block);
3480
3481 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3482 compiler_use_next_block(c, finally);
3483 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003484 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003485
3486 /* Finally block starts; push tmpexit and issue our magic opcode. */
3487 if (!compiler_nameop(c, tmpexit, Load) ||
3488 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003489 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003490 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003491
3492 /* Finally block ends. */
3493 ADDOP(c, END_FINALLY);
3494 compiler_pop_fblock(c, FINALLY_END, finally);
3495 return 1;
3496}
3497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498static int
3499compiler_visit_expr(struct compiler *c, expr_ty e)
3500{
3501 int i, n;
3502
Jeremy Hylton12603c42006-04-01 16:18:02 +00003503 /* If expr e has a different line number than the last expr/stmt,
3504 set a new line number for the next instruction.
3505 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 if (e->lineno > c->u->u_lineno) {
3507 c->u->u_lineno = e->lineno;
3508 c->u->u_lineno_set = false;
3509 }
3510 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003513 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514 VISIT(c, expr, e->v.BinOp.left);
3515 VISIT(c, expr, e->v.BinOp.right);
3516 ADDOP(c, binop(c, e->v.BinOp.op));
3517 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003518 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519 VISIT(c, expr, e->v.UnaryOp.operand);
3520 ADDOP(c, unaryop(e->v.UnaryOp.op));
3521 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003522 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003524 case IfExp_kind:
3525 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 /* XXX get rid of arg? */
3528 ADDOP_I(c, BUILD_MAP, 0);
3529 n = asdl_seq_LEN(e->v.Dict.values);
3530 /* We must arrange things just right for STORE_SUBSCR.
3531 It wants the stack to look like (value) (dict) (key) */
3532 for (i = 0; i < n; i++) {
3533 ADDOP(c, DUP_TOP);
3534 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3535 ADDOP(c, ROT_TWO);
3536 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3537 ADDOP(c, STORE_SUBSCR);
3538 }
3539 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003540 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003542 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 return compiler_genexp(c, e);
3544 case Yield_kind:
3545 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003546 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 /*
3548 for (i = 0; i < c->u->u_nfblocks; i++) {
3549 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3550 return compiler_error(
3551 c, "'yield' not allowed in a 'try' "
3552 "block with a 'finally' clause");
3553 }
3554 */
3555 if (e->v.Yield.value) {
3556 VISIT(c, expr, e->v.Yield.value);
3557 }
3558 else {
3559 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3560 }
3561 ADDOP(c, YIELD_VALUE);
3562 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003565 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003567 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568 VISIT(c, expr, e->v.Repr.value);
3569 ADDOP(c, UNARY_CONVERT);
3570 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003571 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3573 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003574 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003575 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3576 break;
3577 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003578 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579 if (e->v.Attribute.ctx != AugStore)
3580 VISIT(c, expr, e->v.Attribute.value);
3581 switch (e->v.Attribute.ctx) {
3582 case AugLoad:
3583 ADDOP(c, DUP_TOP);
3584 /* Fall through to load */
3585 case Load:
3586 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3587 break;
3588 case AugStore:
3589 ADDOP(c, ROT_TWO);
3590 /* Fall through to save */
3591 case Store:
3592 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3593 break;
3594 case Del:
3595 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3596 break;
3597 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003598 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003599 PyErr_SetString(PyExc_SystemError,
3600 "param invalid in attribute expression");
3601 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602 }
3603 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003604 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 switch (e->v.Subscript.ctx) {
3606 case AugLoad:
3607 VISIT(c, expr, e->v.Subscript.value);
3608 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3609 break;
3610 case Load:
3611 VISIT(c, expr, e->v.Subscript.value);
3612 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3613 break;
3614 case AugStore:
3615 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3616 break;
3617 case Store:
3618 VISIT(c, expr, e->v.Subscript.value);
3619 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3620 break;
3621 case Del:
3622 VISIT(c, expr, e->v.Subscript.value);
3623 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3624 break;
3625 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003626 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003627 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003628 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003629 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 }
3631 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003632 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3634 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003635 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003637 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 return compiler_tuple(c, e);
3639 }
3640 return 1;
3641}
3642
3643static int
3644compiler_augassign(struct compiler *c, stmt_ty s)
3645{
3646 expr_ty e = s->v.AugAssign.target;
3647 expr_ty auge;
3648
3649 assert(s->kind == AugAssign_kind);
3650
3651 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003652 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003654 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 if (auge == NULL)
3656 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 VISIT(c, expr, auge);
3658 VISIT(c, expr, s->v.AugAssign.value);
3659 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3660 auge->v.Attribute.ctx = AugStore;
3661 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662 break;
3663 case Subscript_kind:
3664 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003665 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003666 if (auge == NULL)
3667 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 VISIT(c, expr, auge);
3669 VISIT(c, expr, s->v.AugAssign.value);
3670 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003671 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003673 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 case Name_kind:
3675 VISIT(c, expr, s->v.AugAssign.target);
3676 VISIT(c, expr, s->v.AugAssign.value);
3677 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3678 return compiler_nameop(c, e->v.Name.id, Store);
3679 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003680 PyErr_Format(PyExc_SystemError,
3681 "invalid node type (%d) for augmented assignment",
3682 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003683 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684 }
3685 return 1;
3686}
3687
3688static int
3689compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3690{
3691 struct fblockinfo *f;
3692 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3693 return 0;
3694 f = &c->u->u_fblock[c->u->u_nfblocks++];
3695 f->fb_type = t;
3696 f->fb_block = b;
3697 return 1;
3698}
3699
3700static void
3701compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3702{
3703 struct compiler_unit *u = c->u;
3704 assert(u->u_nfblocks > 0);
3705 u->u_nfblocks--;
3706 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3707 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3708}
3709
3710/* Raises a SyntaxError and returns 0.
3711 If something goes wrong, a different exception may be raised.
3712*/
3713
3714static int
3715compiler_error(struct compiler *c, const char *errstr)
3716{
3717 PyObject *loc;
3718 PyObject *u = NULL, *v = NULL;
3719
3720 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3721 if (!loc) {
3722 Py_INCREF(Py_None);
3723 loc = Py_None;
3724 }
3725 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3726 Py_None, loc);
3727 if (!u)
3728 goto exit;
3729 v = Py_BuildValue("(zO)", errstr, u);
3730 if (!v)
3731 goto exit;
3732 PyErr_SetObject(PyExc_SyntaxError, v);
3733 exit:
3734 Py_DECREF(loc);
3735 Py_XDECREF(u);
3736 Py_XDECREF(v);
3737 return 0;
3738}
3739
3740static int
3741compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003744 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 /* XXX this code is duplicated */
3747 switch (ctx) {
3748 case AugLoad: /* fall through to Load */
3749 case Load: op = BINARY_SUBSCR; break;
3750 case AugStore:/* fall through to Store */
3751 case Store: op = STORE_SUBSCR; break;
3752 case Del: op = DELETE_SUBSCR; break;
3753 case Param:
3754 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003755 "invalid %s kind %d in subscript\n",
3756 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003757 return 0;
3758 }
3759 if (ctx == AugLoad) {
3760 ADDOP_I(c, DUP_TOPX, 2);
3761 }
3762 else if (ctx == AugStore) {
3763 ADDOP(c, ROT_THREE);
3764 }
3765 ADDOP(c, op);
3766 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767}
3768
3769static int
3770compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3771{
3772 int n = 2;
3773 assert(s->kind == Slice_kind);
3774
3775 /* only handles the cases where BUILD_SLICE is emitted */
3776 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003777 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778 }
3779 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003780 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003782
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003784 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785 }
3786 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003787 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788 }
3789
3790 if (s->v.Slice.step) {
3791 n++;
3792 VISIT(c, expr, s->v.Slice.step);
3793 }
3794 ADDOP_I(c, BUILD_SLICE, n);
3795 return 1;
3796}
3797
3798static int
3799compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3800{
3801 int op = 0, slice_offset = 0, stack_count = 0;
3802
3803 assert(s->v.Slice.step == NULL);
3804 if (s->v.Slice.lower) {
3805 slice_offset++;
3806 stack_count++;
3807 if (ctx != AugStore)
3808 VISIT(c, expr, s->v.Slice.lower);
3809 }
3810 if (s->v.Slice.upper) {
3811 slice_offset += 2;
3812 stack_count++;
3813 if (ctx != AugStore)
3814 VISIT(c, expr, s->v.Slice.upper);
3815 }
3816
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003817 if (ctx == AugLoad) {
3818 switch (stack_count) {
3819 case 0: ADDOP(c, DUP_TOP); break;
3820 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3821 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3822 }
3823 }
3824 else if (ctx == AugStore) {
3825 switch (stack_count) {
3826 case 0: ADDOP(c, ROT_TWO); break;
3827 case 1: ADDOP(c, ROT_THREE); break;
3828 case 2: ADDOP(c, ROT_FOUR); break;
3829 }
3830 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003831
3832 switch (ctx) {
3833 case AugLoad: /* fall through to Load */
3834 case Load: op = SLICE; break;
3835 case AugStore:/* fall through to Store */
3836 case Store: op = STORE_SLICE; break;
3837 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003838 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003839 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003840 PyErr_SetString(PyExc_SystemError,
3841 "param invalid in simple slice");
3842 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 }
3844
3845 ADDOP(c, op + slice_offset);
3846 return 1;
3847}
3848
3849static int
3850compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3851 expr_context_ty ctx)
3852{
3853 switch (s->kind) {
3854 case Ellipsis_kind:
3855 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3856 break;
3857 case Slice_kind:
3858 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 case Index_kind:
3860 VISIT(c, expr, s->v.Index.value);
3861 break;
3862 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003863 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003864 PyErr_SetString(PyExc_SystemError,
3865 "extended slice invalid in nested slice");
3866 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867 }
3868 return 1;
3869}
3870
3871
3872static int
3873compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3874{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003875 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003877 case Index_kind:
3878 kindname = "index";
3879 if (ctx != AugStore) {
3880 VISIT(c, expr, s->v.Index.value);
3881 }
3882 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003884 kindname = "ellipsis";
3885 if (ctx != AugStore) {
3886 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3887 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 break;
3889 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003890 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 if (!s->v.Slice.step)
3892 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003893 if (ctx != AugStore) {
3894 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 return 0;
3896 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003897 break;
3898 case ExtSlice_kind:
3899 kindname = "extended slice";
3900 if (ctx != AugStore) {
3901 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3902 for (i = 0; i < n; i++) {
3903 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3904 if (!compiler_visit_nested_slice(c, sub, ctx))
3905 return 0;
3906 }
3907 ADDOP_I(c, BUILD_TUPLE, n);
3908 }
3909 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003910 default:
3911 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003912 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003913 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003915 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916}
3917
3918/* do depth-first search of basic block graph, starting with block.
3919 post records the block indices in post-order.
3920
3921 XXX must handle implicit jumps from one block to next
3922*/
3923
3924static void
3925dfs(struct compiler *c, basicblock *b, struct assembler *a)
3926{
3927 int i;
3928 struct instr *instr = NULL;
3929
3930 if (b->b_seen)
3931 return;
3932 b->b_seen = 1;
3933 if (b->b_next != NULL)
3934 dfs(c, b->b_next, a);
3935 for (i = 0; i < b->b_iused; i++) {
3936 instr = &b->b_instr[i];
3937 if (instr->i_jrel || instr->i_jabs)
3938 dfs(c, instr->i_target, a);
3939 }
3940 a->a_postorder[a->a_nblocks++] = b;
3941}
3942
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003943static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3945{
3946 int i;
3947 struct instr *instr;
3948 if (b->b_seen || b->b_startdepth >= depth)
3949 return maxdepth;
3950 b->b_seen = 1;
3951 b->b_startdepth = depth;
3952 for (i = 0; i < b->b_iused; i++) {
3953 instr = &b->b_instr[i];
3954 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3955 if (depth > maxdepth)
3956 maxdepth = depth;
3957 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3958 if (instr->i_jrel || instr->i_jabs) {
3959 maxdepth = stackdepth_walk(c, instr->i_target,
3960 depth, maxdepth);
3961 if (instr->i_opcode == JUMP_ABSOLUTE ||
3962 instr->i_opcode == JUMP_FORWARD) {
3963 goto out; /* remaining code is dead */
3964 }
3965 }
3966 }
3967 if (b->b_next)
3968 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3969out:
3970 b->b_seen = 0;
3971 return maxdepth;
3972}
3973
3974/* Find the flow path that needs the largest stack. We assume that
3975 * cycles in the flow graph have no net effect on the stack depth.
3976 */
3977static int
3978stackdepth(struct compiler *c)
3979{
3980 basicblock *b, *entryblock;
3981 entryblock = NULL;
3982 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3983 b->b_seen = 0;
3984 b->b_startdepth = INT_MIN;
3985 entryblock = b;
3986 }
3987 return stackdepth_walk(c, entryblock, 0, 0);
3988}
3989
3990static int
3991assemble_init(struct assembler *a, int nblocks, int firstlineno)
3992{
3993 memset(a, 0, sizeof(struct assembler));
3994 a->a_lineno = firstlineno;
3995 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3996 if (!a->a_bytecode)
3997 return 0;
3998 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3999 if (!a->a_lnotab)
4000 return 0;
4001 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004002 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004003 if (!a->a_postorder) {
4004 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004006 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004007 return 1;
4008}
4009
4010static void
4011assemble_free(struct assembler *a)
4012{
4013 Py_XDECREF(a->a_bytecode);
4014 Py_XDECREF(a->a_lnotab);
4015 if (a->a_postorder)
4016 PyObject_Free(a->a_postorder);
4017}
4018
4019/* Return the size of a basic block in bytes. */
4020
4021static int
4022instrsize(struct instr *instr)
4023{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004024 if (!instr->i_hasarg)
4025 return 1;
4026 if (instr->i_oparg > 0xffff)
4027 return 6;
4028 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004029}
4030
4031static int
4032blocksize(basicblock *b)
4033{
4034 int i;
4035 int size = 0;
4036
4037 for (i = 0; i < b->b_iused; i++)
4038 size += instrsize(&b->b_instr[i]);
4039 return size;
4040}
4041
4042/* All about a_lnotab.
4043
4044c_lnotab is an array of unsigned bytes disguised as a Python string.
4045It is used to map bytecode offsets to source code line #s (when needed
4046for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004047
Tim Peters2a7f3842001-06-09 09:26:21 +00004048The array is conceptually a list of
4049 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004050pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004051
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004052 byte code offset source code line number
4053 0 1
4054 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004055 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004056 350 307
4057 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004058
4059The first trick is that these numbers aren't stored, only the increments
4060from one row to the next (this doesn't really work, but it's a start):
4061
4062 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4063
4064The second trick is that an unsigned byte can't hold negative values, or
4065values larger than 255, so (a) there's a deep assumption that byte code
4066offsets and their corresponding line #s both increase monotonically, and (b)
4067if at least one column jumps by more than 255 from one row to the next, more
4068than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004069from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004070part. A user of c_lnotab desiring to find the source line number
4071corresponding to a bytecode address A should do something like this
4072
4073 lineno = addr = 0
4074 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004075 addr += addr_incr
4076 if addr > A:
4077 return lineno
4078 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004079
4080In order for this to work, when the addr field increments by more than 255,
4081the line # increment in each pair generated must be 0 until the remaining addr
4082increment is < 256. So, in the example above, com_set_lineno should not (as
4083was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004084255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004085*/
4086
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004087static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004089{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 int d_bytecode, d_lineno;
4091 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004092 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093
4094 d_bytecode = a->a_offset - a->a_lineno_off;
4095 d_lineno = i->i_lineno - a->a_lineno;
4096
4097 assert(d_bytecode >= 0);
4098 assert(d_lineno >= 0);
4099
4100 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004101 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004102
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004104 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 nbytes = a->a_lnotab_off + 2 * ncodes;
4106 len = PyString_GET_SIZE(a->a_lnotab);
4107 if (nbytes >= len) {
4108 if (len * 2 < nbytes)
4109 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004110 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 len *= 2;
4112 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4113 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004114 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004115 lnotab = (unsigned char *)
4116 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004117 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004118 *lnotab++ = 255;
4119 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004120 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121 d_bytecode -= ncodes * 255;
4122 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004123 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 assert(d_bytecode <= 255);
4125 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004126 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127 nbytes = a->a_lnotab_off + 2 * ncodes;
4128 len = PyString_GET_SIZE(a->a_lnotab);
4129 if (nbytes >= len) {
4130 if (len * 2 < nbytes)
4131 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004132 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133 len *= 2;
4134 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4135 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004136 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004137 lnotab = (unsigned char *)
4138 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139 *lnotab++ = 255;
4140 *lnotab++ = d_bytecode;
4141 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004142 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143 *lnotab++ = 255;
4144 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004145 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146 d_lineno -= ncodes * 255;
4147 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004148 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150 len = PyString_GET_SIZE(a->a_lnotab);
4151 if (a->a_lnotab_off + 2 >= len) {
4152 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004153 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004154 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004155 lnotab = (unsigned char *)
4156 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158 a->a_lnotab_off += 2;
4159 if (d_bytecode) {
4160 *lnotab++ = d_bytecode;
4161 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004162 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004163 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164 *lnotab++ = 0;
4165 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 a->a_lineno = i->i_lineno;
4168 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004169 return 1;
4170}
4171
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172/* assemble_emit()
4173 Extend the bytecode with a new instruction.
4174 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004175*/
4176
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004177static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004179{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004180 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 int len = PyString_GET_SIZE(a->a_bytecode);
4182 char *code;
4183
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004184 size = instrsize(i);
4185 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004187 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004188 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004189 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004190 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191 if (a->a_offset + size >= len) {
4192 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004193 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004194 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4196 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004197 if (size == 6) {
4198 assert(i->i_hasarg);
4199 *code++ = (char)EXTENDED_ARG;
4200 *code++ = ext & 0xff;
4201 *code++ = ext >> 8;
4202 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004203 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004205 if (i->i_hasarg) {
4206 assert(size == 3 || size == 6);
4207 *code++ = arg & 0xff;
4208 *code++ = arg >> 8;
4209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004210 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004211}
4212
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004213static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004214assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004215{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004216 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004217 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004218 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004219
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220 /* Compute the size of each block and fixup jump args.
4221 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004222start:
4223 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004225 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226 bsize = blocksize(b);
4227 b->b_offset = totsize;
4228 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004229 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004230 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004231 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4232 bsize = b->b_offset;
4233 for (i = 0; i < b->b_iused; i++) {
4234 struct instr *instr = &b->b_instr[i];
4235 /* Relative jumps are computed relative to
4236 the instruction pointer after fetching
4237 the jump instruction.
4238 */
4239 bsize += instrsize(instr);
4240 if (instr->i_jabs)
4241 instr->i_oparg = instr->i_target->b_offset;
4242 else if (instr->i_jrel) {
4243 int delta = instr->i_target->b_offset - bsize;
4244 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004245 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004246 else
4247 continue;
4248 if (instr->i_oparg > 0xffff)
4249 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004250 }
4251 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004252
4253 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004254 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004255 with a better solution.
4256
4257 In the meantime, should the goto be dropped in favor
4258 of a loop?
4259
4260 The issue is that in the first loop blocksize() is called
4261 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004262 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004263 i_oparg is calculated in the second loop above.
4264
4265 So we loop until we stop seeing new EXTENDED_ARGs.
4266 The only EXTENDED_ARGs that could be popping up are
4267 ones in jump instructions. So this should converge
4268 fairly quickly.
4269 */
4270 if (last_extended_arg_count != extended_arg_count) {
4271 last_extended_arg_count = extended_arg_count;
4272 goto start;
4273 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004274}
4275
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004276static PyObject *
4277dict_keys_inorder(PyObject *dict, int offset)
4278{
4279 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004280 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004281
4282 tuple = PyTuple_New(size);
4283 if (tuple == NULL)
4284 return NULL;
4285 while (PyDict_Next(dict, &pos, &k, &v)) {
4286 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004287 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004288 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004289 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004290 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004291 PyTuple_SET_ITEM(tuple, i - offset, k);
4292 }
4293 return tuple;
4294}
4295
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004296static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004298{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004299 PySTEntryObject *ste = c->u->u_ste;
4300 int flags = 0, n;
4301 if (ste->ste_type != ModuleBlock)
4302 flags |= CO_NEWLOCALS;
4303 if (ste->ste_type == FunctionBlock) {
4304 if (!ste->ste_unoptimized)
4305 flags |= CO_OPTIMIZED;
4306 if (ste->ste_nested)
4307 flags |= CO_NESTED;
4308 if (ste->ste_generator)
4309 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311 if (ste->ste_varargs)
4312 flags |= CO_VARARGS;
4313 if (ste->ste_varkeywords)
4314 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004315 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004317
4318 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004319 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004320
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004321 n = PyDict_Size(c->u->u_freevars);
4322 if (n < 0)
4323 return -1;
4324 if (n == 0) {
4325 n = PyDict_Size(c->u->u_cellvars);
4326 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004327 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328 if (n == 0) {
4329 flags |= CO_NOFREE;
4330 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004331 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004332
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004333 return flags;
4334}
4335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004336static PyCodeObject *
4337makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004338{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004339 PyObject *tmp;
4340 PyCodeObject *co = NULL;
4341 PyObject *consts = NULL;
4342 PyObject *names = NULL;
4343 PyObject *varnames = NULL;
4344 PyObject *filename = NULL;
4345 PyObject *name = NULL;
4346 PyObject *freevars = NULL;
4347 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004348 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004350
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004351 tmp = dict_keys_inorder(c->u->u_consts, 0);
4352 if (!tmp)
4353 goto error;
4354 consts = PySequence_List(tmp); /* optimize_code requires a list */
4355 Py_DECREF(tmp);
4356
4357 names = dict_keys_inorder(c->u->u_names, 0);
4358 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4359 if (!consts || !names || !varnames)
4360 goto error;
4361
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004362 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4363 if (!cellvars)
4364 goto error;
4365 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4366 if (!freevars)
4367 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368 filename = PyString_FromString(c->c_filename);
4369 if (!filename)
4370 goto error;
4371
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004372 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373 flags = compute_code_flags(c);
4374 if (flags < 0)
4375 goto error;
4376
4377 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4378 if (!bytecode)
4379 goto error;
4380
4381 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4382 if (!tmp)
4383 goto error;
4384 Py_DECREF(consts);
4385 consts = tmp;
4386
4387 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4388 bytecode, consts, names, varnames,
4389 freevars, cellvars,
4390 filename, c->u->u_name,
4391 c->u->u_firstlineno,
4392 a->a_lnotab);
4393 error:
4394 Py_XDECREF(consts);
4395 Py_XDECREF(names);
4396 Py_XDECREF(varnames);
4397 Py_XDECREF(filename);
4398 Py_XDECREF(name);
4399 Py_XDECREF(freevars);
4400 Py_XDECREF(cellvars);
4401 Py_XDECREF(bytecode);
4402 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004403}
4404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405static PyCodeObject *
4406assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004407{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 basicblock *b, *entryblock;
4409 struct assembler a;
4410 int i, j, nblocks;
4411 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004412
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004413 /* Make sure every block that falls off the end returns None.
4414 XXX NEXT_BLOCK() isn't quite right, because if the last
4415 block ends with a jump or return b_next shouldn't set.
4416 */
4417 if (!c->u->u_curblock->b_return) {
4418 NEXT_BLOCK(c);
4419 if (addNone)
4420 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4421 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004422 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004423
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004424 nblocks = 0;
4425 entryblock = NULL;
4426 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4427 nblocks++;
4428 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004429 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004430
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4432 goto error;
4433 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004434
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004435 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004436 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004437
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438 /* Emit code in reverse postorder from dfs. */
4439 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004440 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441 for (j = 0; j < b->b_iused; j++)
4442 if (!assemble_emit(&a, &b->b_instr[j]))
4443 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004444 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004445
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4447 goto error;
4448 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4449 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004450
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004451 co = makecode(c, &a);
4452 error:
4453 assemble_free(&a);
4454 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004455}