blob: 0f7246bf52c7120633229549182c5a92de0fdc17 [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");
2401 except = compiler_new_block(c);
2402 if (except == NULL)
2403 return 0;
2404 if (handler->type) {
2405 ADDOP(c, DUP_TOP);
2406 VISIT(c, expr, handler->type);
2407 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2408 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2409 ADDOP(c, POP_TOP);
2410 }
2411 ADDOP(c, POP_TOP);
2412 if (handler->name) {
2413 VISIT(c, expr, handler->name);
2414 }
2415 else {
2416 ADDOP(c, POP_TOP);
2417 }
2418 ADDOP(c, POP_TOP);
2419 VISIT_SEQ(c, stmt, handler->body);
2420 ADDOP_JREL(c, JUMP_FORWARD, end);
2421 compiler_use_next_block(c, except);
2422 if (handler->type)
2423 ADDOP(c, POP_TOP);
2424 }
2425 ADDOP(c, END_FINALLY);
2426 compiler_use_next_block(c, orelse);
2427 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2428 compiler_use_next_block(c, end);
2429 return 1;
2430}
2431
2432static int
2433compiler_import_as(struct compiler *c, identifier name, identifier asname)
2434{
2435 /* The IMPORT_NAME opcode was already generated. This function
2436 merely needs to bind the result to a name.
2437
2438 If there is a dot in name, we need to split it and emit a
2439 LOAD_ATTR for each name.
2440 */
2441 const char *src = PyString_AS_STRING(name);
2442 const char *dot = strchr(src, '.');
2443 if (dot) {
2444 /* Consume the base module name to get the first attribute */
2445 src = dot + 1;
2446 while (dot) {
2447 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002448 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002449 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002450 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002452 if (!attr)
2453 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002454 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002455 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 src = dot + 1;
2457 }
2458 }
2459 return compiler_nameop(c, asname, Store);
2460}
2461
2462static int
2463compiler_import(struct compiler *c, stmt_ty s)
2464{
2465 /* The Import node stores a module name like a.b.c as a single
2466 string. This is convenient for all cases except
2467 import a.b.c as d
2468 where we need to parse that string to extract the individual
2469 module names.
2470 XXX Perhaps change the representation to make this case simpler?
2471 */
2472 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 for (i = 0; i < n; i++) {
2475 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2476 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002477 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478
Neal Norwitzcbce2802006-04-03 06:26:32 +00002479 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002480 level = PyInt_FromLong(0);
2481 else
2482 level = PyInt_FromLong(-1);
2483
2484 if (level == NULL)
2485 return 0;
2486
2487 ADDOP_O(c, LOAD_CONST, level, consts);
2488 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2490 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2491
2492 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002493 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002494 if (!r)
2495 return r;
2496 }
2497 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002498 identifier tmp = alias->name;
2499 const char *base = PyString_AS_STRING(alias->name);
2500 char *dot = strchr(base, '.');
2501 if (dot)
2502 tmp = PyString_FromStringAndSize(base,
2503 dot - base);
2504 r = compiler_nameop(c, tmp, Store);
2505 if (dot) {
2506 Py_DECREF(tmp);
2507 }
2508 if (!r)
2509 return r;
2510 }
2511 }
2512 return 1;
2513}
2514
2515static int
2516compiler_from_import(struct compiler *c, stmt_ty s)
2517{
2518 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519
2520 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002521 PyObject *level;
2522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523 if (!names)
2524 return 0;
2525
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002526 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002527 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002528 level = PyInt_FromLong(-1);
2529 else
2530 level = PyInt_FromLong(s->v.ImportFrom.level);
2531
2532 if (!level) {
2533 Py_DECREF(names);
2534 return 0;
2535 }
2536
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 /* build up the names */
2538 for (i = 0; i < n; i++) {
2539 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2540 Py_INCREF(alias->name);
2541 PyTuple_SET_ITEM(names, i, alias->name);
2542 }
2543
2544 if (s->lineno > c->c_future->ff_lineno) {
2545 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2546 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002547 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 Py_DECREF(names);
2549 return compiler_error(c,
2550 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002551 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002552
2553 }
2554 }
2555
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002556 ADDOP_O(c, LOAD_CONST, level, consts);
2557 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002558 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002559 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2561 for (i = 0; i < n; i++) {
2562 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2563 identifier store_name;
2564
2565 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2566 assert(n == 1);
2567 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002568 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002569 }
2570
2571 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2572 store_name = alias->name;
2573 if (alias->asname)
2574 store_name = alias->asname;
2575
2576 if (!compiler_nameop(c, store_name, Store)) {
2577 Py_DECREF(names);
2578 return 0;
2579 }
2580 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002581 /* remove imported module */
2582 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 return 1;
2584}
2585
2586static int
2587compiler_assert(struct compiler *c, stmt_ty s)
2588{
2589 static PyObject *assertion_error = NULL;
2590 basicblock *end;
2591
2592 if (Py_OptimizeFlag)
2593 return 1;
2594 if (assertion_error == NULL) {
2595 assertion_error = PyString_FromString("AssertionError");
2596 if (assertion_error == NULL)
2597 return 0;
2598 }
2599 VISIT(c, expr, s->v.Assert.test);
2600 end = compiler_new_block(c);
2601 if (end == NULL)
2602 return 0;
2603 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2604 ADDOP(c, POP_TOP);
2605 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2606 if (s->v.Assert.msg) {
2607 VISIT(c, expr, s->v.Assert.msg);
2608 ADDOP_I(c, RAISE_VARARGS, 2);
2609 }
2610 else {
2611 ADDOP_I(c, RAISE_VARARGS, 1);
2612 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002613 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 ADDOP(c, POP_TOP);
2615 return 1;
2616}
2617
2618static int
2619compiler_visit_stmt(struct compiler *c, stmt_ty s)
2620{
2621 int i, n;
2622
Jeremy Hylton12603c42006-04-01 16:18:02 +00002623 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624 c->u->u_lineno = s->lineno;
2625 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002626
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 if (c->u->u_ste->ste_type != FunctionBlock)
2634 return compiler_error(c, "'return' outside function");
2635 if (s->v.Return.value) {
2636 if (c->u->u_ste->ste_generator) {
2637 return compiler_error(c,
2638 "'return' with argument inside generator");
2639 }
2640 VISIT(c, expr, s->v.Return.value);
2641 }
2642 else
2643 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2644 ADDOP(c, RETURN_VALUE);
2645 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002646 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 VISIT_SEQ(c, expr, s->v.Delete.targets)
2648 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 n = asdl_seq_LEN(s->v.Assign.targets);
2651 VISIT(c, expr, s->v.Assign.value);
2652 for (i = 0; i < n; i++) {
2653 if (i < n - 1)
2654 ADDOP(c, DUP_TOP);
2655 VISIT(c, expr,
2656 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2657 }
2658 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 n = 0;
2671 if (s->v.Raise.type) {
2672 VISIT(c, expr, s->v.Raise.type);
2673 n++;
2674 if (s->v.Raise.inst) {
2675 VISIT(c, expr, s->v.Raise.inst);
2676 n++;
2677 if (s->v.Raise.tback) {
2678 VISIT(c, expr, s->v.Raise.tback);
2679 n++;
2680 }
2681 }
2682 }
2683 ADDOP_I(c, RAISE_VARARGS, n);
2684 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 VISIT(c, expr, s->v.Exec.body);
2697 if (s->v.Exec.globals) {
2698 VISIT(c, expr, s->v.Exec.globals);
2699 if (s->v.Exec.locals) {
2700 VISIT(c, expr, s->v.Exec.locals);
2701 } else {
2702 ADDOP(c, DUP_TOP);
2703 }
2704 } else {
2705 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2706 ADDOP(c, DUP_TOP);
2707 }
2708 ADDOP(c, EXEC_STMT);
2709 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 VISIT(c, expr, s->v.Expr.value);
2714 if (c->c_interactive && c->c_nestlevel <= 1) {
2715 ADDOP(c, PRINT_EXPR);
2716 }
2717 else {
2718 ADDOP(c, POP_TOP);
2719 }
2720 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002723 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 if (!c->u->u_nfblocks)
2725 return compiler_error(c, "'break' outside loop");
2726 ADDOP(c, BREAK_LOOP);
2727 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002728 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 case With_kind:
2731 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 }
2733 return 1;
2734}
2735
2736static int
2737unaryop(unaryop_ty op)
2738{
2739 switch (op) {
2740 case Invert:
2741 return UNARY_INVERT;
2742 case Not:
2743 return UNARY_NOT;
2744 case UAdd:
2745 return UNARY_POSITIVE;
2746 case USub:
2747 return UNARY_NEGATIVE;
2748 }
2749 return 0;
2750}
2751
2752static int
2753binop(struct compiler *c, operator_ty op)
2754{
2755 switch (op) {
2756 case Add:
2757 return BINARY_ADD;
2758 case Sub:
2759 return BINARY_SUBTRACT;
2760 case Mult:
2761 return BINARY_MULTIPLY;
2762 case Div:
2763 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2764 return BINARY_TRUE_DIVIDE;
2765 else
2766 return BINARY_DIVIDE;
2767 case Mod:
2768 return BINARY_MODULO;
2769 case Pow:
2770 return BINARY_POWER;
2771 case LShift:
2772 return BINARY_LSHIFT;
2773 case RShift:
2774 return BINARY_RSHIFT;
2775 case BitOr:
2776 return BINARY_OR;
2777 case BitXor:
2778 return BINARY_XOR;
2779 case BitAnd:
2780 return BINARY_AND;
2781 case FloorDiv:
2782 return BINARY_FLOOR_DIVIDE;
2783 }
2784 return 0;
2785}
2786
2787static int
2788cmpop(cmpop_ty op)
2789{
2790 switch (op) {
2791 case Eq:
2792 return PyCmp_EQ;
2793 case NotEq:
2794 return PyCmp_NE;
2795 case Lt:
2796 return PyCmp_LT;
2797 case LtE:
2798 return PyCmp_LE;
2799 case Gt:
2800 return PyCmp_GT;
2801 case GtE:
2802 return PyCmp_GE;
2803 case Is:
2804 return PyCmp_IS;
2805 case IsNot:
2806 return PyCmp_IS_NOT;
2807 case In:
2808 return PyCmp_IN;
2809 case NotIn:
2810 return PyCmp_NOT_IN;
2811 }
2812 return PyCmp_BAD;
2813}
2814
2815static int
2816inplace_binop(struct compiler *c, operator_ty op)
2817{
2818 switch (op) {
2819 case Add:
2820 return INPLACE_ADD;
2821 case Sub:
2822 return INPLACE_SUBTRACT;
2823 case Mult:
2824 return INPLACE_MULTIPLY;
2825 case Div:
2826 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2827 return INPLACE_TRUE_DIVIDE;
2828 else
2829 return INPLACE_DIVIDE;
2830 case Mod:
2831 return INPLACE_MODULO;
2832 case Pow:
2833 return INPLACE_POWER;
2834 case LShift:
2835 return INPLACE_LSHIFT;
2836 case RShift:
2837 return INPLACE_RSHIFT;
2838 case BitOr:
2839 return INPLACE_OR;
2840 case BitXor:
2841 return INPLACE_XOR;
2842 case BitAnd:
2843 return INPLACE_AND;
2844 case FloorDiv:
2845 return INPLACE_FLOOR_DIVIDE;
2846 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002847 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002848 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849 return 0;
2850}
2851
2852static int
2853compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2854{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002855 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2857
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002858 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002859 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860 /* XXX AugStore isn't used anywhere! */
2861
2862 /* First check for assignment to __debug__. Param? */
2863 if ((ctx == Store || ctx == AugStore || ctx == Del)
2864 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2865 return compiler_error(c, "can not assign to __debug__");
2866 }
2867
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002868 mangled = _Py_Mangle(c->u->u_private, name);
2869 if (!mangled)
2870 return 0;
2871
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872 op = 0;
2873 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002874 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875 switch (scope) {
2876 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002877 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878 optype = OP_DEREF;
2879 break;
2880 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002881 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 optype = OP_DEREF;
2883 break;
2884 case LOCAL:
2885 if (c->u->u_ste->ste_type == FunctionBlock)
2886 optype = OP_FAST;
2887 break;
2888 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002889 if (c->u->u_ste->ste_type == FunctionBlock &&
2890 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891 optype = OP_GLOBAL;
2892 break;
2893 case GLOBAL_EXPLICIT:
2894 optype = OP_GLOBAL;
2895 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002896 default:
2897 /* scope can be 0 */
2898 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899 }
2900
2901 /* XXX Leave assert here, but handle __doc__ and the like better */
2902 assert(scope || PyString_AS_STRING(name)[0] == '_');
2903
2904 switch (optype) {
2905 case OP_DEREF:
2906 switch (ctx) {
2907 case Load: op = LOAD_DEREF; break;
2908 case Store: op = STORE_DEREF; break;
2909 case AugLoad:
2910 case AugStore:
2911 break;
2912 case Del:
2913 PyErr_Format(PyExc_SyntaxError,
2914 "can not delete variable '%s' referenced "
2915 "in nested scope",
2916 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002917 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002920 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002921 PyErr_SetString(PyExc_SystemError,
2922 "param invalid for deref variable");
2923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924 }
2925 break;
2926 case OP_FAST:
2927 switch (ctx) {
2928 case Load: op = LOAD_FAST; break;
2929 case Store: op = STORE_FAST; break;
2930 case Del: op = DELETE_FAST; break;
2931 case AugLoad:
2932 case AugStore:
2933 break;
2934 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002935 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for local variable");
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002940 ADDOP_O(c, op, mangled, varnames);
2941 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 return 1;
2943 case OP_GLOBAL:
2944 switch (ctx) {
2945 case Load: op = LOAD_GLOBAL; break;
2946 case Store: op = STORE_GLOBAL; break;
2947 case Del: op = DELETE_GLOBAL; break;
2948 case AugLoad:
2949 case AugStore:
2950 break;
2951 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002952 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002953 PyErr_SetString(PyExc_SystemError,
2954 "param invalid for global variable");
2955 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 }
2957 break;
2958 case OP_NAME:
2959 switch (ctx) {
2960 case Load: op = LOAD_NAME; break;
2961 case Store: op = STORE_NAME; break;
2962 case Del: op = DELETE_NAME; break;
2963 case AugLoad:
2964 case AugStore:
2965 break;
2966 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002967 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002968 PyErr_SetString(PyExc_SystemError,
2969 "param invalid for name variable");
2970 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 }
2972 break;
2973 }
2974
2975 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002976 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002977 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002978 if (arg < 0)
2979 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002980 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981}
2982
2983static int
2984compiler_boolop(struct compiler *c, expr_ty e)
2985{
2986 basicblock *end;
2987 int jumpi, i, n;
2988 asdl_seq *s;
2989
2990 assert(e->kind == BoolOp_kind);
2991 if (e->v.BoolOp.op == And)
2992 jumpi = JUMP_IF_FALSE;
2993 else
2994 jumpi = JUMP_IF_TRUE;
2995 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002996 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 return 0;
2998 s = e->v.BoolOp.values;
2999 n = asdl_seq_LEN(s) - 1;
3000 for (i = 0; i < n; ++i) {
3001 VISIT(c, expr, asdl_seq_GET(s, i));
3002 ADDOP_JREL(c, jumpi, end);
3003 ADDOP(c, POP_TOP)
3004 }
3005 VISIT(c, expr, asdl_seq_GET(s, n));
3006 compiler_use_next_block(c, end);
3007 return 1;
3008}
3009
3010static int
3011compiler_list(struct compiler *c, expr_ty e)
3012{
3013 int n = asdl_seq_LEN(e->v.List.elts);
3014 if (e->v.List.ctx == Store) {
3015 ADDOP_I(c, UNPACK_SEQUENCE, n);
3016 }
3017 VISIT_SEQ(c, expr, e->v.List.elts);
3018 if (e->v.List.ctx == Load) {
3019 ADDOP_I(c, BUILD_LIST, n);
3020 }
3021 return 1;
3022}
3023
3024static int
3025compiler_tuple(struct compiler *c, expr_ty e)
3026{
3027 int n = asdl_seq_LEN(e->v.Tuple.elts);
3028 if (e->v.Tuple.ctx == Store) {
3029 ADDOP_I(c, UNPACK_SEQUENCE, n);
3030 }
3031 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3032 if (e->v.Tuple.ctx == Load) {
3033 ADDOP_I(c, BUILD_TUPLE, n);
3034 }
3035 return 1;
3036}
3037
3038static int
3039compiler_compare(struct compiler *c, expr_ty e)
3040{
3041 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043
3044 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3045 VISIT(c, expr, e->v.Compare.left);
3046 n = asdl_seq_LEN(e->v.Compare.ops);
3047 assert(n > 0);
3048 if (n > 1) {
3049 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003050 if (cleanup == NULL)
3051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3053 }
3054 for (i = 1; i < n; i++) {
3055 ADDOP(c, DUP_TOP);
3056 ADDOP(c, ROT_THREE);
3057 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3058 ADDOP_I(c, COMPARE_OP,
3059 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3060 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3061 NEXT_BLOCK(c);
3062 ADDOP(c, POP_TOP);
3063 if (i < (n - 1))
3064 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3065 }
3066 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3067 ADDOP_I(c, COMPARE_OP,
3068 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3069 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3070 if (n > 1) {
3071 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003072 if (end == NULL)
3073 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 ADDOP_JREL(c, JUMP_FORWARD, end);
3075 compiler_use_next_block(c, cleanup);
3076 ADDOP(c, ROT_TWO);
3077 ADDOP(c, POP_TOP);
3078 compiler_use_next_block(c, end);
3079 }
3080 return 1;
3081}
3082
3083static int
3084compiler_call(struct compiler *c, expr_ty e)
3085{
3086 int n, code = 0;
3087
3088 VISIT(c, expr, e->v.Call.func);
3089 n = asdl_seq_LEN(e->v.Call.args);
3090 VISIT_SEQ(c, expr, e->v.Call.args);
3091 if (e->v.Call.keywords) {
3092 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3093 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3094 }
3095 if (e->v.Call.starargs) {
3096 VISIT(c, expr, e->v.Call.starargs);
3097 code |= 1;
3098 }
3099 if (e->v.Call.kwargs) {
3100 VISIT(c, expr, e->v.Call.kwargs);
3101 code |= 2;
3102 }
3103 switch (code) {
3104 case 0:
3105 ADDOP_I(c, CALL_FUNCTION, n);
3106 break;
3107 case 1:
3108 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3109 break;
3110 case 2:
3111 ADDOP_I(c, CALL_FUNCTION_KW, n);
3112 break;
3113 case 3:
3114 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3115 break;
3116 }
3117 return 1;
3118}
3119
3120static int
3121compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003122 asdl_seq *generators, int gen_index,
3123 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003124{
3125 /* generate code for the iterator, then each of the ifs,
3126 and then write to the element */
3127
3128 comprehension_ty l;
3129 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003130 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003131
3132 start = compiler_new_block(c);
3133 skip = compiler_new_block(c);
3134 if_cleanup = compiler_new_block(c);
3135 anchor = compiler_new_block(c);
3136
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3138 anchor == NULL)
3139 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003140
3141 l = asdl_seq_GET(generators, gen_index);
3142 VISIT(c, expr, l->iter);
3143 ADDOP(c, GET_ITER);
3144 compiler_use_next_block(c, start);
3145 ADDOP_JREL(c, FOR_ITER, anchor);
3146 NEXT_BLOCK(c);
3147 VISIT(c, expr, l->target);
3148
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003149 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150 n = asdl_seq_LEN(l->ifs);
3151 for (i = 0; i < n; i++) {
3152 expr_ty e = asdl_seq_GET(l->ifs, i);
3153 VISIT(c, expr, e);
3154 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3155 NEXT_BLOCK(c);
3156 ADDOP(c, POP_TOP);
3157 }
3158
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 if (++gen_index < asdl_seq_LEN(generators))
3160 if (!compiler_listcomp_generator(c, tmpname,
3161 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 /* only append after the last for generator */
3165 if (gen_index >= asdl_seq_LEN(generators)) {
3166 if (!compiler_nameop(c, tmpname, Load))
3167 return 0;
3168 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003169 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003170
3171 compiler_use_next_block(c, skip);
3172 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 for (i = 0; i < n; i++) {
3174 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 if (i == 0)
3176 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 ADDOP(c, POP_TOP);
3178 }
3179 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3180 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184 return 0;
3185
3186 return 1;
3187}
3188
3189static int
3190compiler_listcomp(struct compiler *c, expr_ty e)
3191{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 static identifier append;
3195 asdl_seq *generators = e->v.ListComp.generators;
3196
3197 assert(e->kind == ListComp_kind);
3198 if (!append) {
3199 append = PyString_InternFromString("append");
3200 if (!append)
3201 return 0;
3202 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003203 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204 if (!tmp)
3205 return 0;
3206 ADDOP_I(c, BUILD_LIST, 0);
3207 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3210 e->v.ListComp.elt);
3211 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 return rc;
3213}
3214
3215static int
3216compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003217 asdl_seq *generators, int gen_index,
3218 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219{
3220 /* generate code for the iterator, then each of the ifs,
3221 and then write to the element */
3222
3223 comprehension_ty ge;
3224 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003225 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226
3227 start = compiler_new_block(c);
3228 skip = compiler_new_block(c);
3229 if_cleanup = compiler_new_block(c);
3230 anchor = compiler_new_block(c);
3231 end = compiler_new_block(c);
3232
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003233 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 anchor == NULL || end == NULL)
3235 return 0;
3236
3237 ge = asdl_seq_GET(generators, gen_index);
3238 ADDOP_JREL(c, SETUP_LOOP, end);
3239 if (!compiler_push_fblock(c, LOOP, start))
3240 return 0;
3241
3242 if (gen_index == 0) {
3243 /* Receive outermost iter as an implicit argument */
3244 c->u->u_argcount = 1;
3245 ADDOP_I(c, LOAD_FAST, 0);
3246 }
3247 else {
3248 /* Sub-iter - calculate on the fly */
3249 VISIT(c, expr, ge->iter);
3250 ADDOP(c, GET_ITER);
3251 }
3252 compiler_use_next_block(c, start);
3253 ADDOP_JREL(c, FOR_ITER, anchor);
3254 NEXT_BLOCK(c);
3255 VISIT(c, expr, ge->target);
3256
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003257 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 n = asdl_seq_LEN(ge->ifs);
3259 for (i = 0; i < n; i++) {
3260 expr_ty e = asdl_seq_GET(ge->ifs, i);
3261 VISIT(c, expr, e);
3262 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3263 NEXT_BLOCK(c);
3264 ADDOP(c, POP_TOP);
3265 }
3266
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003267 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3269 return 0;
3270
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003271 /* only append after the last 'for' generator */
3272 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273 VISIT(c, expr, elt);
3274 ADDOP(c, YIELD_VALUE);
3275 ADDOP(c, POP_TOP);
3276
3277 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003278 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 for (i = 0; i < n; i++) {
3280 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003281 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282 compiler_use_next_block(c, if_cleanup);
3283
3284 ADDOP(c, POP_TOP);
3285 }
3286 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3287 compiler_use_next_block(c, anchor);
3288 ADDOP(c, POP_BLOCK);
3289 compiler_pop_fblock(c, LOOP, start);
3290 compiler_use_next_block(c, end);
3291
3292 return 1;
3293}
3294
3295static int
3296compiler_genexp(struct compiler *c, expr_ty e)
3297{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003298 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 PyCodeObject *co;
3300 expr_ty outermost_iter = ((comprehension_ty)
3301 (asdl_seq_GET(e->v.GeneratorExp.generators,
3302 0)))->iter;
3303
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003304 if (!name) {
3305 name = PyString_FromString("<genexpr>");
3306 if (!name)
3307 return 0;
3308 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
3310 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3311 return 0;
3312 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3313 e->v.GeneratorExp.elt);
3314 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003315 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 if (co == NULL)
3317 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003318
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003319 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003320 Py_DECREF(co);
3321
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 VISIT(c, expr, outermost_iter);
3323 ADDOP(c, GET_ITER);
3324 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325
3326 return 1;
3327}
3328
3329static int
3330compiler_visit_keyword(struct compiler *c, keyword_ty k)
3331{
3332 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3333 VISIT(c, expr, k->value);
3334 return 1;
3335}
3336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003337/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338 whether they are true or false.
3339
3340 Return values: 1 for true, 0 for false, -1 for non-constant.
3341 */
3342
3343static int
3344expr_constant(expr_ty e)
3345{
3346 switch (e->kind) {
3347 case Num_kind:
3348 return PyObject_IsTrue(e->v.Num.n);
3349 case Str_kind:
3350 return PyObject_IsTrue(e->v.Str.s);
3351 default:
3352 return -1;
3353 }
3354}
3355
Guido van Rossumc2e20742006-02-27 22:32:47 +00003356/*
3357 Implements the with statement from PEP 343.
3358
3359 The semantics outlined in that PEP are as follows:
3360
3361 with EXPR as VAR:
3362 BLOCK
3363
3364 It is implemented roughly as:
3365
3366 context = (EXPR).__context__()
3367 exit = context.__exit__ # not calling it
3368 value = context.__enter__()
3369 try:
3370 VAR = value # if VAR present in the syntax
3371 BLOCK
3372 finally:
3373 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003374 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003375 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003376 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003377 exit(*exc)
3378 */
3379static int
3380compiler_with(struct compiler *c, stmt_ty s)
3381{
3382 static identifier context_attr, enter_attr, exit_attr;
3383 basicblock *block, *finally;
3384 identifier tmpexit, tmpvalue = NULL;
3385
3386 assert(s->kind == With_kind);
3387
3388 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003389 context_attr = PyString_InternFromString("__context__");
3390 if (!context_attr)
3391 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003392 }
3393 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003394 enter_attr = PyString_InternFromString("__enter__");
3395 if (!enter_attr)
3396 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003397 }
3398 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 exit_attr = PyString_InternFromString("__exit__");
3400 if (!exit_attr)
3401 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003402 }
3403
3404 block = compiler_new_block(c);
3405 finally = compiler_new_block(c);
3406 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003407 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003408
3409 /* Create a temporary variable to hold context.__exit__ */
3410 tmpexit = compiler_new_tmpname(c);
3411 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003413 PyArena_AddPyObject(c->c_arena, tmpexit);
3414
3415 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003416 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003417 We need to do this rather than preserving it on the stack
3418 because SETUP_FINALLY remembers the stack level.
3419 We need to do the assignment *inside* the try/finally
3420 so that context.__exit__() is called when the assignment
3421 fails. But we need to call context.__enter__() *before*
3422 the try/finally so that if it fails we won't call
3423 context.__exit__().
3424 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003425 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003426 if (tmpvalue == NULL)
3427 return 0;
3428 PyArena_AddPyObject(c->c_arena, tmpvalue);
3429 }
3430
3431 /* Evaluate (EXPR).__context__() */
3432 VISIT(c, expr, s->v.With.context_expr);
3433 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3434 ADDOP_I(c, CALL_FUNCTION, 0);
3435
3436 /* Squirrel away context.__exit__ */
3437 ADDOP(c, DUP_TOP);
3438 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3439 if (!compiler_nameop(c, tmpexit, Store))
3440 return 0;
3441
3442 /* Call context.__enter__() */
3443 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3444 ADDOP_I(c, CALL_FUNCTION, 0);
3445
3446 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 /* Store it in tmpvalue */
3448 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003449 return 0;
3450 }
3451 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003452 /* Discard result from context.__enter__() */
3453 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003454 }
3455
3456 /* Start the try block */
3457 ADDOP_JREL(c, SETUP_FINALLY, finally);
3458
3459 compiler_use_next_block(c, block);
3460 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003461 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003462 }
3463
3464 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003465 /* Bind saved result of context.__enter__() to VAR */
3466 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003467 !compiler_nameop(c, tmpvalue, Del))
3468 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003469 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003470 }
3471
3472 /* BLOCK code */
3473 VISIT_SEQ(c, stmt, s->v.With.body);
3474
3475 /* End of try block; start the finally block */
3476 ADDOP(c, POP_BLOCK);
3477 compiler_pop_fblock(c, FINALLY_TRY, block);
3478
3479 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3480 compiler_use_next_block(c, finally);
3481 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003483
3484 /* Finally block starts; push tmpexit and issue our magic opcode. */
3485 if (!compiler_nameop(c, tmpexit, Load) ||
3486 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003488 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003489
3490 /* Finally block ends. */
3491 ADDOP(c, END_FINALLY);
3492 compiler_pop_fblock(c, FINALLY_END, finally);
3493 return 1;
3494}
3495
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496static int
3497compiler_visit_expr(struct compiler *c, expr_ty e)
3498{
3499 int i, n;
3500
Jeremy Hylton12603c42006-04-01 16:18:02 +00003501 /* If expr e has a different line number than the last expr/stmt,
3502 set a new line number for the next instruction.
3503 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 if (e->lineno > c->u->u_lineno) {
3505 c->u->u_lineno = e->lineno;
3506 c->u->u_lineno_set = false;
3507 }
3508 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003509 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003512 VISIT(c, expr, e->v.BinOp.left);
3513 VISIT(c, expr, e->v.BinOp.right);
3514 ADDOP(c, binop(c, e->v.BinOp.op));
3515 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003516 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517 VISIT(c, expr, e->v.UnaryOp.operand);
3518 ADDOP(c, unaryop(e->v.UnaryOp.op));
3519 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003520 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003522 case IfExp_kind:
3523 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 /* XXX get rid of arg? */
3526 ADDOP_I(c, BUILD_MAP, 0);
3527 n = asdl_seq_LEN(e->v.Dict.values);
3528 /* We must arrange things just right for STORE_SUBSCR.
3529 It wants the stack to look like (value) (dict) (key) */
3530 for (i = 0; i < n; i++) {
3531 ADDOP(c, DUP_TOP);
3532 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3533 ADDOP(c, ROT_TWO);
3534 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3535 ADDOP(c, STORE_SUBSCR);
3536 }
3537 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003538 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003540 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 return compiler_genexp(c, e);
3542 case Yield_kind:
3543 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003544 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 /*
3546 for (i = 0; i < c->u->u_nfblocks; i++) {
3547 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3548 return compiler_error(
3549 c, "'yield' not allowed in a 'try' "
3550 "block with a 'finally' clause");
3551 }
3552 */
3553 if (e->v.Yield.value) {
3554 VISIT(c, expr, e->v.Yield.value);
3555 }
3556 else {
3557 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3558 }
3559 ADDOP(c, YIELD_VALUE);
3560 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003561 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003565 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 VISIT(c, expr, e->v.Repr.value);
3567 ADDOP(c, UNARY_CONVERT);
3568 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003569 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003570 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3571 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003572 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3574 break;
3575 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003576 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003577 if (e->v.Attribute.ctx != AugStore)
3578 VISIT(c, expr, e->v.Attribute.value);
3579 switch (e->v.Attribute.ctx) {
3580 case AugLoad:
3581 ADDOP(c, DUP_TOP);
3582 /* Fall through to load */
3583 case Load:
3584 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3585 break;
3586 case AugStore:
3587 ADDOP(c, ROT_TWO);
3588 /* Fall through to save */
3589 case Store:
3590 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3591 break;
3592 case Del:
3593 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3594 break;
3595 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003596 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003597 PyErr_SetString(PyExc_SystemError,
3598 "param invalid in attribute expression");
3599 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003600 }
3601 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003602 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003603 switch (e->v.Subscript.ctx) {
3604 case AugLoad:
3605 VISIT(c, expr, e->v.Subscript.value);
3606 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3607 break;
3608 case Load:
3609 VISIT(c, expr, e->v.Subscript.value);
3610 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3611 break;
3612 case AugStore:
3613 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3614 break;
3615 case Store:
3616 VISIT(c, expr, e->v.Subscript.value);
3617 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3618 break;
3619 case Del:
3620 VISIT(c, expr, e->v.Subscript.value);
3621 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3622 break;
3623 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003624 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003625 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003626 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003627 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628 }
3629 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003630 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3632 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003633 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003635 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 return compiler_tuple(c, e);
3637 }
3638 return 1;
3639}
3640
3641static int
3642compiler_augassign(struct compiler *c, stmt_ty s)
3643{
3644 expr_ty e = s->v.AugAssign.target;
3645 expr_ty auge;
3646
3647 assert(s->kind == AugAssign_kind);
3648
3649 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003650 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003652 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003653 if (auge == NULL)
3654 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 VISIT(c, expr, auge);
3656 VISIT(c, expr, s->v.AugAssign.value);
3657 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3658 auge->v.Attribute.ctx = AugStore;
3659 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 break;
3661 case Subscript_kind:
3662 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003663 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003664 if (auge == NULL)
3665 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666 VISIT(c, expr, auge);
3667 VISIT(c, expr, s->v.AugAssign.value);
3668 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003669 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003671 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003672 case Name_kind:
3673 VISIT(c, expr, s->v.AugAssign.target);
3674 VISIT(c, expr, s->v.AugAssign.value);
3675 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3676 return compiler_nameop(c, e->v.Name.id, Store);
3677 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003678 PyErr_Format(PyExc_SystemError,
3679 "invalid node type (%d) for augmented assignment",
3680 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 }
3683 return 1;
3684}
3685
3686static int
3687compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3688{
3689 struct fblockinfo *f;
3690 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3691 return 0;
3692 f = &c->u->u_fblock[c->u->u_nfblocks++];
3693 f->fb_type = t;
3694 f->fb_block = b;
3695 return 1;
3696}
3697
3698static void
3699compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3700{
3701 struct compiler_unit *u = c->u;
3702 assert(u->u_nfblocks > 0);
3703 u->u_nfblocks--;
3704 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3705 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3706}
3707
3708/* Raises a SyntaxError and returns 0.
3709 If something goes wrong, a different exception may be raised.
3710*/
3711
3712static int
3713compiler_error(struct compiler *c, const char *errstr)
3714{
3715 PyObject *loc;
3716 PyObject *u = NULL, *v = NULL;
3717
3718 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3719 if (!loc) {
3720 Py_INCREF(Py_None);
3721 loc = Py_None;
3722 }
3723 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3724 Py_None, loc);
3725 if (!u)
3726 goto exit;
3727 v = Py_BuildValue("(zO)", errstr, u);
3728 if (!v)
3729 goto exit;
3730 PyErr_SetObject(PyExc_SyntaxError, v);
3731 exit:
3732 Py_DECREF(loc);
3733 Py_XDECREF(u);
3734 Py_XDECREF(v);
3735 return 0;
3736}
3737
3738static int
3739compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003744 /* XXX this code is duplicated */
3745 switch (ctx) {
3746 case AugLoad: /* fall through to Load */
3747 case Load: op = BINARY_SUBSCR; break;
3748 case AugStore:/* fall through to Store */
3749 case Store: op = STORE_SUBSCR; break;
3750 case Del: op = DELETE_SUBSCR; break;
3751 case Param:
3752 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003753 "invalid %s kind %d in subscript\n",
3754 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003755 return 0;
3756 }
3757 if (ctx == AugLoad) {
3758 ADDOP_I(c, DUP_TOPX, 2);
3759 }
3760 else if (ctx == AugStore) {
3761 ADDOP(c, ROT_THREE);
3762 }
3763 ADDOP(c, op);
3764 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765}
3766
3767static int
3768compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3769{
3770 int n = 2;
3771 assert(s->kind == Slice_kind);
3772
3773 /* only handles the cases where BUILD_SLICE is emitted */
3774 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003775 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003776 }
3777 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003778 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003780
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003781 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003782 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003783 }
3784 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003785 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786 }
3787
3788 if (s->v.Slice.step) {
3789 n++;
3790 VISIT(c, expr, s->v.Slice.step);
3791 }
3792 ADDOP_I(c, BUILD_SLICE, n);
3793 return 1;
3794}
3795
3796static int
3797compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3798{
3799 int op = 0, slice_offset = 0, stack_count = 0;
3800
3801 assert(s->v.Slice.step == NULL);
3802 if (s->v.Slice.lower) {
3803 slice_offset++;
3804 stack_count++;
3805 if (ctx != AugStore)
3806 VISIT(c, expr, s->v.Slice.lower);
3807 }
3808 if (s->v.Slice.upper) {
3809 slice_offset += 2;
3810 stack_count++;
3811 if (ctx != AugStore)
3812 VISIT(c, expr, s->v.Slice.upper);
3813 }
3814
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003815 if (ctx == AugLoad) {
3816 switch (stack_count) {
3817 case 0: ADDOP(c, DUP_TOP); break;
3818 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3819 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3820 }
3821 }
3822 else if (ctx == AugStore) {
3823 switch (stack_count) {
3824 case 0: ADDOP(c, ROT_TWO); break;
3825 case 1: ADDOP(c, ROT_THREE); break;
3826 case 2: ADDOP(c, ROT_FOUR); break;
3827 }
3828 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829
3830 switch (ctx) {
3831 case AugLoad: /* fall through to Load */
3832 case Load: op = SLICE; break;
3833 case AugStore:/* fall through to Store */
3834 case Store: op = STORE_SLICE; break;
3835 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003836 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003837 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003838 PyErr_SetString(PyExc_SystemError,
3839 "param invalid in simple slice");
3840 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841 }
3842
3843 ADDOP(c, op + slice_offset);
3844 return 1;
3845}
3846
3847static int
3848compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3849 expr_context_ty ctx)
3850{
3851 switch (s->kind) {
3852 case Ellipsis_kind:
3853 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3854 break;
3855 case Slice_kind:
3856 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857 case Index_kind:
3858 VISIT(c, expr, s->v.Index.value);
3859 break;
3860 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003861 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003862 PyErr_SetString(PyExc_SystemError,
3863 "extended slice invalid in nested slice");
3864 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 }
3866 return 1;
3867}
3868
3869
3870static int
3871compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3872{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003873 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003875 case Index_kind:
3876 kindname = "index";
3877 if (ctx != AugStore) {
3878 VISIT(c, expr, s->v.Index.value);
3879 }
3880 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003882 kindname = "ellipsis";
3883 if (ctx != AugStore) {
3884 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 break;
3887 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003888 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 if (!s->v.Slice.step)
3890 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003891 if (ctx != AugStore) {
3892 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 return 0;
3894 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003895 break;
3896 case ExtSlice_kind:
3897 kindname = "extended slice";
3898 if (ctx != AugStore) {
3899 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3900 for (i = 0; i < n; i++) {
3901 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3902 if (!compiler_visit_nested_slice(c, sub, ctx))
3903 return 0;
3904 }
3905 ADDOP_I(c, BUILD_TUPLE, n);
3906 }
3907 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003908 default:
3909 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003910 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003911 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003912 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003913 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914}
3915
3916/* do depth-first search of basic block graph, starting with block.
3917 post records the block indices in post-order.
3918
3919 XXX must handle implicit jumps from one block to next
3920*/
3921
3922static void
3923dfs(struct compiler *c, basicblock *b, struct assembler *a)
3924{
3925 int i;
3926 struct instr *instr = NULL;
3927
3928 if (b->b_seen)
3929 return;
3930 b->b_seen = 1;
3931 if (b->b_next != NULL)
3932 dfs(c, b->b_next, a);
3933 for (i = 0; i < b->b_iused; i++) {
3934 instr = &b->b_instr[i];
3935 if (instr->i_jrel || instr->i_jabs)
3936 dfs(c, instr->i_target, a);
3937 }
3938 a->a_postorder[a->a_nblocks++] = b;
3939}
3940
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003941static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3943{
3944 int i;
3945 struct instr *instr;
3946 if (b->b_seen || b->b_startdepth >= depth)
3947 return maxdepth;
3948 b->b_seen = 1;
3949 b->b_startdepth = depth;
3950 for (i = 0; i < b->b_iused; i++) {
3951 instr = &b->b_instr[i];
3952 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3953 if (depth > maxdepth)
3954 maxdepth = depth;
3955 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3956 if (instr->i_jrel || instr->i_jabs) {
3957 maxdepth = stackdepth_walk(c, instr->i_target,
3958 depth, maxdepth);
3959 if (instr->i_opcode == JUMP_ABSOLUTE ||
3960 instr->i_opcode == JUMP_FORWARD) {
3961 goto out; /* remaining code is dead */
3962 }
3963 }
3964 }
3965 if (b->b_next)
3966 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3967out:
3968 b->b_seen = 0;
3969 return maxdepth;
3970}
3971
3972/* Find the flow path that needs the largest stack. We assume that
3973 * cycles in the flow graph have no net effect on the stack depth.
3974 */
3975static int
3976stackdepth(struct compiler *c)
3977{
3978 basicblock *b, *entryblock;
3979 entryblock = NULL;
3980 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3981 b->b_seen = 0;
3982 b->b_startdepth = INT_MIN;
3983 entryblock = b;
3984 }
3985 return stackdepth_walk(c, entryblock, 0, 0);
3986}
3987
3988static int
3989assemble_init(struct assembler *a, int nblocks, int firstlineno)
3990{
3991 memset(a, 0, sizeof(struct assembler));
3992 a->a_lineno = firstlineno;
3993 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3994 if (!a->a_bytecode)
3995 return 0;
3996 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3997 if (!a->a_lnotab)
3998 return 0;
3999 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004000 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004001 if (!a->a_postorder) {
4002 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004003 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004004 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 return 1;
4006}
4007
4008static void
4009assemble_free(struct assembler *a)
4010{
4011 Py_XDECREF(a->a_bytecode);
4012 Py_XDECREF(a->a_lnotab);
4013 if (a->a_postorder)
4014 PyObject_Free(a->a_postorder);
4015}
4016
4017/* Return the size of a basic block in bytes. */
4018
4019static int
4020instrsize(struct instr *instr)
4021{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004022 if (!instr->i_hasarg)
4023 return 1;
4024 if (instr->i_oparg > 0xffff)
4025 return 6;
4026 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004027}
4028
4029static int
4030blocksize(basicblock *b)
4031{
4032 int i;
4033 int size = 0;
4034
4035 for (i = 0; i < b->b_iused; i++)
4036 size += instrsize(&b->b_instr[i]);
4037 return size;
4038}
4039
4040/* All about a_lnotab.
4041
4042c_lnotab is an array of unsigned bytes disguised as a Python string.
4043It is used to map bytecode offsets to source code line #s (when needed
4044for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004045
Tim Peters2a7f3842001-06-09 09:26:21 +00004046The array is conceptually a list of
4047 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004048pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004050 byte code offset source code line number
4051 0 1
4052 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004053 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004054 350 307
4055 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004056
4057The first trick is that these numbers aren't stored, only the increments
4058from one row to the next (this doesn't really work, but it's a start):
4059
4060 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4061
4062The second trick is that an unsigned byte can't hold negative values, or
4063values larger than 255, so (a) there's a deep assumption that byte code
4064offsets and their corresponding line #s both increase monotonically, and (b)
4065if at least one column jumps by more than 255 from one row to the next, more
4066than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004067from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004068part. A user of c_lnotab desiring to find the source line number
4069corresponding to a bytecode address A should do something like this
4070
4071 lineno = addr = 0
4072 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004073 addr += addr_incr
4074 if addr > A:
4075 return lineno
4076 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004077
4078In order for this to work, when the addr field increments by more than 255,
4079the line # increment in each pair generated must be 0 until the remaining addr
4080increment is < 256. So, in the example above, com_set_lineno should not (as
4081was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004082255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004083*/
4084
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004085static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004086assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004087{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088 int d_bytecode, d_lineno;
4089 int len;
4090 char *lnotab;
4091
4092 d_bytecode = a->a_offset - a->a_lineno_off;
4093 d_lineno = i->i_lineno - a->a_lineno;
4094
4095 assert(d_bytecode >= 0);
4096 assert(d_lineno >= 0);
4097
4098 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004099 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004100
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004102 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 nbytes = a->a_lnotab_off + 2 * ncodes;
4104 len = PyString_GET_SIZE(a->a_lnotab);
4105 if (nbytes >= len) {
4106 if (len * 2 < nbytes)
4107 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004108 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109 len *= 2;
4110 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4111 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004112 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004114 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115 *lnotab++ = 255;
4116 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004117 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004118 d_bytecode -= ncodes * 255;
4119 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004120 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121 assert(d_bytecode <= 255);
4122 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004123 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 nbytes = a->a_lnotab_off + 2 * ncodes;
4125 len = PyString_GET_SIZE(a->a_lnotab);
4126 if (nbytes >= len) {
4127 if (len * 2 < nbytes)
4128 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004129 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 len *= 2;
4131 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4132 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004133 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4135 *lnotab++ = 255;
4136 *lnotab++ = d_bytecode;
4137 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004138 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139 *lnotab++ = 255;
4140 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004141 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142 d_lineno -= ncodes * 255;
4143 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004144 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146 len = PyString_GET_SIZE(a->a_lnotab);
4147 if (a->a_lnotab_off + 2 >= len) {
4148 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004149 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004150 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 a->a_lnotab_off += 2;
4154 if (d_bytecode) {
4155 *lnotab++ = d_bytecode;
4156 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004157 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004158 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 *lnotab++ = 0;
4160 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004161 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 a->a_lineno = i->i_lineno;
4163 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004164 return 1;
4165}
4166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167/* assemble_emit()
4168 Extend the bytecode with a new instruction.
4169 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004170*/
4171
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004172static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004174{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004175 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 int len = PyString_GET_SIZE(a->a_bytecode);
4177 char *code;
4178
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004179 size = instrsize(i);
4180 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004182 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004185 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 if (a->a_offset + size >= len) {
4187 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004188 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4191 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004192 if (size == 6) {
4193 assert(i->i_hasarg);
4194 *code++ = (char)EXTENDED_ARG;
4195 *code++ = ext & 0xff;
4196 *code++ = ext >> 8;
4197 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004200 if (i->i_hasarg) {
4201 assert(size == 3 || size == 6);
4202 *code++ = arg & 0xff;
4203 *code++ = arg >> 8;
4204 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004206}
4207
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004208static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004210{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004212 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004213 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 /* Compute the size of each block and fixup jump args.
4216 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004217start:
4218 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004219 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004220 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 bsize = blocksize(b);
4222 b->b_offset = totsize;
4223 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004224 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004225 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4227 bsize = b->b_offset;
4228 for (i = 0; i < b->b_iused; i++) {
4229 struct instr *instr = &b->b_instr[i];
4230 /* Relative jumps are computed relative to
4231 the instruction pointer after fetching
4232 the jump instruction.
4233 */
4234 bsize += instrsize(instr);
4235 if (instr->i_jabs)
4236 instr->i_oparg = instr->i_target->b_offset;
4237 else if (instr->i_jrel) {
4238 int delta = instr->i_target->b_offset - bsize;
4239 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004240 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004241 else
4242 continue;
4243 if (instr->i_oparg > 0xffff)
4244 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004245 }
4246 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004247
4248 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004249 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004250 with a better solution.
4251
4252 In the meantime, should the goto be dropped in favor
4253 of a loop?
4254
4255 The issue is that in the first loop blocksize() is called
4256 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004257 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004258 i_oparg is calculated in the second loop above.
4259
4260 So we loop until we stop seeing new EXTENDED_ARGs.
4261 The only EXTENDED_ARGs that could be popping up are
4262 ones in jump instructions. So this should converge
4263 fairly quickly.
4264 */
4265 if (last_extended_arg_count != extended_arg_count) {
4266 last_extended_arg_count = extended_arg_count;
4267 goto start;
4268 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004269}
4270
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004271static PyObject *
4272dict_keys_inorder(PyObject *dict, int offset)
4273{
4274 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004275 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004276
4277 tuple = PyTuple_New(size);
4278 if (tuple == NULL)
4279 return NULL;
4280 while (PyDict_Next(dict, &pos, &k, &v)) {
4281 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004282 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004283 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004284 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004285 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004286 PyTuple_SET_ITEM(tuple, i - offset, k);
4287 }
4288 return tuple;
4289}
4290
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004291static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004293{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004294 PySTEntryObject *ste = c->u->u_ste;
4295 int flags = 0, n;
4296 if (ste->ste_type != ModuleBlock)
4297 flags |= CO_NEWLOCALS;
4298 if (ste->ste_type == FunctionBlock) {
4299 if (!ste->ste_unoptimized)
4300 flags |= CO_OPTIMIZED;
4301 if (ste->ste_nested)
4302 flags |= CO_NESTED;
4303 if (ste->ste_generator)
4304 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306 if (ste->ste_varargs)
4307 flags |= CO_VARARGS;
4308 if (ste->ste_varkeywords)
4309 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004310 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004312
4313 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004314 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316 n = PyDict_Size(c->u->u_freevars);
4317 if (n < 0)
4318 return -1;
4319 if (n == 0) {
4320 n = PyDict_Size(c->u->u_cellvars);
4321 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004322 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323 if (n == 0) {
4324 flags |= CO_NOFREE;
4325 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004326 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004327
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004328 return flags;
4329}
4330
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331static PyCodeObject *
4332makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004333{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004334 PyObject *tmp;
4335 PyCodeObject *co = NULL;
4336 PyObject *consts = NULL;
4337 PyObject *names = NULL;
4338 PyObject *varnames = NULL;
4339 PyObject *filename = NULL;
4340 PyObject *name = NULL;
4341 PyObject *freevars = NULL;
4342 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004343 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346 tmp = dict_keys_inorder(c->u->u_consts, 0);
4347 if (!tmp)
4348 goto error;
4349 consts = PySequence_List(tmp); /* optimize_code requires a list */
4350 Py_DECREF(tmp);
4351
4352 names = dict_keys_inorder(c->u->u_names, 0);
4353 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4354 if (!consts || !names || !varnames)
4355 goto error;
4356
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004357 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4358 if (!cellvars)
4359 goto error;
4360 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4361 if (!freevars)
4362 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004363 filename = PyString_FromString(c->c_filename);
4364 if (!filename)
4365 goto error;
4366
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004367 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368 flags = compute_code_flags(c);
4369 if (flags < 0)
4370 goto error;
4371
4372 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4373 if (!bytecode)
4374 goto error;
4375
4376 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4377 if (!tmp)
4378 goto error;
4379 Py_DECREF(consts);
4380 consts = tmp;
4381
4382 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4383 bytecode, consts, names, varnames,
4384 freevars, cellvars,
4385 filename, c->u->u_name,
4386 c->u->u_firstlineno,
4387 a->a_lnotab);
4388 error:
4389 Py_XDECREF(consts);
4390 Py_XDECREF(names);
4391 Py_XDECREF(varnames);
4392 Py_XDECREF(filename);
4393 Py_XDECREF(name);
4394 Py_XDECREF(freevars);
4395 Py_XDECREF(cellvars);
4396 Py_XDECREF(bytecode);
4397 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004398}
4399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400static PyCodeObject *
4401assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004402{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004403 basicblock *b, *entryblock;
4404 struct assembler a;
4405 int i, j, nblocks;
4406 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 /* Make sure every block that falls off the end returns None.
4409 XXX NEXT_BLOCK() isn't quite right, because if the last
4410 block ends with a jump or return b_next shouldn't set.
4411 */
4412 if (!c->u->u_curblock->b_return) {
4413 NEXT_BLOCK(c);
4414 if (addNone)
4415 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4416 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004417 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004418
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419 nblocks = 0;
4420 entryblock = NULL;
4421 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4422 nblocks++;
4423 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004424 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4427 goto error;
4428 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004431 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433 /* Emit code in reverse postorder from dfs. */
4434 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004435 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436 for (j = 0; j < b->b_iused; j++)
4437 if (!assemble_emit(&a, &b->b_instr[j]))
4438 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004439 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004440
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4442 goto error;
4443 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4444 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004445
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446 co = makecode(c, &a);
4447 error:
4448 assemble_free(&a);
4449 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004450}