blob: abc488c58e96fcdb1c028f2283024eb4e47ab237 [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 character encodings aren't handled
Jeremy Hyltone36f7782001-01-19 03:21:30 +000039
Jeremy Hyltone9357b22006-03-01 15:47:05 +000040 ref leaks in interpreter when press return on empty line
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000041
Jeremy Hyltone9357b22006-03-01 15:47:05 +000042 opcode_stack_effect() function should be reviewed since stack depth bugs
43 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000044
Jeremy Hyltone9357b22006-03-01 15:47:05 +000045 Dead code is being generated (i.e. after unconditional jumps).
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000047
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000048#define DEFAULT_BLOCK_SIZE 16
49#define DEFAULT_BLOCKS 8
50#define DEFAULT_CODE_SIZE 128
51#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000053struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000054 unsigned i_jabs : 1;
55 unsigned i_jrel : 1;
56 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057 unsigned char i_opcode;
58 int i_oparg;
59 struct basicblock_ *i_target; /* target block (if jump instruction) */
60 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000061};
62
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063typedef struct basicblock_ {
64 /* next block in the list of blocks for a unit (don't confuse with
65 * b_next) */
66 struct basicblock_ *b_list;
67 /* number of instructions used */
68 int b_iused;
69 /* length of instruction array (b_instr) */
70 int b_ialloc;
71 /* pointer to an array of instructions, initially NULL */
72 struct instr *b_instr;
73 /* If b_next is non-NULL, it is a pointer to the next
74 block reached by normal control flow. */
75 struct basicblock_ *b_next;
76 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000079 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000080 /* depth of stack upon entry of block, computed by stackdepth() */
81 int b_startdepth;
82 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000083 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084} basicblock;
85
86/* fblockinfo tracks the current frame block.
87
Jeremy Hyltone9357b22006-03-01 15:47:05 +000088A frame block is used to handle loops, try/except, and try/finally.
89It's called a frame block to distinguish it from a basic block in the
90compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000091*/
92
93enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
94
95struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000096 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000097 basicblock *fb_block;
98};
99
100/* The following items change on entry and exit of code blocks.
101 They must be saved and restored when returning to a block.
102*/
103struct compiler_unit {
104 PySTEntryObject *u_ste;
105
106 PyObject *u_name;
107 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000108 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109 the argument for opcodes that refer to those collections.
110 */
111 PyObject *u_consts; /* all constants */
112 PyObject *u_names; /* all names */
113 PyObject *u_varnames; /* local variables */
114 PyObject *u_cellvars; /* cell variables */
115 PyObject *u_freevars; /* free variables */
116
117 PyObject *u_private; /* for private name mangling */
118
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000119 int u_argcount; /* number of arguments for block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120 basicblock *u_blocks; /* pointer to list of blocks */
121 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;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325 PyObject *v, *k, *dict = PyDict_New();
Guido van Rossumd076c731998-10-07 19:42:25 +0000326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 n = PyList_Size(list);
328 for (i = 0; i < n; i++) {
329 v = PyInt_FromLong(i);
330 if (!v) {
331 Py_DECREF(dict);
332 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000333 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000334 k = PyList_GET_ITEM(list, i);
335 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
337 Py_XDECREF(k);
338 Py_DECREF(v);
339 Py_DECREF(dict);
340 return NULL;
341 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000342 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000344 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 return dict;
346}
347
348/* Return new dict containing names from src that match scope(s).
349
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000350src is a symbol table dictionary. If the scope of a name matches
351either scope_type or flag is set, insert it into the new dict. The
352values are integers, starting at offset and increasing by one for
353each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354*/
355
356static PyObject *
357dictbytype(PyObject *src, int scope_type, int flag, int offset)
358{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000359 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000360 PyObject *k, *v, *dest = PyDict_New();
361
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000362 assert(offset >= 0);
363 if (dest == NULL)
364 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365
366 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 /* XXX this should probably be a macro in symtable.h */
368 assert(PyInt_Check(v));
369 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000371 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
372 PyObject *tuple, *item = PyInt_FromLong(i);
373 if (item == NULL) {
374 Py_DECREF(dest);
375 return NULL;
376 }
377 i++;
378 tuple = Py_BuildValue("(OO)", k, k->ob_type);
379 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
380 Py_DECREF(item);
381 Py_DECREF(dest);
382 Py_XDECREF(tuple);
383 return NULL;
384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000386 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388 }
389 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000390}
391
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000392/* Begin: Peephole optimizations ----------------------------------------- */
393
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000394#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000395#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000396#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
397#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000398#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000399#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000400#define ISBASICBLOCK(blocks, start, bytes) \
401 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000402
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000403/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000404 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000408 Bails out with no change if one or more of the LOAD_CONSTs is missing.
409 Also works for BUILD_LIST when followed by an "in" or "not in" test.
410*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000411static int
412tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
413{
414 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000415 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000416
417 /* Pre-conditions */
418 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000419 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000420 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000421 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000422 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423
424 /* Buildup new tuple of constants */
425 newconst = PyTuple_New(n);
426 if (newconst == NULL)
427 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000428 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000429 for (i=0 ; i<n ; i++) {
430 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000431 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000432 constant = PyList_GET_ITEM(consts, arg);
433 Py_INCREF(constant);
434 PyTuple_SET_ITEM(newconst, i, constant);
435 }
436
437 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000438 if (PyList_Append(consts, newconst)) {
439 Py_DECREF(newconst);
440 return 0;
441 }
442 Py_DECREF(newconst);
443
444 /* Write NOPs over old LOAD_CONSTS and
445 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
446 memset(codestr, NOP, n*3);
447 codestr[n*3] = LOAD_CONST;
448 SETARG(codestr, (n*3), len_consts);
449 return 1;
450}
451
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000452/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000453 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000457 Abandons the transformation if the folding fails (i.e. 1+'a').
458 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000459 is below a threshold value. That keeps pyc files from
460 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000461*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000462static int
463fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
464{
465 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000466 Py_ssize_t len_consts, size;
467 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000468
469 /* Pre-conditions */
470 assert(PyList_CheckExact(consts));
471 assert(codestr[0] == LOAD_CONST);
472 assert(codestr[3] == LOAD_CONST);
473
474 /* Create new constant */
475 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
476 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
477 opcode = codestr[6];
478 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000479 case BINARY_POWER:
480 newconst = PyNumber_Power(v, w, Py_None);
481 break;
482 case BINARY_MULTIPLY:
483 newconst = PyNumber_Multiply(v, w);
484 break;
485 case BINARY_DIVIDE:
486 /* Cannot fold this operation statically since
487 the result can depend on the run-time presence
488 of the -Qnew flag */
489 return 0;
490 case BINARY_TRUE_DIVIDE:
491 newconst = PyNumber_TrueDivide(v, w);
492 break;
493 case BINARY_FLOOR_DIVIDE:
494 newconst = PyNumber_FloorDivide(v, w);
495 break;
496 case BINARY_MODULO:
497 newconst = PyNumber_Remainder(v, w);
498 break;
499 case BINARY_ADD:
500 newconst = PyNumber_Add(v, w);
501 break;
502 case BINARY_SUBTRACT:
503 newconst = PyNumber_Subtract(v, w);
504 break;
505 case BINARY_SUBSCR:
506 newconst = PyObject_GetItem(v, w);
507 break;
508 case BINARY_LSHIFT:
509 newconst = PyNumber_Lshift(v, w);
510 break;
511 case BINARY_RSHIFT:
512 newconst = PyNumber_Rshift(v, w);
513 break;
514 case BINARY_AND:
515 newconst = PyNumber_And(v, w);
516 break;
517 case BINARY_XOR:
518 newconst = PyNumber_Xor(v, w);
519 break;
520 case BINARY_OR:
521 newconst = PyNumber_Or(v, w);
522 break;
523 default:
524 /* Called with an unknown opcode */
525 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000526 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000527 opcode);
528 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000529 }
530 if (newconst == NULL) {
531 PyErr_Clear();
532 return 0;
533 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000534 size = PyObject_Size(newconst);
535 if (size == -1)
536 PyErr_Clear();
537 else if (size > 20) {
538 Py_DECREF(newconst);
539 return 0;
540 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000541
542 /* Append folded constant into consts table */
543 len_consts = PyList_GET_SIZE(consts);
544 if (PyList_Append(consts, newconst)) {
545 Py_DECREF(newconst);
546 return 0;
547 }
548 Py_DECREF(newconst);
549
550 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
551 memset(codestr, NOP, 4);
552 codestr[4] = LOAD_CONST;
553 SETARG(codestr, 4, len_consts);
554 return 1;
555}
556
Raymond Hettinger80121492005-02-20 12:41:32 +0000557static int
558fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
559{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000560 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000561 Py_ssize_t len_consts;
562 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000563
564 /* Pre-conditions */
565 assert(PyList_CheckExact(consts));
566 assert(codestr[0] == LOAD_CONST);
567
568 /* Create new constant */
569 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
570 opcode = codestr[3];
571 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000572 case UNARY_NEGATIVE:
573 /* Preserve the sign of -0.0 */
574 if (PyObject_IsTrue(v) == 1)
575 newconst = PyNumber_Negative(v);
576 break;
577 case UNARY_CONVERT:
578 newconst = PyObject_Repr(v);
579 break;
580 case UNARY_INVERT:
581 newconst = PyNumber_Invert(v);
582 break;
583 default:
584 /* Called with an unknown opcode */
585 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000586 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000587 opcode);
588 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000589 }
590 if (newconst == NULL) {
591 PyErr_Clear();
592 return 0;
593 }
594
595 /* Append folded constant into consts table */
596 len_consts = PyList_GET_SIZE(consts);
597 if (PyList_Append(consts, newconst)) {
598 Py_DECREF(newconst);
599 return 0;
600 }
601 Py_DECREF(newconst);
602
603 /* Write NOP LOAD_CONST newconst */
604 codestr[0] = NOP;
605 codestr[1] = LOAD_CONST;
606 SETARG(codestr, 1, len_consts);
607 return 1;
608}
609
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000610static unsigned int *
611markblocks(unsigned char *code, int len)
612{
613 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000614 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000615
616 if (blocks == NULL)
617 return NULL;
618 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000619
620 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000621 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
622 opcode = code[i];
623 switch (opcode) {
624 case FOR_ITER:
625 case JUMP_FORWARD:
626 case JUMP_IF_FALSE:
627 case JUMP_IF_TRUE:
628 case JUMP_ABSOLUTE:
629 case CONTINUE_LOOP:
630 case SETUP_LOOP:
631 case SETUP_EXCEPT:
632 case SETUP_FINALLY:
633 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000634 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000635 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000636 }
637 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000638 /* Build block numbers in the second pass */
639 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000640 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000641 blocks[i] = blockcnt;
642 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000643 return blocks;
644}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000645
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000646/* Perform basic peephole optimizations to components of a code object.
647 The consts object should still be in list form to allow new constants
648 to be appended.
649
650 To keep the optimizer simple, it bails out (does nothing) for code
651 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000652 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000653 the lineno table has complex encoding for gaps >= 255.
654
655 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000656 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000657 smaller. For those that reduce size, the gaps are initially filled with
658 NOPs. Later those NOPs are removed and the jump addresses retargeted in
659 a single pass. Line numbering is adjusted accordingly. */
660
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000661static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000662optimize_code(PyObject *code, PyObject* consts, PyObject *names,
663 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000664{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000665 Py_ssize_t i, j, codelen;
666 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000667 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000668 unsigned char *codestr = NULL;
669 unsigned char *lineno;
670 int *addrmap = NULL;
671 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000672 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000673 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000674 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000675
Raymond Hettingereffb3932004-10-30 08:55:08 +0000676 /* Bail out if an exception is set */
677 if (PyErr_Occurred())
678 goto exitUnchanged;
679
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000680 /* Bypass optimization when the lineno table is too complex */
681 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000682 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000683 tabsiz = PyString_GET_SIZE(lineno_obj);
684 if (memchr(lineno, 255, tabsiz) != NULL)
685 goto exitUnchanged;
686
Raymond Hettingera12fa142004-08-24 04:34:16 +0000687 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000688 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000689 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000690 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000691 goto exitUnchanged;
692
693 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000694 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000695 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000696 goto exitUnchanged;
697 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000698
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000699 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000700 the various transformation patterns to look ahead several
701 instructions without additional checks to make sure they are not
702 looking beyond the end of the code string.
703 */
704 if (codestr[codelen-1] != RETURN_VALUE)
705 goto exitUnchanged;
706
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000707 /* Mapping to new jump targets after NOPs are removed */
708 addrmap = PyMem_Malloc(codelen * sizeof(int));
709 if (addrmap == NULL)
710 goto exitUnchanged;
711
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000712 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000713 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000714 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000715 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000716
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000717 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000718 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000719
720 lastlc = cumlc;
721 cumlc = 0;
722
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000723 switch (opcode) {
724
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000725 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
726 with JUMP_IF_TRUE POP_TOP */
727 case UNARY_NOT:
728 if (codestr[i+1] != JUMP_IF_FALSE ||
729 codestr[i+4] != POP_TOP ||
730 !ISBASICBLOCK(blocks,i,5))
731 continue;
732 tgt = GETJUMPTGT(codestr, (i+1));
733 if (codestr[tgt] != POP_TOP)
734 continue;
735 j = GETARG(codestr, i+1) + 1;
736 codestr[i] = JUMP_IF_TRUE;
737 SETARG(codestr, i, j);
738 codestr[i+3] = POP_TOP;
739 codestr[i+4] = NOP;
740 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000741
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000742 /* not a is b --> a is not b
743 not a in b --> a not in b
744 not a is not b --> a is b
745 not a not in b --> a in b
746 */
747 case COMPARE_OP:
748 j = GETARG(codestr, i);
749 if (j < 6 || j > 9 ||
750 codestr[i+3] != UNARY_NOT ||
751 !ISBASICBLOCK(blocks,i,4))
752 continue;
753 SETARG(codestr, i, (j^1));
754 codestr[i+3] = NOP;
755 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000756
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000757 /* Replace LOAD_GLOBAL/LOAD_NAME None
758 with LOAD_CONST None */
759 case LOAD_NAME:
760 case LOAD_GLOBAL:
761 j = GETARG(codestr, i);
762 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
763 if (name == NULL || strcmp(name, "None") != 0)
764 continue;
765 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
766 if (PyList_GET_ITEM(consts, j) == Py_None) {
767 codestr[i] = LOAD_CONST;
768 SETARG(codestr, i, j);
769 cumlc = lastlc + 1;
770 break;
771 }
772 }
773 break;
774
775 /* Skip over LOAD_CONST trueconst
776 JUMP_IF_FALSE xx POP_TOP */
777 case LOAD_CONST:
778 cumlc = lastlc + 1;
779 j = GETARG(codestr, i);
780 if (codestr[i+3] != JUMP_IF_FALSE ||
781 codestr[i+6] != POP_TOP ||
782 !ISBASICBLOCK(blocks,i,7) ||
783 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
784 continue;
785 memset(codestr+i, NOP, 7);
786 cumlc = 0;
787 break;
788
789 /* Try to fold tuples of constants (includes a case for lists
790 which are only used for "in" and "not in" tests).
791 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
792 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
793 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
794 case BUILD_TUPLE:
795 case BUILD_LIST:
796 j = GETARG(codestr, i);
797 h = i - 3 * j;
798 if (h >= 0 &&
799 j <= lastlc &&
800 ((opcode == BUILD_TUPLE &&
801 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
802 (opcode == BUILD_LIST &&
803 codestr[i+3]==COMPARE_OP &&
804 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
805 (GETARG(codestr,i+3)==6 ||
806 GETARG(codestr,i+3)==7))) &&
807 tuple_of_constants(&codestr[h], j, consts)) {
808 assert(codestr[i] == LOAD_CONST);
809 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000810 break;
811 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000812 if (codestr[i+3] != UNPACK_SEQUENCE ||
813 !ISBASICBLOCK(blocks,i,6) ||
814 j != GETARG(codestr, i+3))
815 continue;
816 if (j == 1) {
817 memset(codestr+i, NOP, 6);
818 } else if (j == 2) {
819 codestr[i] = ROT_TWO;
820 memset(codestr+i+1, NOP, 5);
821 } else if (j == 3) {
822 codestr[i] = ROT_THREE;
823 codestr[i+1] = ROT_TWO;
824 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000825 }
826 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000827
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000828 /* Fold binary ops on constants.
829 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
830 case BINARY_POWER:
831 case BINARY_MULTIPLY:
832 case BINARY_TRUE_DIVIDE:
833 case BINARY_FLOOR_DIVIDE:
834 case BINARY_MODULO:
835 case BINARY_ADD:
836 case BINARY_SUBTRACT:
837 case BINARY_SUBSCR:
838 case BINARY_LSHIFT:
839 case BINARY_RSHIFT:
840 case BINARY_AND:
841 case BINARY_XOR:
842 case BINARY_OR:
843 if (lastlc >= 2 &&
844 ISBASICBLOCK(blocks, i-6, 7) &&
845 fold_binops_on_constants(&codestr[i-6], consts)) {
846 i -= 2;
847 assert(codestr[i] == LOAD_CONST);
848 cumlc = 1;
849 }
850 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000851
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000852 /* Fold unary ops on constants.
853 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
854 case UNARY_NEGATIVE:
855 case UNARY_CONVERT:
856 case UNARY_INVERT:
857 if (lastlc >= 1 &&
858 ISBASICBLOCK(blocks, i-3, 4) &&
859 fold_unaryops_on_constants(&codestr[i-3], consts)) {
860 i -= 2;
861 assert(codestr[i] == LOAD_CONST);
862 cumlc = 1;
863 }
864 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000865
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000866 /* Simplify conditional jump to conditional jump where the
867 result of the first test implies the success of a similar
868 test or the failure of the opposite test.
869 Arises in code like:
870 "if a and b:"
871 "if a or b:"
872 "a and b or c"
873 "(a and b) and c"
874 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
875 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
876 where y+3 is the instruction following the second test.
877 */
878 case JUMP_IF_FALSE:
879 case JUMP_IF_TRUE:
880 tgt = GETJUMPTGT(codestr, i);
881 j = codestr[tgt];
882 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
883 if (j == opcode) {
884 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
885 SETARG(codestr, i, tgttgt);
886 } else {
887 tgt -= i;
888 SETARG(codestr, i, tgt);
889 }
890 break;
891 }
892 /* Intentional fallthrough */
893
894 /* Replace jumps to unconditional jumps */
895 case FOR_ITER:
896 case JUMP_FORWARD:
897 case JUMP_ABSOLUTE:
898 case CONTINUE_LOOP:
899 case SETUP_LOOP:
900 case SETUP_EXCEPT:
901 case SETUP_FINALLY:
902 tgt = GETJUMPTGT(codestr, i);
903 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
904 continue;
905 tgttgt = GETJUMPTGT(codestr, tgt);
906 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
907 opcode = JUMP_ABSOLUTE;
908 if (!ABSOLUTE_JUMP(opcode))
909 tgttgt -= i + 3; /* Calc relative jump addr */
910 if (tgttgt < 0) /* No backward relative jumps */
911 continue;
912 codestr[i] = opcode;
913 SETARG(codestr, i, tgttgt);
914 break;
915
916 case EXTENDED_ARG:
917 goto exitUnchanged;
918
919 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
920 case RETURN_VALUE:
921 if (i+4 >= codelen ||
922 codestr[i+4] != RETURN_VALUE ||
923 !ISBASICBLOCK(blocks,i,5))
924 continue;
925 memset(codestr+i+1, NOP, 4);
926 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000927 }
928 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000929
930 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000931 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
932 addrmap[i] = i - nops;
933 if (codestr[i] == NOP)
934 nops++;
935 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000936 cum_orig_line = 0;
937 last_line = 0;
938 for (i=0 ; i < tabsiz ; i+=2) {
939 cum_orig_line += lineno[i];
940 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000941 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000942 lineno[i] =((unsigned char)(new_line - last_line));
943 last_line = new_line;
944 }
945
946 /* Remove NOPs and fixup jump targets */
947 for (i=0, h=0 ; i<codelen ; ) {
948 opcode = codestr[i];
949 switch (opcode) {
950 case NOP:
951 i++;
952 continue;
953
954 case JUMP_ABSOLUTE:
955 case CONTINUE_LOOP:
956 j = addrmap[GETARG(codestr, i)];
957 SETARG(codestr, i, j);
958 break;
959
960 case FOR_ITER:
961 case JUMP_FORWARD:
962 case JUMP_IF_FALSE:
963 case JUMP_IF_TRUE:
964 case SETUP_LOOP:
965 case SETUP_EXCEPT:
966 case SETUP_FINALLY:
967 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
968 SETARG(codestr, i, j);
969 break;
970 }
971 adj = CODESIZE(opcode);
972 while (adj--)
973 codestr[h++] = codestr[i++];
974 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000975 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000976
977 code = PyString_FromStringAndSize((char *)codestr, h);
978 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000979 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000980 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000981 return code;
982
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000983 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000984 if (blocks != NULL)
985 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000986 if (addrmap != NULL)
987 PyMem_Free(addrmap);
988 if (codestr != NULL)
989 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000990 Py_INCREF(code);
991 return code;
992}
993
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000994/* End: Peephole optimizations ----------------------------------------- */
995
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000996/*
997
998Leave this debugging code for just a little longer.
999
1000static void
1001compiler_display_symbols(PyObject *name, PyObject *symbols)
1002{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003PyObject *key, *value;
1004int flags;
1005Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001006
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001007fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1008while (PyDict_Next(symbols, &pos, &key, &value)) {
1009flags = PyInt_AsLong(value);
1010fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1011if (flags & DEF_GLOBAL)
1012fprintf(stderr, " declared_global");
1013if (flags & DEF_LOCAL)
1014fprintf(stderr, " local");
1015if (flags & DEF_PARAM)
1016fprintf(stderr, " param");
1017if (flags & DEF_STAR)
1018fprintf(stderr, " stararg");
1019if (flags & DEF_DOUBLESTAR)
1020fprintf(stderr, " starstar");
1021if (flags & DEF_INTUPLE)
1022fprintf(stderr, " tuple");
1023if (flags & DEF_FREE)
1024fprintf(stderr, " free");
1025if (flags & DEF_FREE_GLOBAL)
1026fprintf(stderr, " global");
1027if (flags & DEF_FREE_CLASS)
1028fprintf(stderr, " free/class");
1029if (flags & DEF_IMPORT)
1030fprintf(stderr, " import");
1031fprintf(stderr, "\n");
1032}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033 fprintf(stderr, "\n");
1034}
1035*/
1036
1037static void
1038compiler_unit_check(struct compiler_unit *u)
1039{
1040 basicblock *block;
1041 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1042 assert(block != (void *)0xcbcbcbcb);
1043 assert(block != (void *)0xfbfbfbfb);
1044 assert(block != (void *)0xdbdbdbdb);
1045 if (block->b_instr != NULL) {
1046 assert(block->b_ialloc > 0);
1047 assert(block->b_iused > 0);
1048 assert(block->b_ialloc >= block->b_iused);
1049 }
1050 else {
1051 assert (block->b_iused == 0);
1052 assert (block->b_ialloc == 0);
1053 }
1054 }
1055}
1056
1057static void
1058compiler_unit_free(struct compiler_unit *u)
1059{
1060 basicblock *b, *next;
1061
1062 compiler_unit_check(u);
1063 b = u->u_blocks;
1064 while (b != NULL) {
1065 if (b->b_instr)
1066 PyObject_Free((void *)b->b_instr);
1067 next = b->b_list;
1068 PyObject_Free((void *)b);
1069 b = next;
1070 }
1071 Py_XDECREF(u->u_ste);
1072 Py_XDECREF(u->u_name);
1073 Py_XDECREF(u->u_consts);
1074 Py_XDECREF(u->u_names);
1075 Py_XDECREF(u->u_varnames);
1076 Py_XDECREF(u->u_freevars);
1077 Py_XDECREF(u->u_cellvars);
1078 Py_XDECREF(u->u_private);
1079 PyObject_Free(u);
1080}
1081
1082static int
1083compiler_enter_scope(struct compiler *c, identifier name, void *key,
1084 int lineno)
1085{
1086 struct compiler_unit *u;
1087
1088 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001089 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001090 PyErr_NoMemory();
1091 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001092 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001093 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001094 u->u_argcount = 0;
1095 u->u_ste = PySymtable_Lookup(c->c_st, key);
1096 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 compiler_unit_free(u);
1098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099 }
1100 Py_INCREF(name);
1101 u->u_name = name;
1102 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1103 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1104 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001105 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001106
1107 u->u_blocks = NULL;
1108 u->u_tmpname = 0;
1109 u->u_nfblocks = 0;
1110 u->u_firstlineno = lineno;
1111 u->u_lineno = 0;
1112 u->u_lineno_set = false;
1113 u->u_consts = PyDict_New();
1114 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001115 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001116 return 0;
1117 }
1118 u->u_names = PyDict_New();
1119 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001120 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001121 return 0;
1122 }
1123
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001124 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125
1126 /* Push the old compiler_unit on the stack. */
1127 if (c->u) {
1128 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1129 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001130 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001131 return 0;
1132 }
1133 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001134 u->u_private = c->u->u_private;
1135 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136 }
1137 c->u = u;
1138
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001139 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001140 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001141 return 0;
1142
1143 return 1;
1144}
1145
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001146static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147compiler_exit_scope(struct compiler *c)
1148{
1149 int n;
1150 PyObject *wrapper;
1151
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001152 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153 compiler_unit_free(c->u);
1154 /* Restore c->u to the parent unit. */
1155 n = PyList_GET_SIZE(c->c_stack) - 1;
1156 if (n >= 0) {
1157 wrapper = PyList_GET_ITEM(c->c_stack, n);
1158 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001159 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001161 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 compiler_unit_check(c->u);
1163 }
1164 else
1165 c->u = NULL;
1166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167}
1168
Guido van Rossumc2e20742006-02-27 22:32:47 +00001169/* Allocate a new "anonymous" local variable.
1170 Used by list comprehensions and with statements.
1171*/
1172
1173static PyObject *
1174compiler_new_tmpname(struct compiler *c)
1175{
1176 char tmpname[256];
1177 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1178 return PyString_FromString(tmpname);
1179}
1180
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181/* Allocate a new block and return a pointer to it.
1182 Returns NULL on error.
1183*/
1184
1185static basicblock *
1186compiler_new_block(struct compiler *c)
1187{
1188 basicblock *b;
1189 struct compiler_unit *u;
1190
1191 u = c->u;
1192 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001193 if (b == NULL) {
1194 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001197 memset((void *)b, 0, sizeof(basicblock));
1198 assert (b->b_next == NULL);
1199 b->b_list = u->u_blocks;
1200 u->u_blocks = b;
1201 return b;
1202}
1203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001204static basicblock *
1205compiler_use_new_block(struct compiler *c)
1206{
1207 basicblock *block = compiler_new_block(c);
1208 if (block == NULL)
1209 return NULL;
1210 c->u->u_curblock = block;
1211 return block;
1212}
1213
1214static basicblock *
1215compiler_next_block(struct compiler *c)
1216{
1217 basicblock *block = compiler_new_block(c);
1218 if (block == NULL)
1219 return NULL;
1220 c->u->u_curblock->b_next = block;
1221 c->u->u_curblock = block;
1222 return block;
1223}
1224
1225static basicblock *
1226compiler_use_next_block(struct compiler *c, basicblock *block)
1227{
1228 assert(block != NULL);
1229 c->u->u_curblock->b_next = block;
1230 c->u->u_curblock = block;
1231 return block;
1232}
1233
1234/* Returns the offset of the next instruction in the current block's
1235 b_instr array. Resizes the b_instr as necessary.
1236 Returns -1 on failure.
1237 */
1238
1239static int
1240compiler_next_instr(struct compiler *c, basicblock *b)
1241{
1242 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001243 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001244 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1245 DEFAULT_BLOCK_SIZE);
1246 if (b->b_instr == NULL) {
1247 PyErr_NoMemory();
1248 return -1;
1249 }
1250 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1251 memset((char *)b->b_instr, 0,
1252 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001253 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001254 else if (b->b_iused == b->b_ialloc) {
1255 size_t oldsize, newsize;
1256 oldsize = b->b_ialloc * sizeof(struct instr);
1257 newsize = oldsize << 1;
1258 if (newsize == 0) {
1259 PyErr_NoMemory();
1260 return -1;
1261 }
1262 b->b_ialloc <<= 1;
1263 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1264 if (b->b_instr == NULL)
1265 return -1;
1266 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1267 }
1268 return b->b_iused++;
1269}
1270
1271static void
1272compiler_set_lineno(struct compiler *c, int off)
1273{
1274 basicblock *b;
1275 if (c->u->u_lineno_set)
1276 return;
1277 c->u->u_lineno_set = true;
1278 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001279 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001280}
1281
1282static int
1283opcode_stack_effect(int opcode, int oparg)
1284{
1285 switch (opcode) {
1286 case POP_TOP:
1287 return -1;
1288 case ROT_TWO:
1289 case ROT_THREE:
1290 return 0;
1291 case DUP_TOP:
1292 return 1;
1293 case ROT_FOUR:
1294 return 0;
1295
1296 case UNARY_POSITIVE:
1297 case UNARY_NEGATIVE:
1298 case UNARY_NOT:
1299 case UNARY_CONVERT:
1300 case UNARY_INVERT:
1301 return 0;
1302
1303 case BINARY_POWER:
1304 case BINARY_MULTIPLY:
1305 case BINARY_DIVIDE:
1306 case BINARY_MODULO:
1307 case BINARY_ADD:
1308 case BINARY_SUBTRACT:
1309 case BINARY_SUBSCR:
1310 case BINARY_FLOOR_DIVIDE:
1311 case BINARY_TRUE_DIVIDE:
1312 return -1;
1313 case INPLACE_FLOOR_DIVIDE:
1314 case INPLACE_TRUE_DIVIDE:
1315 return -1;
1316
1317 case SLICE+0:
1318 return 1;
1319 case SLICE+1:
1320 return 0;
1321 case SLICE+2:
1322 return 0;
1323 case SLICE+3:
1324 return -1;
1325
1326 case STORE_SLICE+0:
1327 return -2;
1328 case STORE_SLICE+1:
1329 return -3;
1330 case STORE_SLICE+2:
1331 return -3;
1332 case STORE_SLICE+3:
1333 return -4;
1334
1335 case DELETE_SLICE+0:
1336 return -1;
1337 case DELETE_SLICE+1:
1338 return -2;
1339 case DELETE_SLICE+2:
1340 return -2;
1341 case DELETE_SLICE+3:
1342 return -3;
1343
1344 case INPLACE_ADD:
1345 case INPLACE_SUBTRACT:
1346 case INPLACE_MULTIPLY:
1347 case INPLACE_DIVIDE:
1348 case INPLACE_MODULO:
1349 return -1;
1350 case STORE_SUBSCR:
1351 return -3;
1352 case DELETE_SUBSCR:
1353 return -2;
1354
1355 case BINARY_LSHIFT:
1356 case BINARY_RSHIFT:
1357 case BINARY_AND:
1358 case BINARY_XOR:
1359 case BINARY_OR:
1360 return -1;
1361 case INPLACE_POWER:
1362 return -1;
1363 case GET_ITER:
1364 return 0;
1365
1366 case PRINT_EXPR:
1367 return -1;
1368 case PRINT_ITEM:
1369 return -1;
1370 case PRINT_NEWLINE:
1371 return 0;
1372 case PRINT_ITEM_TO:
1373 return -2;
1374 case PRINT_NEWLINE_TO:
1375 return -1;
1376 case INPLACE_LSHIFT:
1377 case INPLACE_RSHIFT:
1378 case INPLACE_AND:
1379 case INPLACE_XOR:
1380 case INPLACE_OR:
1381 return -1;
1382 case BREAK_LOOP:
1383 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001384 case WITH_CLEANUP:
1385 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 case LOAD_LOCALS:
1387 return 1;
1388 case RETURN_VALUE:
1389 return -1;
1390 case IMPORT_STAR:
1391 return -1;
1392 case EXEC_STMT:
1393 return -3;
1394 case YIELD_VALUE:
1395 return 0;
1396
1397 case POP_BLOCK:
1398 return 0;
1399 case END_FINALLY:
1400 return -1; /* or -2 or -3 if exception occurred */
1401 case BUILD_CLASS:
1402 return -2;
1403
1404 case STORE_NAME:
1405 return -1;
1406 case DELETE_NAME:
1407 return 0;
1408 case UNPACK_SEQUENCE:
1409 return oparg-1;
1410 case FOR_ITER:
1411 return 1;
1412
1413 case STORE_ATTR:
1414 return -2;
1415 case DELETE_ATTR:
1416 return -1;
1417 case STORE_GLOBAL:
1418 return -1;
1419 case DELETE_GLOBAL:
1420 return 0;
1421 case DUP_TOPX:
1422 return oparg;
1423 case LOAD_CONST:
1424 return 1;
1425 case LOAD_NAME:
1426 return 1;
1427 case BUILD_TUPLE:
1428 case BUILD_LIST:
1429 return 1-oparg;
1430 case BUILD_MAP:
1431 return 1;
1432 case LOAD_ATTR:
1433 return 0;
1434 case COMPARE_OP:
1435 return -1;
1436 case IMPORT_NAME:
1437 return 0;
1438 case IMPORT_FROM:
1439 return 1;
1440
1441 case JUMP_FORWARD:
1442 case JUMP_IF_FALSE:
1443 case JUMP_IF_TRUE:
1444 case JUMP_ABSOLUTE:
1445 return 0;
1446
1447 case LOAD_GLOBAL:
1448 return 1;
1449
1450 case CONTINUE_LOOP:
1451 return 0;
1452 case SETUP_LOOP:
1453 return 0;
1454 case SETUP_EXCEPT:
1455 case SETUP_FINALLY:
1456 return 3; /* actually pushed by an exception */
1457
1458 case LOAD_FAST:
1459 return 1;
1460 case STORE_FAST:
1461 return -1;
1462 case DELETE_FAST:
1463 return 0;
1464
1465 case RAISE_VARARGS:
1466 return -oparg;
1467#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1468 case CALL_FUNCTION:
1469 return -NARGS(oparg);
1470 case CALL_FUNCTION_VAR:
1471 case CALL_FUNCTION_KW:
1472 return -NARGS(oparg)-1;
1473 case CALL_FUNCTION_VAR_KW:
1474 return -NARGS(oparg)-2;
1475#undef NARGS
1476 case MAKE_FUNCTION:
1477 return -oparg;
1478 case BUILD_SLICE:
1479 if (oparg == 3)
1480 return -2;
1481 else
1482 return -1;
1483
1484 case MAKE_CLOSURE:
1485 return -oparg;
1486 case LOAD_CLOSURE:
1487 return 1;
1488 case LOAD_DEREF:
1489 return 1;
1490 case STORE_DEREF:
1491 return -1;
1492 default:
1493 fprintf(stderr, "opcode = %d\n", opcode);
1494 Py_FatalError("opcode_stack_effect()");
1495
1496 }
1497 return 0; /* not reachable */
1498}
1499
1500/* Add an opcode with no argument.
1501 Returns 0 on failure, 1 on success.
1502*/
1503
1504static int
1505compiler_addop(struct compiler *c, int opcode)
1506{
1507 basicblock *b;
1508 struct instr *i;
1509 int off;
1510 off = compiler_next_instr(c, c->u->u_curblock);
1511 if (off < 0)
1512 return 0;
1513 b = c->u->u_curblock;
1514 i = &b->b_instr[off];
1515 i->i_opcode = opcode;
1516 i->i_hasarg = 0;
1517 if (opcode == RETURN_VALUE)
1518 b->b_return = 1;
1519 compiler_set_lineno(c, off);
1520 return 1;
1521}
1522
1523static int
1524compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1525{
1526 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001529 /* necessary to make sure types aren't coerced (e.g., int and long) */
1530 t = PyTuple_Pack(2, o, o->ob_type);
1531 if (t == NULL)
1532 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533
1534 v = PyDict_GetItem(dict, t);
1535 if (!v) {
1536 arg = PyDict_Size(dict);
1537 v = PyInt_FromLong(arg);
1538 if (!v) {
1539 Py_DECREF(t);
1540 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001541 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542 if (PyDict_SetItem(dict, t, v) < 0) {
1543 Py_DECREF(t);
1544 Py_DECREF(v);
1545 return -1;
1546 }
1547 Py_DECREF(v);
1548 }
1549 else
1550 arg = PyInt_AsLong(v);
1551 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001552 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001553}
1554
1555static int
1556compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1557 PyObject *o)
1558{
1559 int arg = compiler_add_o(c, dict, o);
1560 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562 return compiler_addop_i(c, opcode, arg);
1563}
1564
1565static int
1566compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568{
1569 int arg;
1570 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1571 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001572 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 arg = compiler_add_o(c, dict, mangled);
1574 Py_DECREF(mangled);
1575 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001576 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 return compiler_addop_i(c, opcode, arg);
1578}
1579
1580/* Add an opcode with an integer argument.
1581 Returns 0 on failure, 1 on success.
1582*/
1583
1584static int
1585compiler_addop_i(struct compiler *c, int opcode, int oparg)
1586{
1587 struct instr *i;
1588 int off;
1589 off = compiler_next_instr(c, c->u->u_curblock);
1590 if (off < 0)
1591 return 0;
1592 i = &c->u->u_curblock->b_instr[off];
1593 i->i_opcode = opcode;
1594 i->i_oparg = oparg;
1595 i->i_hasarg = 1;
1596 compiler_set_lineno(c, off);
1597 return 1;
1598}
1599
1600static int
1601compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1602{
1603 struct instr *i;
1604 int off;
1605
1606 assert(b != NULL);
1607 off = compiler_next_instr(c, c->u->u_curblock);
1608 if (off < 0)
1609 return 0;
1610 compiler_set_lineno(c, off);
1611 i = &c->u->u_curblock->b_instr[off];
1612 i->i_opcode = opcode;
1613 i->i_target = b;
1614 i->i_hasarg = 1;
1615 if (absolute)
1616 i->i_jabs = 1;
1617 else
1618 i->i_jrel = 1;
1619 return 1;
1620}
1621
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001622/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1623 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624 it as the current block. NEXT_BLOCK() also creates an implicit jump
1625 from the current block to the new block.
1626*/
1627
1628/* XXX The returns inside these macros make it impossible to decref
1629 objects created in the local function.
1630*/
1631
1632
1633#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001634 if (compiler_use_new_block((C)) == NULL) \
1635 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636}
1637
1638#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001639 if (compiler_next_block((C)) == NULL) \
1640 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641}
1642
1643#define ADDOP(C, OP) { \
1644 if (!compiler_addop((C), (OP))) \
1645 return 0; \
1646}
1647
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001648#define ADDOP_IN_SCOPE(C, OP) { \
1649 if (!compiler_addop((C), (OP))) { \
1650 compiler_exit_scope(c); \
1651 return 0; \
1652 } \
1653}
1654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655#define ADDOP_O(C, OP, O, TYPE) { \
1656 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1657 return 0; \
1658}
1659
1660#define ADDOP_NAME(C, OP, O, TYPE) { \
1661 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1662 return 0; \
1663}
1664
1665#define ADDOP_I(C, OP, O) { \
1666 if (!compiler_addop_i((C), (OP), (O))) \
1667 return 0; \
1668}
1669
1670#define ADDOP_JABS(C, OP, O) { \
1671 if (!compiler_addop_j((C), (OP), (O), 1)) \
1672 return 0; \
1673}
1674
1675#define ADDOP_JREL(C, OP, O) { \
1676 if (!compiler_addop_j((C), (OP), (O), 0)) \
1677 return 0; \
1678}
1679
1680/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1681 the ASDL name to synthesize the name of the C type and the visit function.
1682*/
1683
1684#define VISIT(C, TYPE, V) {\
1685 if (!compiler_visit_ ## TYPE((C), (V))) \
1686 return 0; \
1687}
1688
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001689#define VISIT_IN_SCOPE(C, TYPE, V) {\
1690 if (!compiler_visit_ ## TYPE((C), (V))) { \
1691 compiler_exit_scope(c); \
1692 return 0; \
1693 } \
1694}
1695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696#define VISIT_SLICE(C, V, CTX) {\
1697 if (!compiler_visit_slice((C), (V), (CTX))) \
1698 return 0; \
1699}
1700
1701#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001702 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001704 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1705 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 if (!compiler_visit_ ## TYPE((C), elt)) \
1707 return 0; \
1708 } \
1709}
1710
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001711#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001712 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001713 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001714 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1715 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001716 if (!compiler_visit_ ## TYPE((C), elt)) { \
1717 compiler_exit_scope(c); \
1718 return 0; \
1719 } \
1720 } \
1721}
1722
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723static int
1724compiler_isdocstring(stmt_ty s)
1725{
1726 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001727 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001728 return s->v.Expr.value->kind == Str_kind;
1729}
1730
1731/* Compile a sequence of statements, checking for a docstring. */
1732
1733static int
1734compiler_body(struct compiler *c, asdl_seq *stmts)
1735{
1736 int i = 0;
1737 stmt_ty st;
1738
1739 if (!asdl_seq_LEN(stmts))
1740 return 1;
1741 st = asdl_seq_GET(stmts, 0);
1742 if (compiler_isdocstring(st)) {
1743 i = 1;
1744 VISIT(c, expr, st->v.Expr.value);
1745 if (!compiler_nameop(c, __doc__, Store))
1746 return 0;
1747 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001748 for (; i < asdl_seq_LEN(stmts); i++)
1749 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750 return 1;
1751}
1752
1753static PyCodeObject *
1754compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001755{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001756 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001757 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758 static PyObject *module;
1759 if (!module) {
1760 module = PyString_FromString("<module>");
1761 if (!module)
1762 return NULL;
1763 }
1764 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001765 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 switch (mod->kind) {
1767 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001768 if (!compiler_body(c, mod->v.Module.body)) {
1769 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001771 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 break;
1773 case Interactive_kind:
1774 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001775 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 break;
1777 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001778 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001779 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 break;
1781 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001782 PyErr_SetString(PyExc_SystemError,
1783 "suite should not be possible");
1784 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001785 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001786 PyErr_Format(PyExc_SystemError,
1787 "module kind %d should not be possible",
1788 mod->kind);
1789 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 co = assemble(c, addNone);
1792 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001793 return co;
1794}
1795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796/* The test for LOCAL must come before the test for FREE in order to
1797 handle classes where name is both local and free. The local var is
1798 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001799*/
1800
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801static int
1802get_ref_type(struct compiler *c, PyObject *name)
1803{
1804 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001805 if (scope == 0) {
1806 char buf[350];
1807 PyOS_snprintf(buf, sizeof(buf),
1808 "unknown scope for %.100s in %.100s(%s) in %s\n"
1809 "symbols: %s\nlocals: %s\nglobals: %s\n",
1810 PyString_AS_STRING(name),
1811 PyString_AS_STRING(c->u->u_name),
1812 PyObject_REPR(c->u->u_ste->ste_id),
1813 c->c_filename,
1814 PyObject_REPR(c->u->u_ste->ste_symbols),
1815 PyObject_REPR(c->u->u_varnames),
1816 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001818 Py_FatalError(buf);
1819 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001820
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001821 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822}
1823
1824static int
1825compiler_lookup_arg(PyObject *dict, PyObject *name)
1826{
1827 PyObject *k, *v;
1828 k = Py_BuildValue("(OO)", name, name->ob_type);
1829 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001830 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001832 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001834 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835 return PyInt_AS_LONG(v);
1836}
1837
1838static int
1839compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1840{
1841 int i, free = PyCode_GetNumFree(co);
1842 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001843 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1844 ADDOP_I(c, MAKE_FUNCTION, args);
1845 return 1;
1846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 for (i = 0; i < free; ++i) {
1848 /* Bypass com_addop_varname because it will generate
1849 LOAD_DEREF but LOAD_CLOSURE is needed.
1850 */
1851 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1852 int arg, reftype;
1853
1854 /* Special case: If a class contains a method with a
1855 free variable that has the same name as a method,
1856 the name will be considered free *and* local in the
1857 class. It should be handled by the closure, as
1858 well as by the normal name loookup logic.
1859 */
1860 reftype = get_ref_type(c, name);
1861 if (reftype == CELL)
1862 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1863 else /* (reftype == FREE) */
1864 arg = compiler_lookup_arg(c->u->u_freevars, name);
1865 if (arg == -1) {
1866 printf("lookup %s in %s %d %d\n"
1867 "freevars of %s: %s\n",
1868 PyObject_REPR(name),
1869 PyString_AS_STRING(c->u->u_name),
1870 reftype, arg,
1871 PyString_AS_STRING(co->co_name),
1872 PyObject_REPR(co->co_freevars));
1873 Py_FatalError("compiler_make_closure()");
1874 }
1875 ADDOP_I(c, LOAD_CLOSURE, arg);
1876 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001877 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001879 ADDOP_I(c, MAKE_CLOSURE, args);
1880 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881}
1882
1883static int
1884compiler_decorators(struct compiler *c, asdl_seq* decos)
1885{
1886 int i;
1887
1888 if (!decos)
1889 return 1;
1890
1891 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1892 VISIT(c, expr, asdl_seq_GET(decos, i));
1893 }
1894 return 1;
1895}
1896
1897static int
1898compiler_arguments(struct compiler *c, arguments_ty args)
1899{
1900 int i;
1901 int n = asdl_seq_LEN(args->args);
1902 /* Correctly handle nested argument lists */
1903 for (i = 0; i < n; i++) {
1904 expr_ty arg = asdl_seq_GET(args->args, i);
1905 if (arg->kind == Tuple_kind) {
1906 PyObject *id = PyString_FromFormat(".%d", i);
1907 if (id == NULL) {
1908 return 0;
1909 }
1910 if (!compiler_nameop(c, id, Load)) {
1911 Py_DECREF(id);
1912 return 0;
1913 }
1914 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001915 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 }
1917 }
1918 return 1;
1919}
1920
1921static int
1922compiler_function(struct compiler *c, stmt_ty s)
1923{
1924 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001925 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 arguments_ty args = s->v.FunctionDef.args;
1927 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001928 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 int i, n, docstring;
1930
1931 assert(s->kind == FunctionDef_kind);
1932
1933 if (!compiler_decorators(c, decos))
1934 return 0;
1935 if (args->defaults)
1936 VISIT_SEQ(c, expr, args->defaults);
1937 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1938 s->lineno))
1939 return 0;
1940
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001941 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1942 docstring = compiler_isdocstring(st);
1943 if (docstring)
1944 first_const = st->v.Expr.value->v.Str.s;
1945 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001946 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001947 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001948 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001950 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 compiler_arguments(c, args);
1952
1953 c->u->u_argcount = asdl_seq_LEN(args->args);
1954 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001955 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 for (i = docstring; i < n; i++) {
1957 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1958 if (i == 0 && s2->kind == Expr_kind &&
1959 s2->v.Expr.value->kind == Str_kind)
1960 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001961 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 }
1963 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001964 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 if (co == NULL)
1966 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001968 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001969 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970
1971 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1972 ADDOP_I(c, CALL_FUNCTION, 1);
1973 }
1974
1975 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1976}
1977
1978static int
1979compiler_class(struct compiler *c, stmt_ty s)
1980{
1981 int n;
1982 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001983 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 /* push class name on stack, needed by BUILD_CLASS */
1985 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1986 /* push the tuple of base classes on the stack */
1987 n = asdl_seq_LEN(s->v.ClassDef.bases);
1988 if (n > 0)
1989 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1990 ADDOP_I(c, BUILD_TUPLE, n);
1991 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1992 s->lineno))
1993 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001994 c->u->u_private = s->v.ClassDef.name;
1995 Py_INCREF(c->u->u_private);
1996 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 if (!str || !compiler_nameop(c, str, Load)) {
1998 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001999 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002001 }
2002
2003 Py_DECREF(str);
2004 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 if (!str || !compiler_nameop(c, str, Store)) {
2006 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002007 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002009 }
2010 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002012 if (!compiler_body(c, s->v.ClassDef.body)) {
2013 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002015 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002017 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2018 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002020 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 if (co == NULL)
2022 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002024 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002025 Py_DECREF(co);
2026
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 ADDOP_I(c, CALL_FUNCTION, 0);
2028 ADDOP(c, BUILD_CLASS);
2029 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2030 return 0;
2031 return 1;
2032}
2033
2034static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002035compiler_ifexp(struct compiler *c, expr_ty e)
2036{
2037 basicblock *end, *next;
2038
2039 assert(e->kind == IfExp_kind);
2040 end = compiler_new_block(c);
2041 if (end == NULL)
2042 return 0;
2043 next = compiler_new_block(c);
2044 if (next == NULL)
2045 return 0;
2046 VISIT(c, expr, e->v.IfExp.test);
2047 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2048 ADDOP(c, POP_TOP);
2049 VISIT(c, expr, e->v.IfExp.body);
2050 ADDOP_JREL(c, JUMP_FORWARD, end);
2051 compiler_use_next_block(c, next);
2052 ADDOP(c, POP_TOP);
2053 VISIT(c, expr, e->v.IfExp.orelse);
2054 compiler_use_next_block(c, end);
2055 return 1;
2056}
2057
2058static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059compiler_lambda(struct compiler *c, expr_ty e)
2060{
2061 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002062 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 arguments_ty args = e->v.Lambda.args;
2064 assert(e->kind == Lambda_kind);
2065
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002066 if (!name) {
2067 name = PyString_InternFromString("<lambda>");
2068 if (!name)
2069 return 0;
2070 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071
2072 if (args->defaults)
2073 VISIT_SEQ(c, expr, args->defaults);
2074 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2075 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002076
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 compiler_arguments(c, args);
2079
2080 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002081 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2082 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002084 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 if (co == NULL)
2086 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002089 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090
2091 return 1;
2092}
2093
2094static int
2095compiler_print(struct compiler *c, stmt_ty s)
2096{
2097 int i, n;
2098 bool dest;
2099
2100 assert(s->kind == Print_kind);
2101 n = asdl_seq_LEN(s->v.Print.values);
2102 dest = false;
2103 if (s->v.Print.dest) {
2104 VISIT(c, expr, s->v.Print.dest);
2105 dest = true;
2106 }
2107 for (i = 0; i < n; i++) {
2108 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2109 if (dest) {
2110 ADDOP(c, DUP_TOP);
2111 VISIT(c, expr, e);
2112 ADDOP(c, ROT_TWO);
2113 ADDOP(c, PRINT_ITEM_TO);
2114 }
2115 else {
2116 VISIT(c, expr, e);
2117 ADDOP(c, PRINT_ITEM);
2118 }
2119 }
2120 if (s->v.Print.nl) {
2121 if (dest)
2122 ADDOP(c, PRINT_NEWLINE_TO)
2123 else
2124 ADDOP(c, PRINT_NEWLINE)
2125 }
2126 else if (dest)
2127 ADDOP(c, POP_TOP);
2128 return 1;
2129}
2130
2131static int
2132compiler_if(struct compiler *c, stmt_ty s)
2133{
2134 basicblock *end, *next;
2135
2136 assert(s->kind == If_kind);
2137 end = compiler_new_block(c);
2138 if (end == NULL)
2139 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 next = compiler_new_block(c);
2141 if (next == NULL)
2142 return 0;
2143 VISIT(c, expr, s->v.If.test);
2144 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2145 ADDOP(c, POP_TOP);
2146 VISIT_SEQ(c, stmt, s->v.If.body);
2147 ADDOP_JREL(c, JUMP_FORWARD, end);
2148 compiler_use_next_block(c, next);
2149 ADDOP(c, POP_TOP);
2150 if (s->v.If.orelse)
2151 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 compiler_use_next_block(c, end);
2153 return 1;
2154}
2155
2156static int
2157compiler_for(struct compiler *c, stmt_ty s)
2158{
2159 basicblock *start, *cleanup, *end;
2160
2161 start = compiler_new_block(c);
2162 cleanup = compiler_new_block(c);
2163 end = compiler_new_block(c);
2164 if (start == NULL || end == NULL || cleanup == NULL)
2165 return 0;
2166 ADDOP_JREL(c, SETUP_LOOP, end);
2167 if (!compiler_push_fblock(c, LOOP, start))
2168 return 0;
2169 VISIT(c, expr, s->v.For.iter);
2170 ADDOP(c, GET_ITER);
2171 compiler_use_next_block(c, start);
2172 ADDOP_JREL(c, FOR_ITER, cleanup);
2173 VISIT(c, expr, s->v.For.target);
2174 VISIT_SEQ(c, stmt, s->v.For.body);
2175 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2176 compiler_use_next_block(c, cleanup);
2177 ADDOP(c, POP_BLOCK);
2178 compiler_pop_fblock(c, LOOP, start);
2179 VISIT_SEQ(c, stmt, s->v.For.orelse);
2180 compiler_use_next_block(c, end);
2181 return 1;
2182}
2183
2184static int
2185compiler_while(struct compiler *c, stmt_ty s)
2186{
2187 basicblock *loop, *orelse, *end, *anchor = NULL;
2188 int constant = expr_constant(s->v.While.test);
2189
2190 if (constant == 0)
2191 return 1;
2192 loop = compiler_new_block(c);
2193 end = compiler_new_block(c);
2194 if (constant == -1) {
2195 anchor = compiler_new_block(c);
2196 if (anchor == NULL)
2197 return 0;
2198 }
2199 if (loop == NULL || end == NULL)
2200 return 0;
2201 if (s->v.While.orelse) {
2202 orelse = compiler_new_block(c);
2203 if (orelse == NULL)
2204 return 0;
2205 }
2206 else
2207 orelse = NULL;
2208
2209 ADDOP_JREL(c, SETUP_LOOP, end);
2210 compiler_use_next_block(c, loop);
2211 if (!compiler_push_fblock(c, LOOP, loop))
2212 return 0;
2213 if (constant == -1) {
2214 VISIT(c, expr, s->v.While.test);
2215 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2216 ADDOP(c, POP_TOP);
2217 }
2218 VISIT_SEQ(c, stmt, s->v.While.body);
2219 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2220
2221 /* XXX should the two POP instructions be in a separate block
2222 if there is no else clause ?
2223 */
2224
2225 if (constant == -1) {
2226 compiler_use_next_block(c, anchor);
2227 ADDOP(c, POP_TOP);
2228 ADDOP(c, POP_BLOCK);
2229 }
2230 compiler_pop_fblock(c, LOOP, loop);
2231 if (orelse != NULL)
2232 VISIT_SEQ(c, stmt, s->v.While.orelse);
2233 compiler_use_next_block(c, end);
2234
2235 return 1;
2236}
2237
2238static int
2239compiler_continue(struct compiler *c)
2240{
2241 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2242 int i;
2243
2244 if (!c->u->u_nfblocks)
2245 return compiler_error(c, LOOP_ERROR_MSG);
2246 i = c->u->u_nfblocks - 1;
2247 switch (c->u->u_fblock[i].fb_type) {
2248 case LOOP:
2249 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2250 break;
2251 case EXCEPT:
2252 case FINALLY_TRY:
2253 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2254 ;
2255 if (i == -1)
2256 return compiler_error(c, LOOP_ERROR_MSG);
2257 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2258 break;
2259 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002260 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 "'continue' not supported inside 'finally' clause");
2262 }
2263
2264 return 1;
2265}
2266
2267/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2268
2269 SETUP_FINALLY L
2270 <code for body>
2271 POP_BLOCK
2272 LOAD_CONST <None>
2273 L: <code for finalbody>
2274 END_FINALLY
2275
2276 The special instructions use the block stack. Each block
2277 stack entry contains the instruction that created it (here
2278 SETUP_FINALLY), the level of the value stack at the time the
2279 block stack entry was created, and a label (here L).
2280
2281 SETUP_FINALLY:
2282 Pushes the current value stack level and the label
2283 onto the block stack.
2284 POP_BLOCK:
2285 Pops en entry from the block stack, and pops the value
2286 stack until its level is the same as indicated on the
2287 block stack. (The label is ignored.)
2288 END_FINALLY:
2289 Pops a variable number of entries from the *value* stack
2290 and re-raises the exception they specify. The number of
2291 entries popped depends on the (pseudo) exception type.
2292
2293 The block stack is unwound when an exception is raised:
2294 when a SETUP_FINALLY entry is found, the exception is pushed
2295 onto the value stack (and the exception condition is cleared),
2296 and the interpreter jumps to the label gotten from the block
2297 stack.
2298*/
2299
2300static int
2301compiler_try_finally(struct compiler *c, stmt_ty s)
2302{
2303 basicblock *body, *end;
2304 body = compiler_new_block(c);
2305 end = compiler_new_block(c);
2306 if (body == NULL || end == NULL)
2307 return 0;
2308
2309 ADDOP_JREL(c, SETUP_FINALLY, end);
2310 compiler_use_next_block(c, body);
2311 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2312 return 0;
2313 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2314 ADDOP(c, POP_BLOCK);
2315 compiler_pop_fblock(c, FINALLY_TRY, body);
2316
2317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2318 compiler_use_next_block(c, end);
2319 if (!compiler_push_fblock(c, FINALLY_END, end))
2320 return 0;
2321 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2322 ADDOP(c, END_FINALLY);
2323 compiler_pop_fblock(c, FINALLY_END, end);
2324
2325 return 1;
2326}
2327
2328/*
2329 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2330 (The contents of the value stack is shown in [], with the top
2331 at the right; 'tb' is trace-back info, 'val' the exception's
2332 associated value, and 'exc' the exception.)
2333
2334 Value stack Label Instruction Argument
2335 [] SETUP_EXCEPT L1
2336 [] <code for S>
2337 [] POP_BLOCK
2338 [] JUMP_FORWARD L0
2339
2340 [tb, val, exc] L1: DUP )
2341 [tb, val, exc, exc] <evaluate E1> )
2342 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2343 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2344 [tb, val, exc, 1] POP )
2345 [tb, val, exc] POP
2346 [tb, val] <assign to V1> (or POP if no V1)
2347 [tb] POP
2348 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002349 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350
2351 [tb, val, exc, 0] L2: POP
2352 [tb, val, exc] DUP
2353 .............................etc.......................
2354
2355 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002356 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357
2358 [] L0: <next statement>
2359
2360 Of course, parts are not generated if Vi or Ei is not present.
2361*/
2362static int
2363compiler_try_except(struct compiler *c, stmt_ty s)
2364{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002365 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366 int i, n;
2367
2368 body = compiler_new_block(c);
2369 except = compiler_new_block(c);
2370 orelse = compiler_new_block(c);
2371 end = compiler_new_block(c);
2372 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2373 return 0;
2374 ADDOP_JREL(c, SETUP_EXCEPT, except);
2375 compiler_use_next_block(c, body);
2376 if (!compiler_push_fblock(c, EXCEPT, body))
2377 return 0;
2378 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2379 ADDOP(c, POP_BLOCK);
2380 compiler_pop_fblock(c, EXCEPT, body);
2381 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2382 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2383 compiler_use_next_block(c, except);
2384 for (i = 0; i < n; i++) {
2385 excepthandler_ty handler = asdl_seq_GET(
2386 s->v.TryExcept.handlers, i);
2387 if (!handler->type && i < n-1)
2388 return compiler_error(c, "default 'except:' must be last");
2389 except = compiler_new_block(c);
2390 if (except == NULL)
2391 return 0;
2392 if (handler->type) {
2393 ADDOP(c, DUP_TOP);
2394 VISIT(c, expr, handler->type);
2395 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2396 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2397 ADDOP(c, POP_TOP);
2398 }
2399 ADDOP(c, POP_TOP);
2400 if (handler->name) {
2401 VISIT(c, expr, handler->name);
2402 }
2403 else {
2404 ADDOP(c, POP_TOP);
2405 }
2406 ADDOP(c, POP_TOP);
2407 VISIT_SEQ(c, stmt, handler->body);
2408 ADDOP_JREL(c, JUMP_FORWARD, end);
2409 compiler_use_next_block(c, except);
2410 if (handler->type)
2411 ADDOP(c, POP_TOP);
2412 }
2413 ADDOP(c, END_FINALLY);
2414 compiler_use_next_block(c, orelse);
2415 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2416 compiler_use_next_block(c, end);
2417 return 1;
2418}
2419
2420static int
2421compiler_import_as(struct compiler *c, identifier name, identifier asname)
2422{
2423 /* The IMPORT_NAME opcode was already generated. This function
2424 merely needs to bind the result to a name.
2425
2426 If there is a dot in name, we need to split it and emit a
2427 LOAD_ATTR for each name.
2428 */
2429 const char *src = PyString_AS_STRING(name);
2430 const char *dot = strchr(src, '.');
2431 if (dot) {
2432 /* Consume the base module name to get the first attribute */
2433 src = dot + 1;
2434 while (dot) {
2435 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002436 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002438 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002440 if (!attr)
2441 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002443 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 src = dot + 1;
2445 }
2446 }
2447 return compiler_nameop(c, asname, Store);
2448}
2449
2450static int
2451compiler_import(struct compiler *c, stmt_ty s)
2452{
2453 /* The Import node stores a module name like a.b.c as a single
2454 string. This is convenient for all cases except
2455 import a.b.c as d
2456 where we need to parse that string to extract the individual
2457 module names.
2458 XXX Perhaps change the representation to make this case simpler?
2459 */
2460 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 for (i = 0; i < n; i++) {
2463 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2464 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002465 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002467 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2468 level = PyInt_FromLong(0);
2469 else
2470 level = PyInt_FromLong(-1);
2471
2472 if (level == NULL)
2473 return 0;
2474
2475 ADDOP_O(c, LOAD_CONST, level, consts);
2476 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2478 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2479
2480 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002481 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002482 if (!r)
2483 return r;
2484 }
2485 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 identifier tmp = alias->name;
2487 const char *base = PyString_AS_STRING(alias->name);
2488 char *dot = strchr(base, '.');
2489 if (dot)
2490 tmp = PyString_FromStringAndSize(base,
2491 dot - base);
2492 r = compiler_nameop(c, tmp, Store);
2493 if (dot) {
2494 Py_DECREF(tmp);
2495 }
2496 if (!r)
2497 return r;
2498 }
2499 }
2500 return 1;
2501}
2502
2503static int
2504compiler_from_import(struct compiler *c, stmt_ty s)
2505{
2506 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
2508 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002509 PyObject *level;
2510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 if (!names)
2512 return 0;
2513
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002514 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2515 !(c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2516 level = PyInt_FromLong(-1);
2517 else
2518 level = PyInt_FromLong(s->v.ImportFrom.level);
2519
2520 if (!level) {
2521 Py_DECREF(names);
2522 return 0;
2523 }
2524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 /* build up the names */
2526 for (i = 0; i < n; i++) {
2527 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2528 Py_INCREF(alias->name);
2529 PyTuple_SET_ITEM(names, i, alias->name);
2530 }
2531
2532 if (s->lineno > c->c_future->ff_lineno) {
2533 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2534 "__future__")) {
2535 Py_DECREF(names);
2536 return compiler_error(c,
2537 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002538 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539
2540 }
2541 }
2542
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002543 ADDOP_O(c, LOAD_CONST, level, consts);
2544 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002546 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2548 for (i = 0; i < n; i++) {
2549 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2550 identifier store_name;
2551
2552 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2553 assert(n == 1);
2554 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002555 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556 }
2557
2558 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2559 store_name = alias->name;
2560 if (alias->asname)
2561 store_name = alias->asname;
2562
2563 if (!compiler_nameop(c, store_name, Store)) {
2564 Py_DECREF(names);
2565 return 0;
2566 }
2567 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002568 /* remove imported module */
2569 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002570 return 1;
2571}
2572
2573static int
2574compiler_assert(struct compiler *c, stmt_ty s)
2575{
2576 static PyObject *assertion_error = NULL;
2577 basicblock *end;
2578
2579 if (Py_OptimizeFlag)
2580 return 1;
2581 if (assertion_error == NULL) {
2582 assertion_error = PyString_FromString("AssertionError");
2583 if (assertion_error == NULL)
2584 return 0;
2585 }
2586 VISIT(c, expr, s->v.Assert.test);
2587 end = compiler_new_block(c);
2588 if (end == NULL)
2589 return 0;
2590 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2591 ADDOP(c, POP_TOP);
2592 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2593 if (s->v.Assert.msg) {
2594 VISIT(c, expr, s->v.Assert.msg);
2595 ADDOP_I(c, RAISE_VARARGS, 2);
2596 }
2597 else {
2598 ADDOP_I(c, RAISE_VARARGS, 1);
2599 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002600 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 ADDOP(c, POP_TOP);
2602 return 1;
2603}
2604
2605static int
2606compiler_visit_stmt(struct compiler *c, stmt_ty s)
2607{
2608 int i, n;
2609
2610 c->u->u_lineno = s->lineno;
2611 c->u->u_lineno_set = false;
2612 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002613 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002615 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 if (c->u->u_ste->ste_type != FunctionBlock)
2619 return compiler_error(c, "'return' outside function");
2620 if (s->v.Return.value) {
2621 if (c->u->u_ste->ste_generator) {
2622 return compiler_error(c,
2623 "'return' with argument inside generator");
2624 }
2625 VISIT(c, expr, s->v.Return.value);
2626 }
2627 else
2628 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2629 ADDOP(c, RETURN_VALUE);
2630 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002631 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 VISIT_SEQ(c, expr, s->v.Delete.targets)
2633 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 n = asdl_seq_LEN(s->v.Assign.targets);
2636 VISIT(c, expr, s->v.Assign.value);
2637 for (i = 0; i < n; i++) {
2638 if (i < n - 1)
2639 ADDOP(c, DUP_TOP);
2640 VISIT(c, expr,
2641 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2642 }
2643 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002646 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002648 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002650 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002654 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 n = 0;
2656 if (s->v.Raise.type) {
2657 VISIT(c, expr, s->v.Raise.type);
2658 n++;
2659 if (s->v.Raise.inst) {
2660 VISIT(c, expr, s->v.Raise.inst);
2661 n++;
2662 if (s->v.Raise.tback) {
2663 VISIT(c, expr, s->v.Raise.tback);
2664 n++;
2665 }
2666 }
2667 }
2668 ADDOP_I(c, RAISE_VARARGS, n);
2669 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002670 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002672 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002676 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 VISIT(c, expr, s->v.Exec.body);
2682 if (s->v.Exec.globals) {
2683 VISIT(c, expr, s->v.Exec.globals);
2684 if (s->v.Exec.locals) {
2685 VISIT(c, expr, s->v.Exec.locals);
2686 } else {
2687 ADDOP(c, DUP_TOP);
2688 }
2689 } else {
2690 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2691 ADDOP(c, DUP_TOP);
2692 }
2693 ADDOP(c, EXEC_STMT);
2694 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002697 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698 VISIT(c, expr, s->v.Expr.value);
2699 if (c->c_interactive && c->c_nestlevel <= 1) {
2700 ADDOP(c, PRINT_EXPR);
2701 }
2702 else {
2703 ADDOP(c, POP_TOP);
2704 }
2705 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 if (!c->u->u_nfblocks)
2710 return compiler_error(c, "'break' outside loop");
2711 ADDOP(c, BREAK_LOOP);
2712 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 case With_kind:
2716 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 }
2718 return 1;
2719}
2720
2721static int
2722unaryop(unaryop_ty op)
2723{
2724 switch (op) {
2725 case Invert:
2726 return UNARY_INVERT;
2727 case Not:
2728 return UNARY_NOT;
2729 case UAdd:
2730 return UNARY_POSITIVE;
2731 case USub:
2732 return UNARY_NEGATIVE;
2733 }
2734 return 0;
2735}
2736
2737static int
2738binop(struct compiler *c, operator_ty op)
2739{
2740 switch (op) {
2741 case Add:
2742 return BINARY_ADD;
2743 case Sub:
2744 return BINARY_SUBTRACT;
2745 case Mult:
2746 return BINARY_MULTIPLY;
2747 case Div:
2748 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2749 return BINARY_TRUE_DIVIDE;
2750 else
2751 return BINARY_DIVIDE;
2752 case Mod:
2753 return BINARY_MODULO;
2754 case Pow:
2755 return BINARY_POWER;
2756 case LShift:
2757 return BINARY_LSHIFT;
2758 case RShift:
2759 return BINARY_RSHIFT;
2760 case BitOr:
2761 return BINARY_OR;
2762 case BitXor:
2763 return BINARY_XOR;
2764 case BitAnd:
2765 return BINARY_AND;
2766 case FloorDiv:
2767 return BINARY_FLOOR_DIVIDE;
2768 }
2769 return 0;
2770}
2771
2772static int
2773cmpop(cmpop_ty op)
2774{
2775 switch (op) {
2776 case Eq:
2777 return PyCmp_EQ;
2778 case NotEq:
2779 return PyCmp_NE;
2780 case Lt:
2781 return PyCmp_LT;
2782 case LtE:
2783 return PyCmp_LE;
2784 case Gt:
2785 return PyCmp_GT;
2786 case GtE:
2787 return PyCmp_GE;
2788 case Is:
2789 return PyCmp_IS;
2790 case IsNot:
2791 return PyCmp_IS_NOT;
2792 case In:
2793 return PyCmp_IN;
2794 case NotIn:
2795 return PyCmp_NOT_IN;
2796 }
2797 return PyCmp_BAD;
2798}
2799
2800static int
2801inplace_binop(struct compiler *c, operator_ty op)
2802{
2803 switch (op) {
2804 case Add:
2805 return INPLACE_ADD;
2806 case Sub:
2807 return INPLACE_SUBTRACT;
2808 case Mult:
2809 return INPLACE_MULTIPLY;
2810 case Div:
2811 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2812 return INPLACE_TRUE_DIVIDE;
2813 else
2814 return INPLACE_DIVIDE;
2815 case Mod:
2816 return INPLACE_MODULO;
2817 case Pow:
2818 return INPLACE_POWER;
2819 case LShift:
2820 return INPLACE_LSHIFT;
2821 case RShift:
2822 return INPLACE_RSHIFT;
2823 case BitOr:
2824 return INPLACE_OR;
2825 case BitXor:
2826 return INPLACE_XOR;
2827 case BitAnd:
2828 return INPLACE_AND;
2829 case FloorDiv:
2830 return INPLACE_FLOOR_DIVIDE;
2831 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002832 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002833 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834 return 0;
2835}
2836
2837static int
2838compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2839{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002840 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2842
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002843 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002844 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845 /* XXX AugStore isn't used anywhere! */
2846
2847 /* First check for assignment to __debug__. Param? */
2848 if ((ctx == Store || ctx == AugStore || ctx == Del)
2849 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2850 return compiler_error(c, "can not assign to __debug__");
2851 }
2852
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002853 mangled = _Py_Mangle(c->u->u_private, name);
2854 if (!mangled)
2855 return 0;
2856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857 op = 0;
2858 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002859 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860 switch (scope) {
2861 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002862 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863 optype = OP_DEREF;
2864 break;
2865 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002866 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 optype = OP_DEREF;
2868 break;
2869 case LOCAL:
2870 if (c->u->u_ste->ste_type == FunctionBlock)
2871 optype = OP_FAST;
2872 break;
2873 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002874 if (c->u->u_ste->ste_type == FunctionBlock &&
2875 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876 optype = OP_GLOBAL;
2877 break;
2878 case GLOBAL_EXPLICIT:
2879 optype = OP_GLOBAL;
2880 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002881 default:
2882 /* scope can be 0 */
2883 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 }
2885
2886 /* XXX Leave assert here, but handle __doc__ and the like better */
2887 assert(scope || PyString_AS_STRING(name)[0] == '_');
2888
2889 switch (optype) {
2890 case OP_DEREF:
2891 switch (ctx) {
2892 case Load: op = LOAD_DEREF; break;
2893 case Store: op = STORE_DEREF; break;
2894 case AugLoad:
2895 case AugStore:
2896 break;
2897 case Del:
2898 PyErr_Format(PyExc_SyntaxError,
2899 "can not delete variable '%s' referenced "
2900 "in nested scope",
2901 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002902 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002905 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002906 PyErr_SetString(PyExc_SystemError,
2907 "param invalid for deref variable");
2908 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002909 }
2910 break;
2911 case OP_FAST:
2912 switch (ctx) {
2913 case Load: op = LOAD_FAST; break;
2914 case Store: op = STORE_FAST; break;
2915 case Del: op = DELETE_FAST; break;
2916 case AugLoad:
2917 case AugStore:
2918 break;
2919 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 local variable");
2923 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002925 ADDOP_O(c, op, mangled, varnames);
2926 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 return 1;
2928 case OP_GLOBAL:
2929 switch (ctx) {
2930 case Load: op = LOAD_GLOBAL; break;
2931 case Store: op = STORE_GLOBAL; break;
2932 case Del: op = DELETE_GLOBAL; break;
2933 case AugLoad:
2934 case AugStore:
2935 break;
2936 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002937 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002938 PyErr_SetString(PyExc_SystemError,
2939 "param invalid for global variable");
2940 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 }
2942 break;
2943 case OP_NAME:
2944 switch (ctx) {
2945 case Load: op = LOAD_NAME; break;
2946 case Store: op = STORE_NAME; break;
2947 case Del: op = DELETE_NAME; 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 name variable");
2955 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 }
2957 break;
2958 }
2959
2960 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002961 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002962 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002963 if (arg < 0)
2964 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002965 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966}
2967
2968static int
2969compiler_boolop(struct compiler *c, expr_ty e)
2970{
2971 basicblock *end;
2972 int jumpi, i, n;
2973 asdl_seq *s;
2974
2975 assert(e->kind == BoolOp_kind);
2976 if (e->v.BoolOp.op == And)
2977 jumpi = JUMP_IF_FALSE;
2978 else
2979 jumpi = JUMP_IF_TRUE;
2980 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002981 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 return 0;
2983 s = e->v.BoolOp.values;
2984 n = asdl_seq_LEN(s) - 1;
2985 for (i = 0; i < n; ++i) {
2986 VISIT(c, expr, asdl_seq_GET(s, i));
2987 ADDOP_JREL(c, jumpi, end);
2988 ADDOP(c, POP_TOP)
2989 }
2990 VISIT(c, expr, asdl_seq_GET(s, n));
2991 compiler_use_next_block(c, end);
2992 return 1;
2993}
2994
2995static int
2996compiler_list(struct compiler *c, expr_ty e)
2997{
2998 int n = asdl_seq_LEN(e->v.List.elts);
2999 if (e->v.List.ctx == Store) {
3000 ADDOP_I(c, UNPACK_SEQUENCE, n);
3001 }
3002 VISIT_SEQ(c, expr, e->v.List.elts);
3003 if (e->v.List.ctx == Load) {
3004 ADDOP_I(c, BUILD_LIST, n);
3005 }
3006 return 1;
3007}
3008
3009static int
3010compiler_tuple(struct compiler *c, expr_ty e)
3011{
3012 int n = asdl_seq_LEN(e->v.Tuple.elts);
3013 if (e->v.Tuple.ctx == Store) {
3014 ADDOP_I(c, UNPACK_SEQUENCE, n);
3015 }
3016 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3017 if (e->v.Tuple.ctx == Load) {
3018 ADDOP_I(c, BUILD_TUPLE, n);
3019 }
3020 return 1;
3021}
3022
3023static int
3024compiler_compare(struct compiler *c, expr_ty e)
3025{
3026 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003027 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028
3029 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3030 VISIT(c, expr, e->v.Compare.left);
3031 n = asdl_seq_LEN(e->v.Compare.ops);
3032 assert(n > 0);
3033 if (n > 1) {
3034 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003035 if (cleanup == NULL)
3036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3038 }
3039 for (i = 1; i < n; i++) {
3040 ADDOP(c, DUP_TOP);
3041 ADDOP(c, ROT_THREE);
3042 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3043 ADDOP_I(c, COMPARE_OP,
3044 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3045 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3046 NEXT_BLOCK(c);
3047 ADDOP(c, POP_TOP);
3048 if (i < (n - 1))
3049 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3050 }
3051 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3052 ADDOP_I(c, COMPARE_OP,
3053 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3054 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3055 if (n > 1) {
3056 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 if (end == NULL)
3058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 ADDOP_JREL(c, JUMP_FORWARD, end);
3060 compiler_use_next_block(c, cleanup);
3061 ADDOP(c, ROT_TWO);
3062 ADDOP(c, POP_TOP);
3063 compiler_use_next_block(c, end);
3064 }
3065 return 1;
3066}
3067
3068static int
3069compiler_call(struct compiler *c, expr_ty e)
3070{
3071 int n, code = 0;
3072
3073 VISIT(c, expr, e->v.Call.func);
3074 n = asdl_seq_LEN(e->v.Call.args);
3075 VISIT_SEQ(c, expr, e->v.Call.args);
3076 if (e->v.Call.keywords) {
3077 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3078 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3079 }
3080 if (e->v.Call.starargs) {
3081 VISIT(c, expr, e->v.Call.starargs);
3082 code |= 1;
3083 }
3084 if (e->v.Call.kwargs) {
3085 VISIT(c, expr, e->v.Call.kwargs);
3086 code |= 2;
3087 }
3088 switch (code) {
3089 case 0:
3090 ADDOP_I(c, CALL_FUNCTION, n);
3091 break;
3092 case 1:
3093 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3094 break;
3095 case 2:
3096 ADDOP_I(c, CALL_FUNCTION_KW, n);
3097 break;
3098 case 3:
3099 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3100 break;
3101 }
3102 return 1;
3103}
3104
3105static int
3106compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003107 asdl_seq *generators, int gen_index,
3108 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003109{
3110 /* generate code for the iterator, then each of the ifs,
3111 and then write to the element */
3112
3113 comprehension_ty l;
3114 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003115 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003116
3117 start = compiler_new_block(c);
3118 skip = compiler_new_block(c);
3119 if_cleanup = compiler_new_block(c);
3120 anchor = compiler_new_block(c);
3121
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003122 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3123 anchor == NULL)
3124 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
3126 l = asdl_seq_GET(generators, gen_index);
3127 VISIT(c, expr, l->iter);
3128 ADDOP(c, GET_ITER);
3129 compiler_use_next_block(c, start);
3130 ADDOP_JREL(c, FOR_ITER, anchor);
3131 NEXT_BLOCK(c);
3132 VISIT(c, expr, l->target);
3133
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135 n = asdl_seq_LEN(l->ifs);
3136 for (i = 0; i < n; i++) {
3137 expr_ty e = asdl_seq_GET(l->ifs, i);
3138 VISIT(c, expr, e);
3139 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3140 NEXT_BLOCK(c);
3141 ADDOP(c, POP_TOP);
3142 }
3143
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003144 if (++gen_index < asdl_seq_LEN(generators))
3145 if (!compiler_listcomp_generator(c, tmpname,
3146 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003149 /* only append after the last for generator */
3150 if (gen_index >= asdl_seq_LEN(generators)) {
3151 if (!compiler_nameop(c, tmpname, Load))
3152 return 0;
3153 VISIT(c, expr, elt);
3154 ADDOP_I(c, CALL_FUNCTION, 1);
3155 ADDOP(c, POP_TOP);
3156
3157 compiler_use_next_block(c, skip);
3158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 for (i = 0; i < n; i++) {
3160 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 if (i == 0)
3162 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 ADDOP(c, POP_TOP);
3164 }
3165 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3166 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 return 0;
3171
3172 return 1;
3173}
3174
3175static int
3176compiler_listcomp(struct compiler *c, expr_ty e)
3177{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 static identifier append;
3181 asdl_seq *generators = e->v.ListComp.generators;
3182
3183 assert(e->kind == ListComp_kind);
3184 if (!append) {
3185 append = PyString_InternFromString("append");
3186 if (!append)
3187 return 0;
3188 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003189 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 if (!tmp)
3191 return 0;
3192 ADDOP_I(c, BUILD_LIST, 0);
3193 ADDOP(c, DUP_TOP);
3194 ADDOP_O(c, LOAD_ATTR, append, names);
3195 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3197 e->v.ListComp.elt);
3198 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 return rc;
3200}
3201
3202static int
3203compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003204 asdl_seq *generators, int gen_index,
3205 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206{
3207 /* generate code for the iterator, then each of the ifs,
3208 and then write to the element */
3209
3210 comprehension_ty ge;
3211 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003212 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213
3214 start = compiler_new_block(c);
3215 skip = compiler_new_block(c);
3216 if_cleanup = compiler_new_block(c);
3217 anchor = compiler_new_block(c);
3218 end = compiler_new_block(c);
3219
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003220 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 anchor == NULL || end == NULL)
3222 return 0;
3223
3224 ge = asdl_seq_GET(generators, gen_index);
3225 ADDOP_JREL(c, SETUP_LOOP, end);
3226 if (!compiler_push_fblock(c, LOOP, start))
3227 return 0;
3228
3229 if (gen_index == 0) {
3230 /* Receive outermost iter as an implicit argument */
3231 c->u->u_argcount = 1;
3232 ADDOP_I(c, LOAD_FAST, 0);
3233 }
3234 else {
3235 /* Sub-iter - calculate on the fly */
3236 VISIT(c, expr, ge->iter);
3237 ADDOP(c, GET_ITER);
3238 }
3239 compiler_use_next_block(c, start);
3240 ADDOP_JREL(c, FOR_ITER, anchor);
3241 NEXT_BLOCK(c);
3242 VISIT(c, expr, ge->target);
3243
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003244 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245 n = asdl_seq_LEN(ge->ifs);
3246 for (i = 0; i < n; i++) {
3247 expr_ty e = asdl_seq_GET(ge->ifs, i);
3248 VISIT(c, expr, e);
3249 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3250 NEXT_BLOCK(c);
3251 ADDOP(c, POP_TOP);
3252 }
3253
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003254 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3256 return 0;
3257
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003258 /* only append after the last 'for' generator */
3259 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 VISIT(c, expr, elt);
3261 ADDOP(c, YIELD_VALUE);
3262 ADDOP(c, POP_TOP);
3263
3264 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 for (i = 0; i < n; i++) {
3267 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003268 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269 compiler_use_next_block(c, if_cleanup);
3270
3271 ADDOP(c, POP_TOP);
3272 }
3273 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3274 compiler_use_next_block(c, anchor);
3275 ADDOP(c, POP_BLOCK);
3276 compiler_pop_fblock(c, LOOP, start);
3277 compiler_use_next_block(c, end);
3278
3279 return 1;
3280}
3281
3282static int
3283compiler_genexp(struct compiler *c, expr_ty e)
3284{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003285 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286 PyCodeObject *co;
3287 expr_ty outermost_iter = ((comprehension_ty)
3288 (asdl_seq_GET(e->v.GeneratorExp.generators,
3289 0)))->iter;
3290
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003291 if (!name) {
3292 name = PyString_FromString("<genexpr>");
3293 if (!name)
3294 return 0;
3295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296
3297 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3298 return 0;
3299 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3300 e->v.GeneratorExp.elt);
3301 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003302 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 if (co == NULL)
3304 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003306 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003307 Py_DECREF(co);
3308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309 VISIT(c, expr, outermost_iter);
3310 ADDOP(c, GET_ITER);
3311 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312
3313 return 1;
3314}
3315
3316static int
3317compiler_visit_keyword(struct compiler *c, keyword_ty k)
3318{
3319 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3320 VISIT(c, expr, k->value);
3321 return 1;
3322}
3323
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003324/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 whether they are true or false.
3326
3327 Return values: 1 for true, 0 for false, -1 for non-constant.
3328 */
3329
3330static int
3331expr_constant(expr_ty e)
3332{
3333 switch (e->kind) {
3334 case Num_kind:
3335 return PyObject_IsTrue(e->v.Num.n);
3336 case Str_kind:
3337 return PyObject_IsTrue(e->v.Str.s);
3338 default:
3339 return -1;
3340 }
3341}
3342
Guido van Rossumc2e20742006-02-27 22:32:47 +00003343/*
3344 Implements the with statement from PEP 343.
3345
3346 The semantics outlined in that PEP are as follows:
3347
3348 with EXPR as VAR:
3349 BLOCK
3350
3351 It is implemented roughly as:
3352
3353 context = (EXPR).__context__()
3354 exit = context.__exit__ # not calling it
3355 value = context.__enter__()
3356 try:
3357 VAR = value # if VAR present in the syntax
3358 BLOCK
3359 finally:
3360 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003361 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003362 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003363 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003364 exit(*exc)
3365 */
3366static int
3367compiler_with(struct compiler *c, stmt_ty s)
3368{
3369 static identifier context_attr, enter_attr, exit_attr;
3370 basicblock *block, *finally;
3371 identifier tmpexit, tmpvalue = NULL;
3372
3373 assert(s->kind == With_kind);
3374
3375 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003376 context_attr = PyString_InternFromString("__context__");
3377 if (!context_attr)
3378 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003379 }
3380 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 enter_attr = PyString_InternFromString("__enter__");
3382 if (!enter_attr)
3383 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003384 }
3385 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003386 exit_attr = PyString_InternFromString("__exit__");
3387 if (!exit_attr)
3388 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003389 }
3390
3391 block = compiler_new_block(c);
3392 finally = compiler_new_block(c);
3393 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003394 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003395
3396 /* Create a temporary variable to hold context.__exit__ */
3397 tmpexit = compiler_new_tmpname(c);
3398 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003400 PyArena_AddPyObject(c->c_arena, tmpexit);
3401
3402 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003403 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003404 We need to do this rather than preserving it on the stack
3405 because SETUP_FINALLY remembers the stack level.
3406 We need to do the assignment *inside* the try/finally
3407 so that context.__exit__() is called when the assignment
3408 fails. But we need to call context.__enter__() *before*
3409 the try/finally so that if it fails we won't call
3410 context.__exit__().
3411 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003413 if (tmpvalue == NULL)
3414 return 0;
3415 PyArena_AddPyObject(c->c_arena, tmpvalue);
3416 }
3417
3418 /* Evaluate (EXPR).__context__() */
3419 VISIT(c, expr, s->v.With.context_expr);
3420 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3421 ADDOP_I(c, CALL_FUNCTION, 0);
3422
3423 /* Squirrel away context.__exit__ */
3424 ADDOP(c, DUP_TOP);
3425 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3426 if (!compiler_nameop(c, tmpexit, Store))
3427 return 0;
3428
3429 /* Call context.__enter__() */
3430 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3431 ADDOP_I(c, CALL_FUNCTION, 0);
3432
3433 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003434 /* Store it in tmpvalue */
3435 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003436 return 0;
3437 }
3438 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003439 /* Discard result from context.__enter__() */
3440 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003441 }
3442
3443 /* Start the try block */
3444 ADDOP_JREL(c, SETUP_FINALLY, finally);
3445
3446 compiler_use_next_block(c, block);
3447 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003448 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003449 }
3450
3451 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003452 /* Bind saved result of context.__enter__() to VAR */
3453 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003454 !compiler_nameop(c, tmpvalue, Del))
3455 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003456 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003457 }
3458
3459 /* BLOCK code */
3460 VISIT_SEQ(c, stmt, s->v.With.body);
3461
3462 /* End of try block; start the finally block */
3463 ADDOP(c, POP_BLOCK);
3464 compiler_pop_fblock(c, FINALLY_TRY, block);
3465
3466 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3467 compiler_use_next_block(c, finally);
3468 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003469 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003470
3471 /* Finally block starts; push tmpexit and issue our magic opcode. */
3472 if (!compiler_nameop(c, tmpexit, Load) ||
3473 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003474 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003475 ADDOP(c, WITH_CLEANUP);
3476 ADDOP_I(c, CALL_FUNCTION, 3);
3477 ADDOP(c, POP_TOP);
3478
3479 /* Finally block ends. */
3480 ADDOP(c, END_FINALLY);
3481 compiler_pop_fblock(c, FINALLY_END, finally);
3482 return 1;
3483}
3484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485static int
3486compiler_visit_expr(struct compiler *c, expr_ty e)
3487{
3488 int i, n;
3489
3490 if (e->lineno > c->u->u_lineno) {
3491 c->u->u_lineno = e->lineno;
3492 c->u->u_lineno_set = false;
3493 }
3494 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003497 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 VISIT(c, expr, e->v.BinOp.left);
3499 VISIT(c, expr, e->v.BinOp.right);
3500 ADDOP(c, binop(c, e->v.BinOp.op));
3501 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 VISIT(c, expr, e->v.UnaryOp.operand);
3504 ADDOP(c, unaryop(e->v.UnaryOp.op));
3505 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003508 case IfExp_kind:
3509 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003510 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 /* XXX get rid of arg? */
3512 ADDOP_I(c, BUILD_MAP, 0);
3513 n = asdl_seq_LEN(e->v.Dict.values);
3514 /* We must arrange things just right for STORE_SUBSCR.
3515 It wants the stack to look like (value) (dict) (key) */
3516 for (i = 0; i < n; i++) {
3517 ADDOP(c, DUP_TOP);
3518 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3519 ADDOP(c, ROT_TWO);
3520 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3521 ADDOP(c, STORE_SUBSCR);
3522 }
3523 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 return compiler_genexp(c, e);
3528 case Yield_kind:
3529 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003530 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 /*
3532 for (i = 0; i < c->u->u_nfblocks; i++) {
3533 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3534 return compiler_error(
3535 c, "'yield' not allowed in a 'try' "
3536 "block with a 'finally' clause");
3537 }
3538 */
3539 if (e->v.Yield.value) {
3540 VISIT(c, expr, e->v.Yield.value);
3541 }
3542 else {
3543 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3544 }
3545 ADDOP(c, YIELD_VALUE);
3546 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003547 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003549 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003551 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 VISIT(c, expr, e->v.Repr.value);
3553 ADDOP(c, UNARY_CONVERT);
3554 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003555 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3557 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003558 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3560 break;
3561 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003562 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 if (e->v.Attribute.ctx != AugStore)
3564 VISIT(c, expr, e->v.Attribute.value);
3565 switch (e->v.Attribute.ctx) {
3566 case AugLoad:
3567 ADDOP(c, DUP_TOP);
3568 /* Fall through to load */
3569 case Load:
3570 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3571 break;
3572 case AugStore:
3573 ADDOP(c, ROT_TWO);
3574 /* Fall through to save */
3575 case Store:
3576 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3577 break;
3578 case Del:
3579 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3580 break;
3581 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003582 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003583 PyErr_SetString(PyExc_SystemError,
3584 "param invalid in attribute expression");
3585 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 }
3587 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 switch (e->v.Subscript.ctx) {
3590 case AugLoad:
3591 VISIT(c, expr, e->v.Subscript.value);
3592 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3593 break;
3594 case Load:
3595 VISIT(c, expr, e->v.Subscript.value);
3596 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3597 break;
3598 case AugStore:
3599 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3600 break;
3601 case Store:
3602 VISIT(c, expr, e->v.Subscript.value);
3603 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3604 break;
3605 case Del:
3606 VISIT(c, expr, e->v.Subscript.value);
3607 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3608 break;
3609 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003610 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003611 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003612 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003613 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 }
3615 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003616 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3618 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003619 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 return compiler_tuple(c, e);
3623 }
3624 return 1;
3625}
3626
3627static int
3628compiler_augassign(struct compiler *c, stmt_ty s)
3629{
3630 expr_ty e = s->v.AugAssign.target;
3631 expr_ty auge;
3632
3633 assert(s->kind == AugAssign_kind);
3634
3635 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003636 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003637 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003638 AugLoad, e->lineno, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003639 if (auge == NULL)
3640 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641 VISIT(c, expr, auge);
3642 VISIT(c, expr, s->v.AugAssign.value);
3643 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3644 auge->v.Attribute.ctx = AugStore;
3645 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646 break;
3647 case Subscript_kind:
3648 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00003649 AugLoad, e->lineno, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003650 if (auge == NULL)
3651 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003652 VISIT(c, expr, auge);
3653 VISIT(c, expr, s->v.AugAssign.value);
3654 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003657 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 case Name_kind:
3659 VISIT(c, expr, s->v.AugAssign.target);
3660 VISIT(c, expr, s->v.AugAssign.value);
3661 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3662 return compiler_nameop(c, e->v.Name.id, Store);
3663 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003664 PyErr_Format(PyExc_SystemError,
3665 "invalid node type (%d) for augmented assignment",
3666 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003667 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 }
3669 return 1;
3670}
3671
3672static int
3673compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3674{
3675 struct fblockinfo *f;
3676 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3677 return 0;
3678 f = &c->u->u_fblock[c->u->u_nfblocks++];
3679 f->fb_type = t;
3680 f->fb_block = b;
3681 return 1;
3682}
3683
3684static void
3685compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3686{
3687 struct compiler_unit *u = c->u;
3688 assert(u->u_nfblocks > 0);
3689 u->u_nfblocks--;
3690 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3691 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3692}
3693
3694/* Raises a SyntaxError and returns 0.
3695 If something goes wrong, a different exception may be raised.
3696*/
3697
3698static int
3699compiler_error(struct compiler *c, const char *errstr)
3700{
3701 PyObject *loc;
3702 PyObject *u = NULL, *v = NULL;
3703
3704 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3705 if (!loc) {
3706 Py_INCREF(Py_None);
3707 loc = Py_None;
3708 }
3709 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3710 Py_None, loc);
3711 if (!u)
3712 goto exit;
3713 v = Py_BuildValue("(zO)", errstr, u);
3714 if (!v)
3715 goto exit;
3716 PyErr_SetObject(PyExc_SyntaxError, v);
3717 exit:
3718 Py_DECREF(loc);
3719 Py_XDECREF(u);
3720 Py_XDECREF(v);
3721 return 0;
3722}
3723
3724static int
3725compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003726 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 /* XXX this code is duplicated */
3731 switch (ctx) {
3732 case AugLoad: /* fall through to Load */
3733 case Load: op = BINARY_SUBSCR; break;
3734 case AugStore:/* fall through to Store */
3735 case Store: op = STORE_SUBSCR; break;
3736 case Del: op = DELETE_SUBSCR; break;
3737 case Param:
3738 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003739 "invalid %s kind %d in subscript\n",
3740 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003741 return 0;
3742 }
3743 if (ctx == AugLoad) {
3744 ADDOP_I(c, DUP_TOPX, 2);
3745 }
3746 else if (ctx == AugStore) {
3747 ADDOP(c, ROT_THREE);
3748 }
3749 ADDOP(c, op);
3750 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751}
3752
3753static int
3754compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3755{
3756 int n = 2;
3757 assert(s->kind == Slice_kind);
3758
3759 /* only handles the cases where BUILD_SLICE is emitted */
3760 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 }
3763 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003764 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003768 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 }
3770 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003771 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 }
3773
3774 if (s->v.Slice.step) {
3775 n++;
3776 VISIT(c, expr, s->v.Slice.step);
3777 }
3778 ADDOP_I(c, BUILD_SLICE, n);
3779 return 1;
3780}
3781
3782static int
3783compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3784{
3785 int op = 0, slice_offset = 0, stack_count = 0;
3786
3787 assert(s->v.Slice.step == NULL);
3788 if (s->v.Slice.lower) {
3789 slice_offset++;
3790 stack_count++;
3791 if (ctx != AugStore)
3792 VISIT(c, expr, s->v.Slice.lower);
3793 }
3794 if (s->v.Slice.upper) {
3795 slice_offset += 2;
3796 stack_count++;
3797 if (ctx != AugStore)
3798 VISIT(c, expr, s->v.Slice.upper);
3799 }
3800
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003801 if (ctx == AugLoad) {
3802 switch (stack_count) {
3803 case 0: ADDOP(c, DUP_TOP); break;
3804 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3805 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3806 }
3807 }
3808 else if (ctx == AugStore) {
3809 switch (stack_count) {
3810 case 0: ADDOP(c, ROT_TWO); break;
3811 case 1: ADDOP(c, ROT_THREE); break;
3812 case 2: ADDOP(c, ROT_FOUR); break;
3813 }
3814 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815
3816 switch (ctx) {
3817 case AugLoad: /* fall through to Load */
3818 case Load: op = SLICE; break;
3819 case AugStore:/* fall through to Store */
3820 case Store: op = STORE_SLICE; break;
3821 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003822 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003823 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003824 PyErr_SetString(PyExc_SystemError,
3825 "param invalid in simple slice");
3826 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 }
3828
3829 ADDOP(c, op + slice_offset);
3830 return 1;
3831}
3832
3833static int
3834compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3835 expr_context_ty ctx)
3836{
3837 switch (s->kind) {
3838 case Ellipsis_kind:
3839 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3840 break;
3841 case Slice_kind:
3842 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 case Index_kind:
3844 VISIT(c, expr, s->v.Index.value);
3845 break;
3846 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003847 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003848 PyErr_SetString(PyExc_SystemError,
3849 "extended slice invalid in nested slice");
3850 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 }
3852 return 1;
3853}
3854
3855
3856static int
3857compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3858{
3859 switch (s->kind) {
3860 case Ellipsis_kind:
3861 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3862 break;
3863 case Slice_kind:
3864 if (!s->v.Slice.step)
3865 return compiler_simple_slice(c, s, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003866 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003867 return 0;
3868 if (ctx == AugLoad) {
3869 ADDOP_I(c, DUP_TOPX, 2);
3870 }
3871 else if (ctx == AugStore) {
3872 ADDOP(c, ROT_THREE);
3873 }
3874 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875 case ExtSlice_kind: {
3876 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3877 for (i = 0; i < n; i++) {
3878 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3879 if (!compiler_visit_nested_slice(c, sub, ctx))
3880 return 0;
3881 }
3882 ADDOP_I(c, BUILD_TUPLE, n);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003883 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 }
3885 case Index_kind:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003886 if (ctx != AugStore)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003887 VISIT(c, expr, s->v.Index.value);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003888 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003889 default:
3890 PyErr_Format(PyExc_SystemError,
3891 "invalid slice %d", s->kind);
3892 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003893 }
3894 return 1;
3895}
3896
3897/* do depth-first search of basic block graph, starting with block.
3898 post records the block indices in post-order.
3899
3900 XXX must handle implicit jumps from one block to next
3901*/
3902
3903static void
3904dfs(struct compiler *c, basicblock *b, struct assembler *a)
3905{
3906 int i;
3907 struct instr *instr = NULL;
3908
3909 if (b->b_seen)
3910 return;
3911 b->b_seen = 1;
3912 if (b->b_next != NULL)
3913 dfs(c, b->b_next, a);
3914 for (i = 0; i < b->b_iused; i++) {
3915 instr = &b->b_instr[i];
3916 if (instr->i_jrel || instr->i_jabs)
3917 dfs(c, instr->i_target, a);
3918 }
3919 a->a_postorder[a->a_nblocks++] = b;
3920}
3921
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003922static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3924{
3925 int i;
3926 struct instr *instr;
3927 if (b->b_seen || b->b_startdepth >= depth)
3928 return maxdepth;
3929 b->b_seen = 1;
3930 b->b_startdepth = depth;
3931 for (i = 0; i < b->b_iused; i++) {
3932 instr = &b->b_instr[i];
3933 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3934 if (depth > maxdepth)
3935 maxdepth = depth;
3936 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3937 if (instr->i_jrel || instr->i_jabs) {
3938 maxdepth = stackdepth_walk(c, instr->i_target,
3939 depth, maxdepth);
3940 if (instr->i_opcode == JUMP_ABSOLUTE ||
3941 instr->i_opcode == JUMP_FORWARD) {
3942 goto out; /* remaining code is dead */
3943 }
3944 }
3945 }
3946 if (b->b_next)
3947 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3948out:
3949 b->b_seen = 0;
3950 return maxdepth;
3951}
3952
3953/* Find the flow path that needs the largest stack. We assume that
3954 * cycles in the flow graph have no net effect on the stack depth.
3955 */
3956static int
3957stackdepth(struct compiler *c)
3958{
3959 basicblock *b, *entryblock;
3960 entryblock = NULL;
3961 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3962 b->b_seen = 0;
3963 b->b_startdepth = INT_MIN;
3964 entryblock = b;
3965 }
3966 return stackdepth_walk(c, entryblock, 0, 0);
3967}
3968
3969static int
3970assemble_init(struct assembler *a, int nblocks, int firstlineno)
3971{
3972 memset(a, 0, sizeof(struct assembler));
3973 a->a_lineno = firstlineno;
3974 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3975 if (!a->a_bytecode)
3976 return 0;
3977 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3978 if (!a->a_lnotab)
3979 return 0;
3980 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003981 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003982 if (!a->a_postorder) {
3983 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003985 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986 return 1;
3987}
3988
3989static void
3990assemble_free(struct assembler *a)
3991{
3992 Py_XDECREF(a->a_bytecode);
3993 Py_XDECREF(a->a_lnotab);
3994 if (a->a_postorder)
3995 PyObject_Free(a->a_postorder);
3996}
3997
3998/* Return the size of a basic block in bytes. */
3999
4000static int
4001instrsize(struct instr *instr)
4002{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004003 if (!instr->i_hasarg)
4004 return 1;
4005 if (instr->i_oparg > 0xffff)
4006 return 6;
4007 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004008}
4009
4010static int
4011blocksize(basicblock *b)
4012{
4013 int i;
4014 int size = 0;
4015
4016 for (i = 0; i < b->b_iused; i++)
4017 size += instrsize(&b->b_instr[i]);
4018 return size;
4019}
4020
4021/* All about a_lnotab.
4022
4023c_lnotab is an array of unsigned bytes disguised as a Python string.
4024It is used to map bytecode offsets to source code line #s (when needed
4025for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004026
Tim Peters2a7f3842001-06-09 09:26:21 +00004027The array is conceptually a list of
4028 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004029pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004030
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004031 byte code offset source code line number
4032 0 1
4033 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004034 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004035 350 307
4036 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004037
4038The first trick is that these numbers aren't stored, only the increments
4039from one row to the next (this doesn't really work, but it's a start):
4040
4041 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4042
4043The second trick is that an unsigned byte can't hold negative values, or
4044values larger than 255, so (a) there's a deep assumption that byte code
4045offsets and their corresponding line #s both increase monotonically, and (b)
4046if at least one column jumps by more than 255 from one row to the next, more
4047than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004048from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004049part. A user of c_lnotab desiring to find the source line number
4050corresponding to a bytecode address A should do something like this
4051
4052 lineno = addr = 0
4053 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004054 addr += addr_incr
4055 if addr > A:
4056 return lineno
4057 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004058
4059In order for this to work, when the addr field increments by more than 255,
4060the line # increment in each pair generated must be 0 until the remaining addr
4061increment is < 256. So, in the example above, com_set_lineno should not (as
4062was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004063255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004064*/
4065
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004066static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004068{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004069 int d_bytecode, d_lineno;
4070 int len;
4071 char *lnotab;
4072
4073 d_bytecode = a->a_offset - a->a_lineno_off;
4074 d_lineno = i->i_lineno - a->a_lineno;
4075
4076 assert(d_bytecode >= 0);
4077 assert(d_lineno >= 0);
4078
4079 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004080 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004081
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004083 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004084 nbytes = a->a_lnotab_off + 2 * ncodes;
4085 len = PyString_GET_SIZE(a->a_lnotab);
4086 if (nbytes >= len) {
4087 if (len * 2 < nbytes)
4088 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004089 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 len *= 2;
4091 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4092 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004093 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004095 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096 *lnotab++ = 255;
4097 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004098 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004099 d_bytecode -= ncodes * 255;
4100 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004101 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004102 assert(d_bytecode <= 255);
4103 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004104 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 nbytes = a->a_lnotab_off + 2 * ncodes;
4106 len = PyString_GET_SIZE(a->a_lnotab);
4107 if (nbytes >= len) {
4108 if (len * 2 < nbytes)
4109 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004110 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 len *= 2;
4112 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4113 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004114 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4116 *lnotab++ = 255;
4117 *lnotab++ = d_bytecode;
4118 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004119 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120 *lnotab++ = 255;
4121 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004122 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 d_lineno -= ncodes * 255;
4124 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004125 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004126
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127 len = PyString_GET_SIZE(a->a_lnotab);
4128 if (a->a_lnotab_off + 2 >= len) {
4129 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004130 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004131 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004133
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 a->a_lnotab_off += 2;
4135 if (d_bytecode) {
4136 *lnotab++ = d_bytecode;
4137 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004138 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004139 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004140 *lnotab++ = 0;
4141 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004142 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143 a->a_lineno = i->i_lineno;
4144 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004145 return 1;
4146}
4147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148/* assemble_emit()
4149 Extend the bytecode with a new instruction.
4150 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004151*/
4152
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004153static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004155{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004156 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157 int len = PyString_GET_SIZE(a->a_bytecode);
4158 char *code;
4159
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004160 size = instrsize(i);
4161 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004163 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004164 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004166 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 if (a->a_offset + size >= len) {
4168 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004169 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004170 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4172 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004173 if (size == 6) {
4174 assert(i->i_hasarg);
4175 *code++ = (char)EXTENDED_ARG;
4176 *code++ = ext & 0xff;
4177 *code++ = ext >> 8;
4178 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004179 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004181 if (i->i_hasarg) {
4182 assert(size == 3 || size == 6);
4183 *code++ = arg & 0xff;
4184 *code++ = arg >> 8;
4185 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004187}
4188
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004189static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004191{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004193 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004194 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196 /* Compute the size of each block and fixup jump args.
4197 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004198start:
4199 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004201 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004202 bsize = blocksize(b);
4203 b->b_offset = totsize;
4204 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004205 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004206 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4208 bsize = b->b_offset;
4209 for (i = 0; i < b->b_iused; i++) {
4210 struct instr *instr = &b->b_instr[i];
4211 /* Relative jumps are computed relative to
4212 the instruction pointer after fetching
4213 the jump instruction.
4214 */
4215 bsize += instrsize(instr);
4216 if (instr->i_jabs)
4217 instr->i_oparg = instr->i_target->b_offset;
4218 else if (instr->i_jrel) {
4219 int delta = instr->i_target->b_offset - bsize;
4220 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004221 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004222 else
4223 continue;
4224 if (instr->i_oparg > 0xffff)
4225 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004226 }
4227 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004228
4229 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004230 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004231 with a better solution.
4232
4233 In the meantime, should the goto be dropped in favor
4234 of a loop?
4235
4236 The issue is that in the first loop blocksize() is called
4237 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004238 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004239 i_oparg is calculated in the second loop above.
4240
4241 So we loop until we stop seeing new EXTENDED_ARGs.
4242 The only EXTENDED_ARGs that could be popping up are
4243 ones in jump instructions. So this should converge
4244 fairly quickly.
4245 */
4246 if (last_extended_arg_count != extended_arg_count) {
4247 last_extended_arg_count = extended_arg_count;
4248 goto start;
4249 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004250}
4251
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004252static PyObject *
4253dict_keys_inorder(PyObject *dict, int offset)
4254{
4255 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004256 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004257
4258 tuple = PyTuple_New(size);
4259 if (tuple == NULL)
4260 return NULL;
4261 while (PyDict_Next(dict, &pos, &k, &v)) {
4262 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004263 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004264 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004265 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004266 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004267 PyTuple_SET_ITEM(tuple, i - offset, k);
4268 }
4269 return tuple;
4270}
4271
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004272static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004273compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004274{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004275 PySTEntryObject *ste = c->u->u_ste;
4276 int flags = 0, n;
4277 if (ste->ste_type != ModuleBlock)
4278 flags |= CO_NEWLOCALS;
4279 if (ste->ste_type == FunctionBlock) {
4280 if (!ste->ste_unoptimized)
4281 flags |= CO_OPTIMIZED;
4282 if (ste->ste_nested)
4283 flags |= CO_NESTED;
4284 if (ste->ste_generator)
4285 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004286 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004287 if (ste->ste_varargs)
4288 flags |= CO_VARARGS;
4289 if (ste->ste_varkeywords)
4290 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004291 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004293
4294 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004295 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297 n = PyDict_Size(c->u->u_freevars);
4298 if (n < 0)
4299 return -1;
4300 if (n == 0) {
4301 n = PyDict_Size(c->u->u_cellvars);
4302 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004303 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004304 if (n == 0) {
4305 flags |= CO_NOFREE;
4306 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004307 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004308
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004309 return flags;
4310}
4311
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004312static PyCodeObject *
4313makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004314{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315 PyObject *tmp;
4316 PyCodeObject *co = NULL;
4317 PyObject *consts = NULL;
4318 PyObject *names = NULL;
4319 PyObject *varnames = NULL;
4320 PyObject *filename = NULL;
4321 PyObject *name = NULL;
4322 PyObject *freevars = NULL;
4323 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004324 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004327 tmp = dict_keys_inorder(c->u->u_consts, 0);
4328 if (!tmp)
4329 goto error;
4330 consts = PySequence_List(tmp); /* optimize_code requires a list */
4331 Py_DECREF(tmp);
4332
4333 names = dict_keys_inorder(c->u->u_names, 0);
4334 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4335 if (!consts || !names || !varnames)
4336 goto error;
4337
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004338 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4339 if (!cellvars)
4340 goto error;
4341 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4342 if (!freevars)
4343 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344 filename = PyString_FromString(c->c_filename);
4345 if (!filename)
4346 goto error;
4347
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004348 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349 flags = compute_code_flags(c);
4350 if (flags < 0)
4351 goto error;
4352
4353 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4354 if (!bytecode)
4355 goto error;
4356
4357 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4358 if (!tmp)
4359 goto error;
4360 Py_DECREF(consts);
4361 consts = tmp;
4362
4363 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4364 bytecode, consts, names, varnames,
4365 freevars, cellvars,
4366 filename, c->u->u_name,
4367 c->u->u_firstlineno,
4368 a->a_lnotab);
4369 error:
4370 Py_XDECREF(consts);
4371 Py_XDECREF(names);
4372 Py_XDECREF(varnames);
4373 Py_XDECREF(filename);
4374 Py_XDECREF(name);
4375 Py_XDECREF(freevars);
4376 Py_XDECREF(cellvars);
4377 Py_XDECREF(bytecode);
4378 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004379}
4380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381static PyCodeObject *
4382assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004383{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384 basicblock *b, *entryblock;
4385 struct assembler a;
4386 int i, j, nblocks;
4387 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004388
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389 /* Make sure every block that falls off the end returns None.
4390 XXX NEXT_BLOCK() isn't quite right, because if the last
4391 block ends with a jump or return b_next shouldn't set.
4392 */
4393 if (!c->u->u_curblock->b_return) {
4394 NEXT_BLOCK(c);
4395 if (addNone)
4396 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4397 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004398 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400 nblocks = 0;
4401 entryblock = NULL;
4402 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4403 nblocks++;
4404 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004405 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004407 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4408 goto error;
4409 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004412 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004413
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414 /* Emit code in reverse postorder from dfs. */
4415 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004416 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004417 for (j = 0; j < b->b_iused; j++)
4418 if (!assemble_emit(&a, &b->b_instr[j]))
4419 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004420 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4423 goto error;
4424 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4425 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004426
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004427 co = makecode(c, &a);
4428 error:
4429 assemble_free(&a);
4430 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004431}