blob: 6d96006f31ef4e29ef5efe8a6e42fbc01a40fde8 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
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 *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207 if (privateobj == NULL || name == NULL || name[0] != '_' ||
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 name[1] != '_') {
209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
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)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317 PyObject_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;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000337 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000380 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000394/* Begin: Peephole optimizations ----------------------------------------- */
395
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000396#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000398#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
399#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000400#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define ISBASICBLOCK(blocks, start, bytes) \
403 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000410 Bails out with no change if one or more of the LOAD_CONSTs is missing.
411 Also works for BUILD_LIST when followed by an "in" or "not in" test.
412*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413static int
414tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
415{
416 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418
419 /* Pre-conditions */
420 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000421 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000424 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425
426 /* Buildup new tuple of constants */
427 newconst = PyTuple_New(n);
428 if (newconst == NULL)
429 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 for (i=0 ; i<n ; i++) {
432 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 constant = PyList_GET_ITEM(consts, arg);
435 Py_INCREF(constant);
436 PyTuple_SET_ITEM(newconst, i, constant);
437 }
438
439 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 if (PyList_Append(consts, newconst)) {
441 Py_DECREF(newconst);
442 return 0;
443 }
444 Py_DECREF(newconst);
445
446 /* Write NOPs over old LOAD_CONSTS and
447 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
448 memset(codestr, NOP, n*3);
449 codestr[n*3] = LOAD_CONST;
450 SETARG(codestr, (n*3), len_consts);
451 return 1;
452}
453
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000458 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000459 Abandons the transformation if the folding fails (i.e. 1+'a').
460 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 is below a threshold value. That keeps pyc files from
462 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000463*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000464static int
465fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
466{
467 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t len_consts, size;
469 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000470
471 /* Pre-conditions */
472 assert(PyList_CheckExact(consts));
473 assert(codestr[0] == LOAD_CONST);
474 assert(codestr[3] == LOAD_CONST);
475
476 /* Create new constant */
477 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
478 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
479 opcode = codestr[6];
480 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 case BINARY_POWER:
482 newconst = PyNumber_Power(v, w, Py_None);
483 break;
484 case BINARY_MULTIPLY:
485 newconst = PyNumber_Multiply(v, w);
486 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000487 case BINARY_TRUE_DIVIDE:
488 newconst = PyNumber_TrueDivide(v, w);
489 break;
490 case BINARY_FLOOR_DIVIDE:
491 newconst = PyNumber_FloorDivide(v, w);
492 break;
493 case BINARY_MODULO:
494 newconst = PyNumber_Remainder(v, w);
495 break;
496 case BINARY_ADD:
497 newconst = PyNumber_Add(v, w);
498 break;
499 case BINARY_SUBTRACT:
500 newconst = PyNumber_Subtract(v, w);
501 break;
502 case BINARY_SUBSCR:
503 newconst = PyObject_GetItem(v, w);
504 break;
505 case BINARY_LSHIFT:
506 newconst = PyNumber_Lshift(v, w);
507 break;
508 case BINARY_RSHIFT:
509 newconst = PyNumber_Rshift(v, w);
510 break;
511 case BINARY_AND:
512 newconst = PyNumber_And(v, w);
513 break;
514 case BINARY_XOR:
515 newconst = PyNumber_Xor(v, w);
516 break;
517 case BINARY_OR:
518 newconst = PyNumber_Or(v, w);
519 break;
520 default:
521 /* Called with an unknown opcode */
522 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000523 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000524 opcode);
525 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000526 }
527 if (newconst == NULL) {
528 PyErr_Clear();
529 return 0;
530 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000531 size = PyObject_Size(newconst);
532 if (size == -1)
533 PyErr_Clear();
534 else if (size > 20) {
535 Py_DECREF(newconst);
536 return 0;
537 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000538
539 /* Append folded constant into consts table */
540 len_consts = PyList_GET_SIZE(consts);
541 if (PyList_Append(consts, newconst)) {
542 Py_DECREF(newconst);
543 return 0;
544 }
545 Py_DECREF(newconst);
546
547 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
548 memset(codestr, NOP, 4);
549 codestr[4] = LOAD_CONST;
550 SETARG(codestr, 4, len_consts);
551 return 1;
552}
553
Raymond Hettinger80121492005-02-20 12:41:32 +0000554static int
555fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
556{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000557 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558 Py_ssize_t len_consts;
559 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000560
561 /* Pre-conditions */
562 assert(PyList_CheckExact(consts));
563 assert(codestr[0] == LOAD_CONST);
564
565 /* Create new constant */
566 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
567 opcode = codestr[3];
568 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000569 case UNARY_NEGATIVE:
570 /* Preserve the sign of -0.0 */
571 if (PyObject_IsTrue(v) == 1)
572 newconst = PyNumber_Negative(v);
573 break;
574 case UNARY_CONVERT:
575 newconst = PyObject_Repr(v);
576 break;
577 case UNARY_INVERT:
578 newconst = PyNumber_Invert(v);
579 break;
580 default:
581 /* Called with an unknown opcode */
582 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000583 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000584 opcode);
585 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000586 }
587 if (newconst == NULL) {
588 PyErr_Clear();
589 return 0;
590 }
591
592 /* Append folded constant into consts table */
593 len_consts = PyList_GET_SIZE(consts);
594 if (PyList_Append(consts, newconst)) {
595 Py_DECREF(newconst);
596 return 0;
597 }
598 Py_DECREF(newconst);
599
600 /* Write NOP LOAD_CONST newconst */
601 codestr[0] = NOP;
602 codestr[1] = LOAD_CONST;
603 SETARG(codestr, 1, len_consts);
604 return 1;
605}
606
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000607static unsigned int *
608markblocks(unsigned char *code, int len)
609{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000610 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000611 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612
613 if (blocks == NULL)
614 return NULL;
615 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616
617 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000618 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
619 opcode = code[i];
620 switch (opcode) {
621 case FOR_ITER:
622 case JUMP_FORWARD:
623 case JUMP_IF_FALSE:
624 case JUMP_IF_TRUE:
625 case JUMP_ABSOLUTE:
626 case CONTINUE_LOOP:
627 case SETUP_LOOP:
628 case SETUP_EXCEPT:
629 case SETUP_FINALLY:
630 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000631 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000633 }
634 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000635 /* Build block numbers in the second pass */
636 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000638 blocks[i] = blockcnt;
639 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000640 return blocks;
641}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000642
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000643/* Perform basic peephole optimizations to components of a code object.
644 The consts object should still be in list form to allow new constants
645 to be appended.
646
647 To keep the optimizer simple, it bails out (does nothing) for code
648 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000649 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000650 the lineno table has complex encoding for gaps >= 255.
651
652 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000653 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000654 smaller. For those that reduce size, the gaps are initially filled with
655 NOPs. Later those NOPs are removed and the jump addresses retargeted in
656 a single pass. Line numbering is adjusted accordingly. */
657
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000658static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000659optimize_code(PyObject *code, PyObject* consts, PyObject *names,
660 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000661{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000662 Py_ssize_t i, j, codelen;
663 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000664 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000665 unsigned char *codestr = NULL;
666 unsigned char *lineno;
667 int *addrmap = NULL;
668 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000669 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000670 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000671 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000672
Raymond Hettingereffb3932004-10-30 08:55:08 +0000673 /* Bail out if an exception is set */
674 if (PyErr_Occurred())
675 goto exitUnchanged;
676
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000677 /* Bypass optimization when the lineno table is too complex */
678 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000679 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000680 tabsiz = PyString_GET_SIZE(lineno_obj);
681 if (memchr(lineno, 255, tabsiz) != NULL)
682 goto exitUnchanged;
683
Raymond Hettingera12fa142004-08-24 04:34:16 +0000684 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000685 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000686 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000687 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000688 goto exitUnchanged;
689
690 /* Make a modifiable copy of the code string */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000692 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000693 goto exitUnchanged;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 codestr = (unsigned char *)memcpy(codestr,
695 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000696
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000697 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000698 the various transformation patterns to look ahead several
699 instructions without additional checks to make sure they are not
700 looking beyond the end of the code string.
701 */
702 if (codestr[codelen-1] != RETURN_VALUE)
703 goto exitUnchanged;
704
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000705 /* Mapping to new jump targets after NOPs are removed */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000706 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000707 if (addrmap == NULL)
708 goto exitUnchanged;
709
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000710 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000711 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000712 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000713 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000714
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000715 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000716 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000717
718 lastlc = cumlc;
719 cumlc = 0;
720
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000721 switch (opcode) {
722
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000723 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
724 with JUMP_IF_TRUE POP_TOP */
725 case UNARY_NOT:
726 if (codestr[i+1] != JUMP_IF_FALSE ||
727 codestr[i+4] != POP_TOP ||
728 !ISBASICBLOCK(blocks,i,5))
729 continue;
730 tgt = GETJUMPTGT(codestr, (i+1));
731 if (codestr[tgt] != POP_TOP)
732 continue;
733 j = GETARG(codestr, i+1) + 1;
734 codestr[i] = JUMP_IF_TRUE;
735 SETARG(codestr, i, j);
736 codestr[i+3] = POP_TOP;
737 codestr[i+4] = NOP;
738 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000739
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000740 /* not a is b --> a is not b
741 not a in b --> a not in b
742 not a is not b --> a is b
743 not a not in b --> a in b
744 */
745 case COMPARE_OP:
746 j = GETARG(codestr, i);
747 if (j < 6 || j > 9 ||
748 codestr[i+3] != UNARY_NOT ||
749 !ISBASICBLOCK(blocks,i,4))
750 continue;
751 SETARG(codestr, i, (j^1));
752 codestr[i+3] = NOP;
753 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000754
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000755 /* Replace LOAD_GLOBAL/LOAD_NAME None
756 with LOAD_CONST None */
757 case LOAD_NAME:
758 case LOAD_GLOBAL:
759 j = GETARG(codestr, i);
760 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
761 if (name == NULL || strcmp(name, "None") != 0)
762 continue;
763 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
764 if (PyList_GET_ITEM(consts, j) == Py_None) {
765 codestr[i] = LOAD_CONST;
766 SETARG(codestr, i, j);
767 cumlc = lastlc + 1;
768 break;
769 }
770 }
771 break;
772
773 /* Skip over LOAD_CONST trueconst
774 JUMP_IF_FALSE xx POP_TOP */
775 case LOAD_CONST:
776 cumlc = lastlc + 1;
777 j = GETARG(codestr, i);
778 if (codestr[i+3] != JUMP_IF_FALSE ||
779 codestr[i+6] != POP_TOP ||
780 !ISBASICBLOCK(blocks,i,7) ||
781 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
782 continue;
783 memset(codestr+i, NOP, 7);
784 cumlc = 0;
785 break;
786
787 /* Try to fold tuples of constants (includes a case for lists
788 which are only used for "in" and "not in" tests).
789 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
790 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
791 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
792 case BUILD_TUPLE:
793 case BUILD_LIST:
794 j = GETARG(codestr, i);
795 h = i - 3 * j;
796 if (h >= 0 &&
797 j <= lastlc &&
798 ((opcode == BUILD_TUPLE &&
799 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
800 (opcode == BUILD_LIST &&
801 codestr[i+3]==COMPARE_OP &&
802 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
803 (GETARG(codestr,i+3)==6 ||
804 GETARG(codestr,i+3)==7))) &&
805 tuple_of_constants(&codestr[h], j, consts)) {
806 assert(codestr[i] == LOAD_CONST);
807 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000808 break;
809 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000810 if (codestr[i+3] != UNPACK_SEQUENCE ||
811 !ISBASICBLOCK(blocks,i,6) ||
812 j != GETARG(codestr, i+3))
813 continue;
814 if (j == 1) {
815 memset(codestr+i, NOP, 6);
816 } else if (j == 2) {
817 codestr[i] = ROT_TWO;
818 memset(codestr+i+1, NOP, 5);
819 } else if (j == 3) {
820 codestr[i] = ROT_THREE;
821 codestr[i+1] = ROT_TWO;
822 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000823 }
824 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000825
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000826 /* Fold binary ops on constants.
827 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
828 case BINARY_POWER:
829 case BINARY_MULTIPLY:
830 case BINARY_TRUE_DIVIDE:
831 case BINARY_FLOOR_DIVIDE:
832 case BINARY_MODULO:
833 case BINARY_ADD:
834 case BINARY_SUBTRACT:
835 case BINARY_SUBSCR:
836 case BINARY_LSHIFT:
837 case BINARY_RSHIFT:
838 case BINARY_AND:
839 case BINARY_XOR:
840 case BINARY_OR:
841 if (lastlc >= 2 &&
842 ISBASICBLOCK(blocks, i-6, 7) &&
843 fold_binops_on_constants(&codestr[i-6], consts)) {
844 i -= 2;
845 assert(codestr[i] == LOAD_CONST);
846 cumlc = 1;
847 }
848 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000849
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000850 /* Fold unary ops on constants.
851 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
852 case UNARY_NEGATIVE:
853 case UNARY_CONVERT:
854 case UNARY_INVERT:
855 if (lastlc >= 1 &&
856 ISBASICBLOCK(blocks, i-3, 4) &&
857 fold_unaryops_on_constants(&codestr[i-3], consts)) {
858 i -= 2;
859 assert(codestr[i] == LOAD_CONST);
860 cumlc = 1;
861 }
862 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000863
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000864 /* Simplify conditional jump to conditional jump where the
865 result of the first test implies the success of a similar
866 test or the failure of the opposite test.
867 Arises in code like:
868 "if a and b:"
869 "if a or b:"
870 "a and b or c"
871 "(a and b) and c"
872 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
873 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
874 where y+3 is the instruction following the second test.
875 */
876 case JUMP_IF_FALSE:
877 case JUMP_IF_TRUE:
878 tgt = GETJUMPTGT(codestr, i);
879 j = codestr[tgt];
880 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
881 if (j == opcode) {
882 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
883 SETARG(codestr, i, tgttgt);
884 } else {
885 tgt -= i;
886 SETARG(codestr, i, tgt);
887 }
888 break;
889 }
890 /* Intentional fallthrough */
891
892 /* Replace jumps to unconditional jumps */
893 case FOR_ITER:
894 case JUMP_FORWARD:
895 case JUMP_ABSOLUTE:
896 case CONTINUE_LOOP:
897 case SETUP_LOOP:
898 case SETUP_EXCEPT:
899 case SETUP_FINALLY:
900 tgt = GETJUMPTGT(codestr, i);
901 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
902 continue;
903 tgttgt = GETJUMPTGT(codestr, tgt);
904 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
905 opcode = JUMP_ABSOLUTE;
906 if (!ABSOLUTE_JUMP(opcode))
907 tgttgt -= i + 3; /* Calc relative jump addr */
908 if (tgttgt < 0) /* No backward relative jumps */
909 continue;
910 codestr[i] = opcode;
911 SETARG(codestr, i, tgttgt);
912 break;
913
914 case EXTENDED_ARG:
915 goto exitUnchanged;
916
917 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
918 case RETURN_VALUE:
919 if (i+4 >= codelen ||
920 codestr[i+4] != RETURN_VALUE ||
921 !ISBASICBLOCK(blocks,i,5))
922 continue;
923 memset(codestr+i+1, NOP, 4);
924 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000925 }
926 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000927
928 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000929 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
930 addrmap[i] = i - nops;
931 if (codestr[i] == NOP)
932 nops++;
933 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000934 cum_orig_line = 0;
935 last_line = 0;
936 for (i=0 ; i < tabsiz ; i+=2) {
937 cum_orig_line += lineno[i];
938 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000939 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000940 lineno[i] =((unsigned char)(new_line - last_line));
941 last_line = new_line;
942 }
943
944 /* Remove NOPs and fixup jump targets */
945 for (i=0, h=0 ; i<codelen ; ) {
946 opcode = codestr[i];
947 switch (opcode) {
948 case NOP:
949 i++;
950 continue;
951
952 case JUMP_ABSOLUTE:
953 case CONTINUE_LOOP:
954 j = addrmap[GETARG(codestr, i)];
955 SETARG(codestr, i, j);
956 break;
957
958 case FOR_ITER:
959 case JUMP_FORWARD:
960 case JUMP_IF_FALSE:
961 case JUMP_IF_TRUE:
962 case SETUP_LOOP:
963 case SETUP_EXCEPT:
964 case SETUP_FINALLY:
965 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
966 SETARG(codestr, i, j);
967 break;
968 }
969 adj = CODESIZE(opcode);
970 while (adj--)
971 codestr[h++] = codestr[i++];
972 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000973 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000974
975 code = PyString_FromStringAndSize((char *)codestr, h);
976 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000977 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000978 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000979 return code;
980
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000981 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000982 if (blocks != NULL)
983 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000984 if (addrmap != NULL)
985 PyMem_Free(addrmap);
986 if (codestr != NULL)
987 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000988 Py_INCREF(code);
989 return code;
990}
991
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000992/* End: Peephole optimizations ----------------------------------------- */
993
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000994/*
995
996Leave this debugging code for just a little longer.
997
998static void
999compiler_display_symbols(PyObject *name, PyObject *symbols)
1000{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001001PyObject *key, *value;
1002int flags;
1003Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001005fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1006while (PyDict_Next(symbols, &pos, &key, &value)) {
1007flags = PyInt_AsLong(value);
1008fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1009if (flags & DEF_GLOBAL)
1010fprintf(stderr, " declared_global");
1011if (flags & DEF_LOCAL)
1012fprintf(stderr, " local");
1013if (flags & DEF_PARAM)
1014fprintf(stderr, " param");
1015if (flags & DEF_STAR)
1016fprintf(stderr, " stararg");
1017if (flags & DEF_DOUBLESTAR)
1018fprintf(stderr, " starstar");
1019if (flags & DEF_INTUPLE)
1020fprintf(stderr, " tuple");
1021if (flags & DEF_FREE)
1022fprintf(stderr, " free");
1023if (flags & DEF_FREE_GLOBAL)
1024fprintf(stderr, " global");
1025if (flags & DEF_FREE_CLASS)
1026fprintf(stderr, " free/class");
1027if (flags & DEF_IMPORT)
1028fprintf(stderr, " import");
1029fprintf(stderr, "\n");
1030}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031 fprintf(stderr, "\n");
1032}
1033*/
1034
1035static void
1036compiler_unit_check(struct compiler_unit *u)
1037{
1038 basicblock *block;
1039 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1040 assert(block != (void *)0xcbcbcbcb);
1041 assert(block != (void *)0xfbfbfbfb);
1042 assert(block != (void *)0xdbdbdbdb);
1043 if (block->b_instr != NULL) {
1044 assert(block->b_ialloc > 0);
1045 assert(block->b_iused > 0);
1046 assert(block->b_ialloc >= block->b_iused);
1047 }
1048 else {
1049 assert (block->b_iused == 0);
1050 assert (block->b_ialloc == 0);
1051 }
1052 }
1053}
1054
1055static void
1056compiler_unit_free(struct compiler_unit *u)
1057{
1058 basicblock *b, *next;
1059
1060 compiler_unit_check(u);
1061 b = u->u_blocks;
1062 while (b != NULL) {
1063 if (b->b_instr)
1064 PyObject_Free((void *)b->b_instr);
1065 next = b->b_list;
1066 PyObject_Free((void *)b);
1067 b = next;
1068 }
1069 Py_XDECREF(u->u_ste);
1070 Py_XDECREF(u->u_name);
1071 Py_XDECREF(u->u_consts);
1072 Py_XDECREF(u->u_names);
1073 Py_XDECREF(u->u_varnames);
1074 Py_XDECREF(u->u_freevars);
1075 Py_XDECREF(u->u_cellvars);
1076 Py_XDECREF(u->u_private);
1077 PyObject_Free(u);
1078}
1079
1080static int
1081compiler_enter_scope(struct compiler *c, identifier name, void *key,
1082 int lineno)
1083{
1084 struct compiler_unit *u;
1085
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001086 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1087 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001088 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001089 PyErr_NoMemory();
1090 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001091 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001092 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093 u->u_argcount = 0;
1094 u->u_ste = PySymtable_Lookup(c->c_st, key);
1095 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001096 compiler_unit_free(u);
1097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 }
1099 Py_INCREF(name);
1100 u->u_name = name;
1101 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1102 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1103 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001104 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105
1106 u->u_blocks = NULL;
1107 u->u_tmpname = 0;
1108 u->u_nfblocks = 0;
1109 u->u_firstlineno = lineno;
1110 u->u_lineno = 0;
1111 u->u_lineno_set = false;
1112 u->u_consts = PyDict_New();
1113 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001114 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001115 return 0;
1116 }
1117 u->u_names = PyDict_New();
1118 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001119 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return 0;
1121 }
1122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001123 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
1125 /* Push the old compiler_unit on the stack. */
1126 if (c->u) {
1127 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1128 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001129 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 return 0;
1131 }
1132 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001133 u->u_private = c->u->u_private;
1134 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 }
1136 c->u = u;
1137
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001139 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return 0;
1141
1142 return 1;
1143}
1144
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001145static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146compiler_exit_scope(struct compiler *c)
1147{
1148 int n;
1149 PyObject *wrapper;
1150
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 compiler_unit_free(c->u);
1153 /* Restore c->u to the parent unit. */
1154 n = PyList_GET_SIZE(c->c_stack) - 1;
1155 if (n >= 0) {
1156 wrapper = PyList_GET_ITEM(c->c_stack, n);
1157 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001158 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001160 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 compiler_unit_check(c->u);
1162 }
1163 else
1164 c->u = NULL;
1165
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
Guido van Rossumc2e20742006-02-27 22:32:47 +00001168/* Allocate a new "anonymous" local variable.
1169 Used by list comprehensions and with statements.
1170*/
1171
1172static PyObject *
1173compiler_new_tmpname(struct compiler *c)
1174{
1175 char tmpname[256];
1176 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1177 return PyString_FromString(tmpname);
1178}
1179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180/* Allocate a new block and return a pointer to it.
1181 Returns NULL on error.
1182*/
1183
1184static basicblock *
1185compiler_new_block(struct compiler *c)
1186{
1187 basicblock *b;
1188 struct compiler_unit *u;
1189
1190 u = c->u;
1191 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001192 if (b == NULL) {
1193 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001197 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198 b->b_list = u->u_blocks;
1199 u->u_blocks = b;
1200 return b;
1201}
1202
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203static basicblock *
1204compiler_use_new_block(struct compiler *c)
1205{
1206 basicblock *block = compiler_new_block(c);
1207 if (block == NULL)
1208 return NULL;
1209 c->u->u_curblock = block;
1210 return block;
1211}
1212
1213static basicblock *
1214compiler_next_block(struct compiler *c)
1215{
1216 basicblock *block = compiler_new_block(c);
1217 if (block == NULL)
1218 return NULL;
1219 c->u->u_curblock->b_next = block;
1220 c->u->u_curblock = block;
1221 return block;
1222}
1223
1224static basicblock *
1225compiler_use_next_block(struct compiler *c, basicblock *block)
1226{
1227 assert(block != NULL);
1228 c->u->u_curblock->b_next = block;
1229 c->u->u_curblock = block;
1230 return block;
1231}
1232
1233/* Returns the offset of the next instruction in the current block's
1234 b_instr array. Resizes the b_instr as necessary.
1235 Returns -1 on failure.
1236 */
1237
1238static int
1239compiler_next_instr(struct compiler *c, basicblock *b)
1240{
1241 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001242 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001243 b->b_instr = (struct instr *)PyObject_Malloc(
1244 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001245 if (b->b_instr == NULL) {
1246 PyErr_NoMemory();
1247 return -1;
1248 }
1249 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1250 memset((char *)b->b_instr, 0,
1251 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253 else if (b->b_iused == b->b_ialloc) {
1254 size_t oldsize, newsize;
1255 oldsize = b->b_ialloc * sizeof(struct instr);
1256 newsize = oldsize << 1;
1257 if (newsize == 0) {
1258 PyErr_NoMemory();
1259 return -1;
1260 }
1261 b->b_ialloc <<= 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262 b->b_instr = (struct instr *)PyObject_Realloc(
1263 (void *)b->b_instr, newsize);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001264 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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271/* Set the i_lineno member of the instruction at offse off if the
1272 line number for the current expression/statement (?) has not
1273 already been set. If it has been set, the call has no effect.
1274
1275 Every time a new node is b
1276 */
1277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278static void
1279compiler_set_lineno(struct compiler *c, int off)
1280{
1281 basicblock *b;
1282 if (c->u->u_lineno_set)
1283 return;
1284 c->u->u_lineno_set = true;
1285 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001286 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287}
1288
1289static int
1290opcode_stack_effect(int opcode, int oparg)
1291{
1292 switch (opcode) {
1293 case POP_TOP:
1294 return -1;
1295 case ROT_TWO:
1296 case ROT_THREE:
1297 return 0;
1298 case DUP_TOP:
1299 return 1;
1300 case ROT_FOUR:
1301 return 0;
1302
1303 case UNARY_POSITIVE:
1304 case UNARY_NEGATIVE:
1305 case UNARY_NOT:
1306 case UNARY_CONVERT:
1307 case UNARY_INVERT:
1308 return 0;
1309
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001310 case LIST_APPEND:
1311 return -2;
1312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313 case BINARY_POWER:
1314 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001315 case BINARY_MODULO:
1316 case BINARY_ADD:
1317 case BINARY_SUBTRACT:
1318 case BINARY_SUBSCR:
1319 case BINARY_FLOOR_DIVIDE:
1320 case BINARY_TRUE_DIVIDE:
1321 return -1;
1322 case INPLACE_FLOOR_DIVIDE:
1323 case INPLACE_TRUE_DIVIDE:
1324 return -1;
1325
1326 case SLICE+0:
1327 return 1;
1328 case SLICE+1:
1329 return 0;
1330 case SLICE+2:
1331 return 0;
1332 case SLICE+3:
1333 return -1;
1334
1335 case STORE_SLICE+0:
1336 return -2;
1337 case STORE_SLICE+1:
1338 return -3;
1339 case STORE_SLICE+2:
1340 return -3;
1341 case STORE_SLICE+3:
1342 return -4;
1343
1344 case DELETE_SLICE+0:
1345 return -1;
1346 case DELETE_SLICE+1:
1347 return -2;
1348 case DELETE_SLICE+2:
1349 return -2;
1350 case DELETE_SLICE+3:
1351 return -3;
1352
1353 case INPLACE_ADD:
1354 case INPLACE_SUBTRACT:
1355 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 case INPLACE_MODULO:
1357 return -1;
1358 case STORE_SUBSCR:
1359 return -3;
1360 case DELETE_SUBSCR:
1361 return -2;
1362
1363 case BINARY_LSHIFT:
1364 case BINARY_RSHIFT:
1365 case BINARY_AND:
1366 case BINARY_XOR:
1367 case BINARY_OR:
1368 return -1;
1369 case INPLACE_POWER:
1370 return -1;
1371 case GET_ITER:
1372 return 0;
1373
1374 case PRINT_EXPR:
1375 return -1;
1376 case PRINT_ITEM:
1377 return -1;
1378 case PRINT_NEWLINE:
1379 return 0;
1380 case PRINT_ITEM_TO:
1381 return -2;
1382 case PRINT_NEWLINE_TO:
1383 return -1;
1384 case INPLACE_LSHIFT:
1385 case INPLACE_RSHIFT:
1386 case INPLACE_AND:
1387 case INPLACE_XOR:
1388 case INPLACE_OR:
1389 return -1;
1390 case BREAK_LOOP:
1391 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001392 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001393 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 case LOAD_LOCALS:
1395 return 1;
1396 case RETURN_VALUE:
1397 return -1;
1398 case IMPORT_STAR:
1399 return -1;
1400 case EXEC_STMT:
1401 return -3;
1402 case YIELD_VALUE:
1403 return 0;
1404
1405 case POP_BLOCK:
1406 return 0;
1407 case END_FINALLY:
1408 return -1; /* or -2 or -3 if exception occurred */
1409 case BUILD_CLASS:
1410 return -2;
1411
1412 case STORE_NAME:
1413 return -1;
1414 case DELETE_NAME:
1415 return 0;
1416 case UNPACK_SEQUENCE:
1417 return oparg-1;
1418 case FOR_ITER:
1419 return 1;
1420
1421 case STORE_ATTR:
1422 return -2;
1423 case DELETE_ATTR:
1424 return -1;
1425 case STORE_GLOBAL:
1426 return -1;
1427 case DELETE_GLOBAL:
1428 return 0;
1429 case DUP_TOPX:
1430 return oparg;
1431 case LOAD_CONST:
1432 return 1;
1433 case LOAD_NAME:
1434 return 1;
1435 case BUILD_TUPLE:
1436 case BUILD_LIST:
1437 return 1-oparg;
1438 case BUILD_MAP:
1439 return 1;
1440 case LOAD_ATTR:
1441 return 0;
1442 case COMPARE_OP:
1443 return -1;
1444 case IMPORT_NAME:
1445 return 0;
1446 case IMPORT_FROM:
1447 return 1;
1448
1449 case JUMP_FORWARD:
1450 case JUMP_IF_FALSE:
1451 case JUMP_IF_TRUE:
1452 case JUMP_ABSOLUTE:
1453 return 0;
1454
1455 case LOAD_GLOBAL:
1456 return 1;
1457
1458 case CONTINUE_LOOP:
1459 return 0;
1460 case SETUP_LOOP:
1461 return 0;
1462 case SETUP_EXCEPT:
1463 case SETUP_FINALLY:
1464 return 3; /* actually pushed by an exception */
1465
1466 case LOAD_FAST:
1467 return 1;
1468 case STORE_FAST:
1469 return -1;
1470 case DELETE_FAST:
1471 return 0;
1472
1473 case RAISE_VARARGS:
1474 return -oparg;
1475#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1476 case CALL_FUNCTION:
1477 return -NARGS(oparg);
1478 case CALL_FUNCTION_VAR:
1479 case CALL_FUNCTION_KW:
1480 return -NARGS(oparg)-1;
1481 case CALL_FUNCTION_VAR_KW:
1482 return -NARGS(oparg)-2;
1483#undef NARGS
1484 case MAKE_FUNCTION:
1485 return -oparg;
1486 case BUILD_SLICE:
1487 if (oparg == 3)
1488 return -2;
1489 else
1490 return -1;
1491
1492 case MAKE_CLOSURE:
1493 return -oparg;
1494 case LOAD_CLOSURE:
1495 return 1;
1496 case LOAD_DEREF:
1497 return 1;
1498 case STORE_DEREF:
1499 return -1;
1500 default:
1501 fprintf(stderr, "opcode = %d\n", opcode);
1502 Py_FatalError("opcode_stack_effect()");
1503
1504 }
1505 return 0; /* not reachable */
1506}
1507
1508/* Add an opcode with no argument.
1509 Returns 0 on failure, 1 on success.
1510*/
1511
1512static int
1513compiler_addop(struct compiler *c, int opcode)
1514{
1515 basicblock *b;
1516 struct instr *i;
1517 int off;
1518 off = compiler_next_instr(c, c->u->u_curblock);
1519 if (off < 0)
1520 return 0;
1521 b = c->u->u_curblock;
1522 i = &b->b_instr[off];
1523 i->i_opcode = opcode;
1524 i->i_hasarg = 0;
1525 if (opcode == RETURN_VALUE)
1526 b->b_return = 1;
1527 compiler_set_lineno(c, off);
1528 return 1;
1529}
1530
1531static int
1532compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1533{
1534 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001535 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001537 /* necessary to make sure types aren't coerced (e.g., int and long) */
1538 t = PyTuple_Pack(2, o, o->ob_type);
1539 if (t == NULL)
1540 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001541
1542 v = PyDict_GetItem(dict, t);
1543 if (!v) {
1544 arg = PyDict_Size(dict);
1545 v = PyInt_FromLong(arg);
1546 if (!v) {
1547 Py_DECREF(t);
1548 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001549 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550 if (PyDict_SetItem(dict, t, v) < 0) {
1551 Py_DECREF(t);
1552 Py_DECREF(v);
1553 return -1;
1554 }
1555 Py_DECREF(v);
1556 }
1557 else
1558 arg = PyInt_AsLong(v);
1559 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001560 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561}
1562
1563static int
1564compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1565 PyObject *o)
1566{
1567 int arg = compiler_add_o(c, dict, o);
1568 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001569 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570 return compiler_addop_i(c, opcode, arg);
1571}
1572
1573static int
1574compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001575 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576{
1577 int arg;
1578 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1579 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001580 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001581 arg = compiler_add_o(c, dict, mangled);
1582 Py_DECREF(mangled);
1583 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001584 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585 return compiler_addop_i(c, opcode, arg);
1586}
1587
1588/* Add an opcode with an integer argument.
1589 Returns 0 on failure, 1 on success.
1590*/
1591
1592static int
1593compiler_addop_i(struct compiler *c, int opcode, int oparg)
1594{
1595 struct instr *i;
1596 int off;
1597 off = compiler_next_instr(c, c->u->u_curblock);
1598 if (off < 0)
1599 return 0;
1600 i = &c->u->u_curblock->b_instr[off];
1601 i->i_opcode = opcode;
1602 i->i_oparg = oparg;
1603 i->i_hasarg = 1;
1604 compiler_set_lineno(c, off);
1605 return 1;
1606}
1607
1608static int
1609compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1610{
1611 struct instr *i;
1612 int off;
1613
1614 assert(b != NULL);
1615 off = compiler_next_instr(c, c->u->u_curblock);
1616 if (off < 0)
1617 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 i = &c->u->u_curblock->b_instr[off];
1619 i->i_opcode = opcode;
1620 i->i_target = b;
1621 i->i_hasarg = 1;
1622 if (absolute)
1623 i->i_jabs = 1;
1624 else
1625 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001626 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001627 return 1;
1628}
1629
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001630/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1631 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632 it as the current block. NEXT_BLOCK() also creates an implicit jump
1633 from the current block to the new block.
1634*/
1635
1636/* XXX The returns inside these macros make it impossible to decref
1637 objects created in the local function.
1638*/
1639
1640
1641#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001642 if (compiler_use_new_block((C)) == NULL) \
1643 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644}
1645
1646#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001647 if (compiler_next_block((C)) == NULL) \
1648 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649}
1650
1651#define ADDOP(C, OP) { \
1652 if (!compiler_addop((C), (OP))) \
1653 return 0; \
1654}
1655
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001656#define ADDOP_IN_SCOPE(C, OP) { \
1657 if (!compiler_addop((C), (OP))) { \
1658 compiler_exit_scope(c); \
1659 return 0; \
1660 } \
1661}
1662
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663#define ADDOP_O(C, OP, O, TYPE) { \
1664 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1665 return 0; \
1666}
1667
1668#define ADDOP_NAME(C, OP, O, TYPE) { \
1669 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1670 return 0; \
1671}
1672
1673#define ADDOP_I(C, OP, O) { \
1674 if (!compiler_addop_i((C), (OP), (O))) \
1675 return 0; \
1676}
1677
1678#define ADDOP_JABS(C, OP, O) { \
1679 if (!compiler_addop_j((C), (OP), (O), 1)) \
1680 return 0; \
1681}
1682
1683#define ADDOP_JREL(C, OP, O) { \
1684 if (!compiler_addop_j((C), (OP), (O), 0)) \
1685 return 0; \
1686}
1687
1688/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1689 the ASDL name to synthesize the name of the C type and the visit function.
1690*/
1691
1692#define VISIT(C, TYPE, V) {\
1693 if (!compiler_visit_ ## TYPE((C), (V))) \
1694 return 0; \
1695}
1696
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001697#define VISIT_IN_SCOPE(C, TYPE, V) {\
1698 if (!compiler_visit_ ## TYPE((C), (V))) { \
1699 compiler_exit_scope(c); \
1700 return 0; \
1701 } \
1702}
1703
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704#define VISIT_SLICE(C, V, CTX) {\
1705 if (!compiler_visit_slice((C), (V), (CTX))) \
1706 return 0; \
1707}
1708
1709#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001710 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001712 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001713 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001714 if (!compiler_visit_ ## TYPE((C), elt)) \
1715 return 0; \
1716 } \
1717}
1718
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001719#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001720 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001721 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001722 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001723 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001724 if (!compiler_visit_ ## TYPE((C), elt)) { \
1725 compiler_exit_scope(c); \
1726 return 0; \
1727 } \
1728 } \
1729}
1730
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001731static int
1732compiler_isdocstring(stmt_ty s)
1733{
1734 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001735 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736 return s->v.Expr.value->kind == Str_kind;
1737}
1738
1739/* Compile a sequence of statements, checking for a docstring. */
1740
1741static int
1742compiler_body(struct compiler *c, asdl_seq *stmts)
1743{
1744 int i = 0;
1745 stmt_ty st;
1746
1747 if (!asdl_seq_LEN(stmts))
1748 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001749 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750 if (compiler_isdocstring(st)) {
1751 i = 1;
1752 VISIT(c, expr, st->v.Expr.value);
1753 if (!compiler_nameop(c, __doc__, Store))
1754 return 0;
1755 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001756 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001757 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758 return 1;
1759}
1760
1761static PyCodeObject *
1762compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001763{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001764 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001765 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 static PyObject *module;
1767 if (!module) {
1768 module = PyString_FromString("<module>");
1769 if (!module)
1770 return NULL;
1771 }
1772 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001773 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 switch (mod->kind) {
1775 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001776 if (!compiler_body(c, mod->v.Module.body)) {
1777 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001779 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 break;
1781 case Interactive_kind:
1782 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001783 VISIT_SEQ_IN_SCOPE(c, stmt,
1784 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 break;
1786 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001787 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001788 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 break;
1790 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001791 PyErr_SetString(PyExc_SystemError,
1792 "suite should not be possible");
1793 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001794 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001795 PyErr_Format(PyExc_SystemError,
1796 "module kind %d should not be possible",
1797 mod->kind);
1798 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 co = assemble(c, addNone);
1801 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001802 return co;
1803}
1804
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805/* The test for LOCAL must come before the test for FREE in order to
1806 handle classes where name is both local and free. The local var is
1807 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001808*/
1809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810static int
1811get_ref_type(struct compiler *c, PyObject *name)
1812{
1813 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001814 if (scope == 0) {
1815 char buf[350];
1816 PyOS_snprintf(buf, sizeof(buf),
1817 "unknown scope for %.100s in %.100s(%s) in %s\n"
1818 "symbols: %s\nlocals: %s\nglobals: %s\n",
1819 PyString_AS_STRING(name),
1820 PyString_AS_STRING(c->u->u_name),
1821 PyObject_REPR(c->u->u_ste->ste_id),
1822 c->c_filename,
1823 PyObject_REPR(c->u->u_ste->ste_symbols),
1824 PyObject_REPR(c->u->u_varnames),
1825 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001827 Py_FatalError(buf);
1828 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001829
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001830 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831}
1832
1833static int
1834compiler_lookup_arg(PyObject *dict, PyObject *name)
1835{
1836 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001837 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001839 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001841 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001843 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 return PyInt_AS_LONG(v);
1845}
1846
1847static int
1848compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1849{
1850 int i, free = PyCode_GetNumFree(co);
1851 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001852 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1853 ADDOP_I(c, MAKE_FUNCTION, args);
1854 return 1;
1855 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856 for (i = 0; i < free; ++i) {
1857 /* Bypass com_addop_varname because it will generate
1858 LOAD_DEREF but LOAD_CLOSURE is needed.
1859 */
1860 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1861 int arg, reftype;
1862
1863 /* Special case: If a class contains a method with a
1864 free variable that has the same name as a method,
1865 the name will be considered free *and* local in the
1866 class. It should be handled by the closure, as
1867 well as by the normal name loookup logic.
1868 */
1869 reftype = get_ref_type(c, name);
1870 if (reftype == CELL)
1871 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1872 else /* (reftype == FREE) */
1873 arg = compiler_lookup_arg(c->u->u_freevars, name);
1874 if (arg == -1) {
1875 printf("lookup %s in %s %d %d\n"
1876 "freevars of %s: %s\n",
1877 PyObject_REPR(name),
1878 PyString_AS_STRING(c->u->u_name),
1879 reftype, arg,
1880 PyString_AS_STRING(co->co_name),
1881 PyObject_REPR(co->co_freevars));
1882 Py_FatalError("compiler_make_closure()");
1883 }
1884 ADDOP_I(c, LOAD_CLOSURE, arg);
1885 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001886 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001888 ADDOP_I(c, MAKE_CLOSURE, args);
1889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890}
1891
1892static int
1893compiler_decorators(struct compiler *c, asdl_seq* decos)
1894{
1895 int i;
1896
1897 if (!decos)
1898 return 1;
1899
1900 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001901 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902 }
1903 return 1;
1904}
1905
1906static int
1907compiler_arguments(struct compiler *c, arguments_ty args)
1908{
1909 int i;
1910 int n = asdl_seq_LEN(args->args);
1911 /* Correctly handle nested argument lists */
1912 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001913 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 if (arg->kind == Tuple_kind) {
1915 PyObject *id = PyString_FromFormat(".%d", i);
1916 if (id == NULL) {
1917 return 0;
1918 }
1919 if (!compiler_nameop(c, id, Load)) {
1920 Py_DECREF(id);
1921 return 0;
1922 }
1923 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001924 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925 }
1926 }
1927 return 1;
1928}
1929
1930static int
1931compiler_function(struct compiler *c, stmt_ty s)
1932{
1933 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001934 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935 arguments_ty args = s->v.FunctionDef.args;
1936 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001937 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938 int i, n, docstring;
1939
1940 assert(s->kind == FunctionDef_kind);
1941
1942 if (!compiler_decorators(c, decos))
1943 return 0;
1944 if (args->defaults)
1945 VISIT_SEQ(c, expr, args->defaults);
1946 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1947 s->lineno))
1948 return 0;
1949
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001950 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001951 docstring = compiler_isdocstring(st);
1952 if (docstring)
1953 first_const = st->v.Expr.value->v.Str.s;
1954 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001955 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001956 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001957 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960 compiler_arguments(c, args);
1961
1962 c->u->u_argcount = asdl_seq_LEN(args->args);
1963 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001964 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 for (i = docstring; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001966 stmt_ty s2 = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 if (i == 0 && s2->kind == Expr_kind &&
1968 s2->v.Expr.value->kind == Str_kind)
1969 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001970 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971 }
1972 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001973 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974 if (co == NULL)
1975 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001977 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001978 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
1980 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1981 ADDOP_I(c, CALL_FUNCTION, 1);
1982 }
1983
1984 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1985}
1986
1987static int
1988compiler_class(struct compiler *c, stmt_ty s)
1989{
1990 int n;
1991 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001992 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 /* push class name on stack, needed by BUILD_CLASS */
1994 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1995 /* push the tuple of base classes on the stack */
1996 n = asdl_seq_LEN(s->v.ClassDef.bases);
1997 if (n > 0)
1998 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1999 ADDOP_I(c, BUILD_TUPLE, n);
2000 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2001 s->lineno))
2002 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002003 c->u->u_private = s->v.ClassDef.name;
2004 Py_INCREF(c->u->u_private);
2005 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006 if (!str || !compiler_nameop(c, str, Load)) {
2007 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002008 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002010 }
2011
2012 Py_DECREF(str);
2013 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 if (!str || !compiler_nameop(c, str, Store)) {
2015 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002016 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002018 }
2019 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002021 if (!compiler_body(c, s->v.ClassDef.body)) {
2022 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002024 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002026 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2027 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002029 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030 if (co == NULL)
2031 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002033 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002034 Py_DECREF(co);
2035
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 ADDOP_I(c, CALL_FUNCTION, 0);
2037 ADDOP(c, BUILD_CLASS);
2038 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2039 return 0;
2040 return 1;
2041}
2042
2043static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002044compiler_ifexp(struct compiler *c, expr_ty e)
2045{
2046 basicblock *end, *next;
2047
2048 assert(e->kind == IfExp_kind);
2049 end = compiler_new_block(c);
2050 if (end == NULL)
2051 return 0;
2052 next = compiler_new_block(c);
2053 if (next == NULL)
2054 return 0;
2055 VISIT(c, expr, e->v.IfExp.test);
2056 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2057 ADDOP(c, POP_TOP);
2058 VISIT(c, expr, e->v.IfExp.body);
2059 ADDOP_JREL(c, JUMP_FORWARD, end);
2060 compiler_use_next_block(c, next);
2061 ADDOP(c, POP_TOP);
2062 VISIT(c, expr, e->v.IfExp.orelse);
2063 compiler_use_next_block(c, end);
2064 return 1;
2065}
2066
2067static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068compiler_lambda(struct compiler *c, expr_ty e)
2069{
2070 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002071 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 arguments_ty args = e->v.Lambda.args;
2073 assert(e->kind == Lambda_kind);
2074
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002075 if (!name) {
2076 name = PyString_InternFromString("<lambda>");
2077 if (!name)
2078 return 0;
2079 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080
2081 if (args->defaults)
2082 VISIT_SEQ(c, expr, args->defaults);
2083 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2084 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002085
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002086 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 compiler_arguments(c, args);
2088
2089 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002090 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2091 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002093 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094 if (co == NULL)
2095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002097 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002098 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002099
2100 return 1;
2101}
2102
2103static int
2104compiler_print(struct compiler *c, stmt_ty s)
2105{
2106 int i, n;
2107 bool dest;
2108
2109 assert(s->kind == Print_kind);
2110 n = asdl_seq_LEN(s->v.Print.values);
2111 dest = false;
2112 if (s->v.Print.dest) {
2113 VISIT(c, expr, s->v.Print.dest);
2114 dest = true;
2115 }
2116 for (i = 0; i < n; i++) {
2117 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2118 if (dest) {
2119 ADDOP(c, DUP_TOP);
2120 VISIT(c, expr, e);
2121 ADDOP(c, ROT_TWO);
2122 ADDOP(c, PRINT_ITEM_TO);
2123 }
2124 else {
2125 VISIT(c, expr, e);
2126 ADDOP(c, PRINT_ITEM);
2127 }
2128 }
2129 if (s->v.Print.nl) {
2130 if (dest)
2131 ADDOP(c, PRINT_NEWLINE_TO)
2132 else
2133 ADDOP(c, PRINT_NEWLINE)
2134 }
2135 else if (dest)
2136 ADDOP(c, POP_TOP);
2137 return 1;
2138}
2139
2140static int
2141compiler_if(struct compiler *c, stmt_ty s)
2142{
2143 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002144 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 assert(s->kind == If_kind);
2146 end = compiler_new_block(c);
2147 if (end == NULL)
2148 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002149 next = compiler_new_block(c);
2150 if (next == NULL)
2151 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002152
2153 constant = expr_constant(s->v.If.test);
2154 /* constant = 0: "if 0"
2155 * constant = 1: "if 1", "if 2", ...
2156 * constant = -1: rest */
2157 if (constant == 0) {
2158 if (s->v.If.orelse)
2159 VISIT_SEQ(c, stmt, s->v.If.orelse);
2160 } else if (constant == 1) {
2161 VISIT_SEQ(c, stmt, s->v.If.body);
2162 } else {
2163 VISIT(c, expr, s->v.If.test);
2164 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2165 ADDOP(c, POP_TOP);
2166 VISIT_SEQ(c, stmt, s->v.If.body);
2167 ADDOP_JREL(c, JUMP_FORWARD, end);
2168 compiler_use_next_block(c, next);
2169 ADDOP(c, POP_TOP);
2170 if (s->v.If.orelse)
2171 VISIT_SEQ(c, stmt, s->v.If.orelse);
2172 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002173 compiler_use_next_block(c, end);
2174 return 1;
2175}
2176
2177static int
2178compiler_for(struct compiler *c, stmt_ty s)
2179{
2180 basicblock *start, *cleanup, *end;
2181
2182 start = compiler_new_block(c);
2183 cleanup = compiler_new_block(c);
2184 end = compiler_new_block(c);
2185 if (start == NULL || end == NULL || cleanup == NULL)
2186 return 0;
2187 ADDOP_JREL(c, SETUP_LOOP, end);
2188 if (!compiler_push_fblock(c, LOOP, start))
2189 return 0;
2190 VISIT(c, expr, s->v.For.iter);
2191 ADDOP(c, GET_ITER);
2192 compiler_use_next_block(c, start);
2193 ADDOP_JREL(c, FOR_ITER, cleanup);
2194 VISIT(c, expr, s->v.For.target);
2195 VISIT_SEQ(c, stmt, s->v.For.body);
2196 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2197 compiler_use_next_block(c, cleanup);
2198 ADDOP(c, POP_BLOCK);
2199 compiler_pop_fblock(c, LOOP, start);
2200 VISIT_SEQ(c, stmt, s->v.For.orelse);
2201 compiler_use_next_block(c, end);
2202 return 1;
2203}
2204
2205static int
2206compiler_while(struct compiler *c, stmt_ty s)
2207{
2208 basicblock *loop, *orelse, *end, *anchor = NULL;
2209 int constant = expr_constant(s->v.While.test);
2210
2211 if (constant == 0)
2212 return 1;
2213 loop = compiler_new_block(c);
2214 end = compiler_new_block(c);
2215 if (constant == -1) {
2216 anchor = compiler_new_block(c);
2217 if (anchor == NULL)
2218 return 0;
2219 }
2220 if (loop == NULL || end == NULL)
2221 return 0;
2222 if (s->v.While.orelse) {
2223 orelse = compiler_new_block(c);
2224 if (orelse == NULL)
2225 return 0;
2226 }
2227 else
2228 orelse = NULL;
2229
2230 ADDOP_JREL(c, SETUP_LOOP, end);
2231 compiler_use_next_block(c, loop);
2232 if (!compiler_push_fblock(c, LOOP, loop))
2233 return 0;
2234 if (constant == -1) {
2235 VISIT(c, expr, s->v.While.test);
2236 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2237 ADDOP(c, POP_TOP);
2238 }
2239 VISIT_SEQ(c, stmt, s->v.While.body);
2240 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2241
2242 /* XXX should the two POP instructions be in a separate block
2243 if there is no else clause ?
2244 */
2245
2246 if (constant == -1) {
2247 compiler_use_next_block(c, anchor);
2248 ADDOP(c, POP_TOP);
2249 ADDOP(c, POP_BLOCK);
2250 }
2251 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002252 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 VISIT_SEQ(c, stmt, s->v.While.orelse);
2254 compiler_use_next_block(c, end);
2255
2256 return 1;
2257}
2258
2259static int
2260compiler_continue(struct compiler *c)
2261{
2262 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2263 int i;
2264
2265 if (!c->u->u_nfblocks)
2266 return compiler_error(c, LOOP_ERROR_MSG);
2267 i = c->u->u_nfblocks - 1;
2268 switch (c->u->u_fblock[i].fb_type) {
2269 case LOOP:
2270 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2271 break;
2272 case EXCEPT:
2273 case FINALLY_TRY:
2274 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2275 ;
2276 if (i == -1)
2277 return compiler_error(c, LOOP_ERROR_MSG);
2278 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2279 break;
2280 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002281 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 "'continue' not supported inside 'finally' clause");
2283 }
2284
2285 return 1;
2286}
2287
2288/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2289
2290 SETUP_FINALLY L
2291 <code for body>
2292 POP_BLOCK
2293 LOAD_CONST <None>
2294 L: <code for finalbody>
2295 END_FINALLY
2296
2297 The special instructions use the block stack. Each block
2298 stack entry contains the instruction that created it (here
2299 SETUP_FINALLY), the level of the value stack at the time the
2300 block stack entry was created, and a label (here L).
2301
2302 SETUP_FINALLY:
2303 Pushes the current value stack level and the label
2304 onto the block stack.
2305 POP_BLOCK:
2306 Pops en entry from the block stack, and pops the value
2307 stack until its level is the same as indicated on the
2308 block stack. (The label is ignored.)
2309 END_FINALLY:
2310 Pops a variable number of entries from the *value* stack
2311 and re-raises the exception they specify. The number of
2312 entries popped depends on the (pseudo) exception type.
2313
2314 The block stack is unwound when an exception is raised:
2315 when a SETUP_FINALLY entry is found, the exception is pushed
2316 onto the value stack (and the exception condition is cleared),
2317 and the interpreter jumps to the label gotten from the block
2318 stack.
2319*/
2320
2321static int
2322compiler_try_finally(struct compiler *c, stmt_ty s)
2323{
2324 basicblock *body, *end;
2325 body = compiler_new_block(c);
2326 end = compiler_new_block(c);
2327 if (body == NULL || end == NULL)
2328 return 0;
2329
2330 ADDOP_JREL(c, SETUP_FINALLY, end);
2331 compiler_use_next_block(c, body);
2332 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2333 return 0;
2334 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2335 ADDOP(c, POP_BLOCK);
2336 compiler_pop_fblock(c, FINALLY_TRY, body);
2337
2338 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2339 compiler_use_next_block(c, end);
2340 if (!compiler_push_fblock(c, FINALLY_END, end))
2341 return 0;
2342 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2343 ADDOP(c, END_FINALLY);
2344 compiler_pop_fblock(c, FINALLY_END, end);
2345
2346 return 1;
2347}
2348
2349/*
2350 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2351 (The contents of the value stack is shown in [], with the top
2352 at the right; 'tb' is trace-back info, 'val' the exception's
2353 associated value, and 'exc' the exception.)
2354
2355 Value stack Label Instruction Argument
2356 [] SETUP_EXCEPT L1
2357 [] <code for S>
2358 [] POP_BLOCK
2359 [] JUMP_FORWARD L0
2360
2361 [tb, val, exc] L1: DUP )
2362 [tb, val, exc, exc] <evaluate E1> )
2363 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2364 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2365 [tb, val, exc, 1] POP )
2366 [tb, val, exc] POP
2367 [tb, val] <assign to V1> (or POP if no V1)
2368 [tb] POP
2369 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002370 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371
2372 [tb, val, exc, 0] L2: POP
2373 [tb, val, exc] DUP
2374 .............................etc.......................
2375
2376 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002377 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378
2379 [] L0: <next statement>
2380
2381 Of course, parts are not generated if Vi or Ei is not present.
2382*/
2383static int
2384compiler_try_except(struct compiler *c, stmt_ty s)
2385{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002386 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002387 int i, n;
2388
2389 body = compiler_new_block(c);
2390 except = compiler_new_block(c);
2391 orelse = compiler_new_block(c);
2392 end = compiler_new_block(c);
2393 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2394 return 0;
2395 ADDOP_JREL(c, SETUP_EXCEPT, except);
2396 compiler_use_next_block(c, body);
2397 if (!compiler_push_fblock(c, EXCEPT, body))
2398 return 0;
2399 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2400 ADDOP(c, POP_BLOCK);
2401 compiler_pop_fblock(c, EXCEPT, body);
2402 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2403 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2404 compiler_use_next_block(c, except);
2405 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002406 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 s->v.TryExcept.handlers, i);
2408 if (!handler->type && i < n-1)
2409 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002410 c->u->u_lineno_set = false;
2411 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412 except = compiler_new_block(c);
2413 if (except == NULL)
2414 return 0;
2415 if (handler->type) {
2416 ADDOP(c, DUP_TOP);
2417 VISIT(c, expr, handler->type);
2418 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2419 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2420 ADDOP(c, POP_TOP);
2421 }
2422 ADDOP(c, POP_TOP);
2423 if (handler->name) {
2424 VISIT(c, expr, handler->name);
2425 }
2426 else {
2427 ADDOP(c, POP_TOP);
2428 }
2429 ADDOP(c, POP_TOP);
2430 VISIT_SEQ(c, stmt, handler->body);
2431 ADDOP_JREL(c, JUMP_FORWARD, end);
2432 compiler_use_next_block(c, except);
2433 if (handler->type)
2434 ADDOP(c, POP_TOP);
2435 }
2436 ADDOP(c, END_FINALLY);
2437 compiler_use_next_block(c, orelse);
2438 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2439 compiler_use_next_block(c, end);
2440 return 1;
2441}
2442
2443static int
2444compiler_import_as(struct compiler *c, identifier name, identifier asname)
2445{
2446 /* The IMPORT_NAME opcode was already generated. This function
2447 merely needs to bind the result to a name.
2448
2449 If there is a dot in name, we need to split it and emit a
2450 LOAD_ATTR for each name.
2451 */
2452 const char *src = PyString_AS_STRING(name);
2453 const char *dot = strchr(src, '.');
2454 if (dot) {
2455 /* Consume the base module name to get the first attribute */
2456 src = dot + 1;
2457 while (dot) {
2458 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002459 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002461 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002463 if (!attr)
2464 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002466 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 src = dot + 1;
2468 }
2469 }
2470 return compiler_nameop(c, asname, Store);
2471}
2472
2473static int
2474compiler_import(struct compiler *c, stmt_ty s)
2475{
2476 /* The Import node stores a module name like a.b.c as a single
2477 string. This is convenient for all cases except
2478 import a.b.c as d
2479 where we need to parse that string to extract the individual
2480 module names.
2481 XXX Perhaps change the representation to make this case simpler?
2482 */
2483 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002485 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002486 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002487 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002488 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489
Guido van Rossum45aecf42006-03-15 04:58:47 +00002490 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002491 if (level == NULL)
2492 return 0;
2493
2494 ADDOP_O(c, LOAD_CONST, level, consts);
2495 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2497 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2498
2499 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002500 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002501 if (!r)
2502 return r;
2503 }
2504 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002505 identifier tmp = alias->name;
2506 const char *base = PyString_AS_STRING(alias->name);
2507 char *dot = strchr(base, '.');
2508 if (dot)
2509 tmp = PyString_FromStringAndSize(base,
2510 dot - base);
2511 r = compiler_nameop(c, tmp, Store);
2512 if (dot) {
2513 Py_DECREF(tmp);
2514 }
2515 if (!r)
2516 return r;
2517 }
2518 }
2519 return 1;
2520}
2521
2522static int
2523compiler_from_import(struct compiler *c, stmt_ty s)
2524{
2525 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526
2527 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002528 PyObject *level;
2529
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 if (!names)
2531 return 0;
2532
Guido van Rossum45aecf42006-03-15 04:58:47 +00002533 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002534 if (!level) {
2535 Py_DECREF(names);
2536 return 0;
2537 }
2538
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 /* build up the names */
2540 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002541 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 Py_INCREF(alias->name);
2543 PyTuple_SET_ITEM(names, i, alias->name);
2544 }
2545
2546 if (s->lineno > c->c_future->ff_lineno) {
2547 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2548 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002549 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 Py_DECREF(names);
2551 return compiler_error(c,
2552 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002553 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554
2555 }
2556 }
2557
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002558 ADDOP_O(c, LOAD_CONST, level, consts);
2559 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002561 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2563 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002564 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565 identifier store_name;
2566
2567 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2568 assert(n == 1);
2569 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002570 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 }
2572
2573 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2574 store_name = alias->name;
2575 if (alias->asname)
2576 store_name = alias->asname;
2577
2578 if (!compiler_nameop(c, store_name, Store)) {
2579 Py_DECREF(names);
2580 return 0;
2581 }
2582 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002583 /* remove imported module */
2584 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 return 1;
2586}
2587
2588static int
2589compiler_assert(struct compiler *c, stmt_ty s)
2590{
2591 static PyObject *assertion_error = NULL;
2592 basicblock *end;
2593
2594 if (Py_OptimizeFlag)
2595 return 1;
2596 if (assertion_error == NULL) {
2597 assertion_error = PyString_FromString("AssertionError");
2598 if (assertion_error == NULL)
2599 return 0;
2600 }
2601 VISIT(c, expr, s->v.Assert.test);
2602 end = compiler_new_block(c);
2603 if (end == NULL)
2604 return 0;
2605 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2606 ADDOP(c, POP_TOP);
2607 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2608 if (s->v.Assert.msg) {
2609 VISIT(c, expr, s->v.Assert.msg);
2610 ADDOP_I(c, RAISE_VARARGS, 2);
2611 }
2612 else {
2613 ADDOP_I(c, RAISE_VARARGS, 1);
2614 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002615 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 ADDOP(c, POP_TOP);
2617 return 1;
2618}
2619
2620static int
2621compiler_visit_stmt(struct compiler *c, stmt_ty s)
2622{
2623 int i, n;
2624
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002625 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002626 c->u->u_lineno = s->lineno;
2627 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002628
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 if (c->u->u_ste->ste_type != FunctionBlock)
2636 return compiler_error(c, "'return' outside function");
2637 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 VISIT(c, expr, s->v.Return.value);
2639 }
2640 else
2641 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2642 ADDOP(c, RETURN_VALUE);
2643 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 VISIT_SEQ(c, expr, s->v.Delete.targets)
2646 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 n = asdl_seq_LEN(s->v.Assign.targets);
2649 VISIT(c, expr, s->v.Assign.value);
2650 for (i = 0; i < n; i++) {
2651 if (i < n - 1)
2652 ADDOP(c, DUP_TOP);
2653 VISIT(c, expr,
2654 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2655 }
2656 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 n = 0;
2669 if (s->v.Raise.type) {
2670 VISIT(c, expr, s->v.Raise.type);
2671 n++;
2672 if (s->v.Raise.inst) {
2673 VISIT(c, expr, s->v.Raise.inst);
2674 n++;
2675 if (s->v.Raise.tback) {
2676 VISIT(c, expr, s->v.Raise.tback);
2677 n++;
2678 }
2679 }
2680 }
2681 ADDOP_I(c, RAISE_VARARGS, n);
2682 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 VISIT(c, expr, s->v.Exec.body);
2695 if (s->v.Exec.globals) {
2696 VISIT(c, expr, s->v.Exec.globals);
2697 if (s->v.Exec.locals) {
2698 VISIT(c, expr, s->v.Exec.locals);
2699 } else {
2700 ADDOP(c, DUP_TOP);
2701 }
2702 } else {
2703 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2704 ADDOP(c, DUP_TOP);
2705 }
2706 ADDOP(c, EXEC_STMT);
2707 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 VISIT(c, expr, s->v.Expr.value);
2712 if (c->c_interactive && c->c_nestlevel <= 1) {
2713 ADDOP(c, PRINT_EXPR);
2714 }
2715 else {
2716 ADDOP(c, POP_TOP);
2717 }
2718 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002721 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 if (!c->u->u_nfblocks)
2723 return compiler_error(c, "'break' outside loop");
2724 ADDOP(c, BREAK_LOOP);
2725 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002726 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002728 case With_kind:
2729 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730 }
2731 return 1;
2732}
2733
2734static int
2735unaryop(unaryop_ty op)
2736{
2737 switch (op) {
2738 case Invert:
2739 return UNARY_INVERT;
2740 case Not:
2741 return UNARY_NOT;
2742 case UAdd:
2743 return UNARY_POSITIVE;
2744 case USub:
2745 return UNARY_NEGATIVE;
2746 }
2747 return 0;
2748}
2749
2750static int
2751binop(struct compiler *c, operator_ty op)
2752{
2753 switch (op) {
2754 case Add:
2755 return BINARY_ADD;
2756 case Sub:
2757 return BINARY_SUBTRACT;
2758 case Mult:
2759 return BINARY_MULTIPLY;
2760 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002761 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762 case Mod:
2763 return BINARY_MODULO;
2764 case Pow:
2765 return BINARY_POWER;
2766 case LShift:
2767 return BINARY_LSHIFT;
2768 case RShift:
2769 return BINARY_RSHIFT;
2770 case BitOr:
2771 return BINARY_OR;
2772 case BitXor:
2773 return BINARY_XOR;
2774 case BitAnd:
2775 return BINARY_AND;
2776 case FloorDiv:
2777 return BINARY_FLOOR_DIVIDE;
2778 }
2779 return 0;
2780}
2781
2782static int
2783cmpop(cmpop_ty op)
2784{
2785 switch (op) {
2786 case Eq:
2787 return PyCmp_EQ;
2788 case NotEq:
2789 return PyCmp_NE;
2790 case Lt:
2791 return PyCmp_LT;
2792 case LtE:
2793 return PyCmp_LE;
2794 case Gt:
2795 return PyCmp_GT;
2796 case GtE:
2797 return PyCmp_GE;
2798 case Is:
2799 return PyCmp_IS;
2800 case IsNot:
2801 return PyCmp_IS_NOT;
2802 case In:
2803 return PyCmp_IN;
2804 case NotIn:
2805 return PyCmp_NOT_IN;
2806 }
2807 return PyCmp_BAD;
2808}
2809
2810static int
2811inplace_binop(struct compiler *c, operator_ty op)
2812{
2813 switch (op) {
2814 case Add:
2815 return INPLACE_ADD;
2816 case Sub:
2817 return INPLACE_SUBTRACT;
2818 case Mult:
2819 return INPLACE_MULTIPLY;
2820 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002821 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002822 case Mod:
2823 return INPLACE_MODULO;
2824 case Pow:
2825 return INPLACE_POWER;
2826 case LShift:
2827 return INPLACE_LSHIFT;
2828 case RShift:
2829 return INPLACE_RSHIFT;
2830 case BitOr:
2831 return INPLACE_OR;
2832 case BitXor:
2833 return INPLACE_XOR;
2834 case BitAnd:
2835 return INPLACE_AND;
2836 case FloorDiv:
2837 return INPLACE_FLOOR_DIVIDE;
2838 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002839 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002840 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841 return 0;
2842}
2843
2844static int
2845compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2846{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002847 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2849
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002850 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002851 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852 /* XXX AugStore isn't used anywhere! */
2853
2854 /* First check for assignment to __debug__. Param? */
2855 if ((ctx == Store || ctx == AugStore || ctx == Del)
2856 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2857 return compiler_error(c, "can not assign to __debug__");
2858 }
2859
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002860 mangled = _Py_Mangle(c->u->u_private, name);
2861 if (!mangled)
2862 return 0;
2863
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 op = 0;
2865 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002866 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002867 switch (scope) {
2868 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002869 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870 optype = OP_DEREF;
2871 break;
2872 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 optype = OP_DEREF;
2875 break;
2876 case LOCAL:
2877 if (c->u->u_ste->ste_type == FunctionBlock)
2878 optype = OP_FAST;
2879 break;
2880 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002881 if (c->u->u_ste->ste_type == FunctionBlock &&
2882 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 optype = OP_GLOBAL;
2884 break;
2885 case GLOBAL_EXPLICIT:
2886 optype = OP_GLOBAL;
2887 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002888 default:
2889 /* scope can be 0 */
2890 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002891 }
2892
2893 /* XXX Leave assert here, but handle __doc__ and the like better */
2894 assert(scope || PyString_AS_STRING(name)[0] == '_');
2895
2896 switch (optype) {
2897 case OP_DEREF:
2898 switch (ctx) {
2899 case Load: op = LOAD_DEREF; break;
2900 case Store: op = STORE_DEREF; break;
2901 case AugLoad:
2902 case AugStore:
2903 break;
2904 case Del:
2905 PyErr_Format(PyExc_SyntaxError,
2906 "can not delete variable '%s' referenced "
2907 "in nested scope",
2908 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002909 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002911 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002912 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002913 PyErr_SetString(PyExc_SystemError,
2914 "param invalid for deref variable");
2915 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002916 }
2917 break;
2918 case OP_FAST:
2919 switch (ctx) {
2920 case Load: op = LOAD_FAST; break;
2921 case Store: op = STORE_FAST; break;
2922 case Del: op = DELETE_FAST; break;
2923 case AugLoad:
2924 case AugStore:
2925 break;
2926 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002927 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002928 PyErr_SetString(PyExc_SystemError,
2929 "param invalid for local variable");
2930 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002932 ADDOP_O(c, op, mangled, varnames);
2933 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 return 1;
2935 case OP_GLOBAL:
2936 switch (ctx) {
2937 case Load: op = LOAD_GLOBAL; break;
2938 case Store: op = STORE_GLOBAL; break;
2939 case Del: op = DELETE_GLOBAL; break;
2940 case AugLoad:
2941 case AugStore:
2942 break;
2943 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002944 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002945 PyErr_SetString(PyExc_SystemError,
2946 "param invalid for global variable");
2947 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 }
2949 break;
2950 case OP_NAME:
2951 switch (ctx) {
2952 case Load: op = LOAD_NAME; break;
2953 case Store: op = STORE_NAME; break;
2954 case Del: op = DELETE_NAME; break;
2955 case AugLoad:
2956 case AugStore:
2957 break;
2958 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002959 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002960 PyErr_SetString(PyExc_SystemError,
2961 "param invalid for name variable");
2962 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 }
2964 break;
2965 }
2966
2967 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002968 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002969 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002970 if (arg < 0)
2971 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002972 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973}
2974
2975static int
2976compiler_boolop(struct compiler *c, expr_ty e)
2977{
2978 basicblock *end;
2979 int jumpi, i, n;
2980 asdl_seq *s;
2981
2982 assert(e->kind == BoolOp_kind);
2983 if (e->v.BoolOp.op == And)
2984 jumpi = JUMP_IF_FALSE;
2985 else
2986 jumpi = JUMP_IF_TRUE;
2987 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002988 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989 return 0;
2990 s = e->v.BoolOp.values;
2991 n = asdl_seq_LEN(s) - 1;
2992 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002993 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994 ADDOP_JREL(c, jumpi, end);
2995 ADDOP(c, POP_TOP)
2996 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002997 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002998 compiler_use_next_block(c, end);
2999 return 1;
3000}
3001
3002static int
3003compiler_list(struct compiler *c, expr_ty e)
3004{
3005 int n = asdl_seq_LEN(e->v.List.elts);
3006 if (e->v.List.ctx == Store) {
3007 ADDOP_I(c, UNPACK_SEQUENCE, n);
3008 }
3009 VISIT_SEQ(c, expr, e->v.List.elts);
3010 if (e->v.List.ctx == Load) {
3011 ADDOP_I(c, BUILD_LIST, n);
3012 }
3013 return 1;
3014}
3015
3016static int
3017compiler_tuple(struct compiler *c, expr_ty e)
3018{
3019 int n = asdl_seq_LEN(e->v.Tuple.elts);
3020 if (e->v.Tuple.ctx == Store) {
3021 ADDOP_I(c, UNPACK_SEQUENCE, n);
3022 }
3023 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3024 if (e->v.Tuple.ctx == Load) {
3025 ADDOP_I(c, BUILD_TUPLE, n);
3026 }
3027 return 1;
3028}
3029
3030static int
3031compiler_compare(struct compiler *c, expr_ty e)
3032{
3033 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003034 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035
3036 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3037 VISIT(c, expr, e->v.Compare.left);
3038 n = asdl_seq_LEN(e->v.Compare.ops);
3039 assert(n > 0);
3040 if (n > 1) {
3041 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003042 if (cleanup == NULL)
3043 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003044 VISIT(c, expr,
3045 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046 }
3047 for (i = 1; i < n; i++) {
3048 ADDOP(c, DUP_TOP);
3049 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003051 cmpop((cmpop_ty)(asdl_seq_GET(
3052 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3054 NEXT_BLOCK(c);
3055 ADDOP(c, POP_TOP);
3056 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003057 VISIT(c, expr,
3058 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003060 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003061 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003062 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003063 if (n > 1) {
3064 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 if (end == NULL)
3066 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067 ADDOP_JREL(c, JUMP_FORWARD, end);
3068 compiler_use_next_block(c, cleanup);
3069 ADDOP(c, ROT_TWO);
3070 ADDOP(c, POP_TOP);
3071 compiler_use_next_block(c, end);
3072 }
3073 return 1;
3074}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003075#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076
3077static int
3078compiler_call(struct compiler *c, expr_ty e)
3079{
3080 int n, code = 0;
3081
3082 VISIT(c, expr, e->v.Call.func);
3083 n = asdl_seq_LEN(e->v.Call.args);
3084 VISIT_SEQ(c, expr, e->v.Call.args);
3085 if (e->v.Call.keywords) {
3086 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3087 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3088 }
3089 if (e->v.Call.starargs) {
3090 VISIT(c, expr, e->v.Call.starargs);
3091 code |= 1;
3092 }
3093 if (e->v.Call.kwargs) {
3094 VISIT(c, expr, e->v.Call.kwargs);
3095 code |= 2;
3096 }
3097 switch (code) {
3098 case 0:
3099 ADDOP_I(c, CALL_FUNCTION, n);
3100 break;
3101 case 1:
3102 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3103 break;
3104 case 2:
3105 ADDOP_I(c, CALL_FUNCTION_KW, n);
3106 break;
3107 case 3:
3108 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3109 break;
3110 }
3111 return 1;
3112}
3113
3114static int
3115compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 asdl_seq *generators, int gen_index,
3117 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118{
3119 /* generate code for the iterator, then each of the ifs,
3120 and then write to the element */
3121
3122 comprehension_ty l;
3123 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003124 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003125
3126 start = compiler_new_block(c);
3127 skip = compiler_new_block(c);
3128 if_cleanup = compiler_new_block(c);
3129 anchor = compiler_new_block(c);
3130
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003131 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3132 anchor == NULL)
3133 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003134
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003135 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 VISIT(c, expr, l->iter);
3137 ADDOP(c, GET_ITER);
3138 compiler_use_next_block(c, start);
3139 ADDOP_JREL(c, FOR_ITER, anchor);
3140 NEXT_BLOCK(c);
3141 VISIT(c, expr, l->target);
3142
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003143 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 n = asdl_seq_LEN(l->ifs);
3145 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003146 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147 VISIT(c, expr, e);
3148 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3149 NEXT_BLOCK(c);
3150 ADDOP(c, POP_TOP);
3151 }
3152
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003153 if (++gen_index < asdl_seq_LEN(generators))
3154 if (!compiler_listcomp_generator(c, tmpname,
3155 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 /* only append after the last for generator */
3159 if (gen_index >= asdl_seq_LEN(generators)) {
3160 if (!compiler_nameop(c, tmpname, Load))
3161 return 0;
3162 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003163 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164
3165 compiler_use_next_block(c, skip);
3166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167 for (i = 0; i < n; i++) {
3168 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 if (i == 0)
3170 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171 ADDOP(c, POP_TOP);
3172 }
3173 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3174 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 return 0;
3179
3180 return 1;
3181}
3182
3183static int
3184compiler_listcomp(struct compiler *c, expr_ty e)
3185{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003187 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 static identifier append;
3189 asdl_seq *generators = e->v.ListComp.generators;
3190
3191 assert(e->kind == ListComp_kind);
3192 if (!append) {
3193 append = PyString_InternFromString("append");
3194 if (!append)
3195 return 0;
3196 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003197 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 if (!tmp)
3199 return 0;
3200 ADDOP_I(c, BUILD_LIST, 0);
3201 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3204 e->v.ListComp.elt);
3205 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206 return rc;
3207}
3208
3209static int
3210compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 asdl_seq *generators, int gen_index,
3212 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213{
3214 /* generate code for the iterator, then each of the ifs,
3215 and then write to the element */
3216
3217 comprehension_ty ge;
3218 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
3221 start = compiler_new_block(c);
3222 skip = compiler_new_block(c);
3223 if_cleanup = compiler_new_block(c);
3224 anchor = compiler_new_block(c);
3225 end = compiler_new_block(c);
3226
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228 anchor == NULL || end == NULL)
3229 return 0;
3230
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003231 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 ADDOP_JREL(c, SETUP_LOOP, end);
3233 if (!compiler_push_fblock(c, LOOP, start))
3234 return 0;
3235
3236 if (gen_index == 0) {
3237 /* Receive outermost iter as an implicit argument */
3238 c->u->u_argcount = 1;
3239 ADDOP_I(c, LOAD_FAST, 0);
3240 }
3241 else {
3242 /* Sub-iter - calculate on the fly */
3243 VISIT(c, expr, ge->iter);
3244 ADDOP(c, GET_ITER);
3245 }
3246 compiler_use_next_block(c, start);
3247 ADDOP_JREL(c, FOR_ITER, anchor);
3248 NEXT_BLOCK(c);
3249 VISIT(c, expr, ge->target);
3250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 n = asdl_seq_LEN(ge->ifs);
3253 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003254 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 VISIT(c, expr, e);
3256 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3257 NEXT_BLOCK(c);
3258 ADDOP(c, POP_TOP);
3259 }
3260
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003261 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3263 return 0;
3264
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 /* only append after the last 'for' generator */
3266 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 VISIT(c, expr, elt);
3268 ADDOP(c, YIELD_VALUE);
3269 ADDOP(c, POP_TOP);
3270
3271 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003272 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273 for (i = 0; i < n; i++) {
3274 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003275 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276 compiler_use_next_block(c, if_cleanup);
3277
3278 ADDOP(c, POP_TOP);
3279 }
3280 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3281 compiler_use_next_block(c, anchor);
3282 ADDOP(c, POP_BLOCK);
3283 compiler_pop_fblock(c, LOOP, start);
3284 compiler_use_next_block(c, end);
3285
3286 return 1;
3287}
3288
3289static int
3290compiler_genexp(struct compiler *c, expr_ty e)
3291{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003292 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293 PyCodeObject *co;
3294 expr_ty outermost_iter = ((comprehension_ty)
3295 (asdl_seq_GET(e->v.GeneratorExp.generators,
3296 0)))->iter;
3297
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003298 if (!name) {
3299 name = PyString_FromString("<genexpr>");
3300 if (!name)
3301 return 0;
3302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303
3304 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3305 return 0;
3306 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3307 e->v.GeneratorExp.elt);
3308 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003309 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 if (co == NULL)
3311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003312
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003314 Py_DECREF(co);
3315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 VISIT(c, expr, outermost_iter);
3317 ADDOP(c, GET_ITER);
3318 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319
3320 return 1;
3321}
3322
3323static int
3324compiler_visit_keyword(struct compiler *c, keyword_ty k)
3325{
3326 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3327 VISIT(c, expr, k->value);
3328 return 1;
3329}
3330
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003331/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332 whether they are true or false.
3333
3334 Return values: 1 for true, 0 for false, -1 for non-constant.
3335 */
3336
3337static int
3338expr_constant(expr_ty e)
3339{
3340 switch (e->kind) {
3341 case Num_kind:
3342 return PyObject_IsTrue(e->v.Num.n);
3343 case Str_kind:
3344 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003345 case Name_kind:
3346 /* __debug__ is not assignable, so we can optimize
3347 * it away in if and while statements */
3348 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3349 "__debug__") == 0)
3350 return ! Py_OptimizeFlag;
3351 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352 default:
3353 return -1;
3354 }
3355}
3356
Guido van Rossumc2e20742006-02-27 22:32:47 +00003357/*
3358 Implements the with statement from PEP 343.
3359
3360 The semantics outlined in that PEP are as follows:
3361
3362 with EXPR as VAR:
3363 BLOCK
3364
3365 It is implemented roughly as:
3366
Thomas Wouters477c8d52006-05-27 19:21:47 +00003367 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003368 exit = context.__exit__ # not calling it
3369 value = context.__enter__()
3370 try:
3371 VAR = value # if VAR present in the syntax
3372 BLOCK
3373 finally:
3374 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003375 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003376 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003377 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003378 exit(*exc)
3379 */
3380static int
3381compiler_with(struct compiler *c, stmt_ty s)
3382{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003383 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003384 basicblock *block, *finally;
3385 identifier tmpexit, tmpvalue = NULL;
3386
3387 assert(s->kind == With_kind);
3388
Guido van Rossumc2e20742006-02-27 22:32:47 +00003389 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003390 enter_attr = PyString_InternFromString("__enter__");
3391 if (!enter_attr)
3392 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003393 }
3394 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 exit_attr = PyString_InternFromString("__exit__");
3396 if (!exit_attr)
3397 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003398 }
3399
3400 block = compiler_new_block(c);
3401 finally = compiler_new_block(c);
3402 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003403 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003404
3405 /* Create a temporary variable to hold context.__exit__ */
3406 tmpexit = compiler_new_tmpname(c);
3407 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003408 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003409 PyArena_AddPyObject(c->c_arena, tmpexit);
3410
3411 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003413 We need to do this rather than preserving it on the stack
3414 because SETUP_FINALLY remembers the stack level.
3415 We need to do the assignment *inside* the try/finally
3416 so that context.__exit__() is called when the assignment
3417 fails. But we need to call context.__enter__() *before*
3418 the try/finally so that if it fails we won't call
3419 context.__exit__().
3420 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003421 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003422 if (tmpvalue == NULL)
3423 return 0;
3424 PyArena_AddPyObject(c->c_arena, tmpvalue);
3425 }
3426
Thomas Wouters477c8d52006-05-27 19:21:47 +00003427 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003428 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003429
3430 /* Squirrel away context.__exit__ */
3431 ADDOP(c, DUP_TOP);
3432 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3433 if (!compiler_nameop(c, tmpexit, Store))
3434 return 0;
3435
3436 /* Call context.__enter__() */
3437 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3438 ADDOP_I(c, CALL_FUNCTION, 0);
3439
3440 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003441 /* Store it in tmpvalue */
3442 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003443 return 0;
3444 }
3445 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003446 /* Discard result from context.__enter__() */
3447 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003448 }
3449
3450 /* Start the try block */
3451 ADDOP_JREL(c, SETUP_FINALLY, finally);
3452
3453 compiler_use_next_block(c, block);
3454 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003456 }
3457
3458 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 /* Bind saved result of context.__enter__() to VAR */
3460 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003461 !compiler_nameop(c, tmpvalue, Del))
3462 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003463 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003464 }
3465
3466 /* BLOCK code */
3467 VISIT_SEQ(c, stmt, s->v.With.body);
3468
3469 /* End of try block; start the finally block */
3470 ADDOP(c, POP_BLOCK);
3471 compiler_pop_fblock(c, FINALLY_TRY, block);
3472
3473 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3474 compiler_use_next_block(c, finally);
3475 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003476 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003477
3478 /* Finally block starts; push tmpexit and issue our magic opcode. */
3479 if (!compiler_nameop(c, tmpexit, Load) ||
3480 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003481 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003482 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003483
3484 /* Finally block ends. */
3485 ADDOP(c, END_FINALLY);
3486 compiler_pop_fblock(c, FINALLY_END, finally);
3487 return 1;
3488}
3489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490static int
3491compiler_visit_expr(struct compiler *c, expr_ty e)
3492{
3493 int i, n;
3494
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003495 /* If expr e has a different line number than the last expr/stmt,
3496 set a new line number for the next instruction.
3497 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 if (e->lineno > c->u->u_lineno) {
3499 c->u->u_lineno = e->lineno;
3500 c->u->u_lineno_set = false;
3501 }
3502 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003503 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 VISIT(c, expr, e->v.BinOp.left);
3507 VISIT(c, expr, e->v.BinOp.right);
3508 ADDOP(c, binop(c, e->v.BinOp.op));
3509 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003510 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 VISIT(c, expr, e->v.UnaryOp.operand);
3512 ADDOP(c, unaryop(e->v.UnaryOp.op));
3513 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003514 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003516 case IfExp_kind:
3517 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003518 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519 /* XXX get rid of arg? */
3520 ADDOP_I(c, BUILD_MAP, 0);
3521 n = asdl_seq_LEN(e->v.Dict.values);
3522 /* We must arrange things just right for STORE_SUBSCR.
3523 It wants the stack to look like (value) (dict) (key) */
3524 for (i = 0; i < n; i++) {
3525 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003526 VISIT(c, expr,
3527 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003529 VISIT(c, expr,
3530 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 ADDOP(c, STORE_SUBSCR);
3532 }
3533 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003534 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003536 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537 return compiler_genexp(c, e);
3538 case Yield_kind:
3539 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003540 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541 /*
3542 for (i = 0; i < c->u->u_nfblocks; i++) {
3543 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3544 return compiler_error(
3545 c, "'yield' not allowed in a 'try' "
3546 "block with a 'finally' clause");
3547 }
3548 */
3549 if (e->v.Yield.value) {
3550 VISIT(c, expr, e->v.Yield.value);
3551 }
3552 else {
3553 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3554 }
3555 ADDOP(c, YIELD_VALUE);
3556 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003559 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003561 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 VISIT(c, expr, e->v.Repr.value);
3563 ADDOP(c, UNARY_CONVERT);
3564 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003565 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3567 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003568 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3570 break;
3571 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003572 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 if (e->v.Attribute.ctx != AugStore)
3574 VISIT(c, expr, e->v.Attribute.value);
3575 switch (e->v.Attribute.ctx) {
3576 case AugLoad:
3577 ADDOP(c, DUP_TOP);
3578 /* Fall through to load */
3579 case Load:
3580 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3581 break;
3582 case AugStore:
3583 ADDOP(c, ROT_TWO);
3584 /* Fall through to save */
3585 case Store:
3586 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3587 break;
3588 case Del:
3589 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3590 break;
3591 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003592 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003593 PyErr_SetString(PyExc_SystemError,
3594 "param invalid in attribute expression");
3595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 }
3597 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003598 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 switch (e->v.Subscript.ctx) {
3600 case AugLoad:
3601 VISIT(c, expr, e->v.Subscript.value);
3602 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3603 break;
3604 case Load:
3605 VISIT(c, expr, e->v.Subscript.value);
3606 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3607 break;
3608 case AugStore:
3609 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3610 break;
3611 case Store:
3612 VISIT(c, expr, e->v.Subscript.value);
3613 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3614 break;
3615 case Del:
3616 VISIT(c, expr, e->v.Subscript.value);
3617 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3618 break;
3619 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003620 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003621 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003622 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003623 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 }
3625 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003626 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3628 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003629 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003631 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 return compiler_tuple(c, e);
3633 }
3634 return 1;
3635}
3636
3637static int
3638compiler_augassign(struct compiler *c, stmt_ty s)
3639{
3640 expr_ty e = s->v.AugAssign.target;
3641 expr_ty auge;
3642
3643 assert(s->kind == AugAssign_kind);
3644
3645 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003646 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003648 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003649 if (auge == NULL)
3650 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 VISIT(c, expr, auge);
3652 VISIT(c, expr, s->v.AugAssign.value);
3653 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3654 auge->v.Attribute.ctx = AugStore;
3655 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 break;
3657 case Subscript_kind:
3658 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003659 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003660 if (auge == NULL)
3661 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662 VISIT(c, expr, auge);
3663 VISIT(c, expr, s->v.AugAssign.value);
3664 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003665 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003667 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 case Name_kind:
3669 VISIT(c, expr, s->v.AugAssign.target);
3670 VISIT(c, expr, s->v.AugAssign.value);
3671 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3672 return compiler_nameop(c, e->v.Name.id, Store);
3673 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003674 PyErr_Format(PyExc_SystemError,
3675 "invalid node type (%d) for augmented assignment",
3676 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003677 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678 }
3679 return 1;
3680}
3681
3682static int
3683compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3684{
3685 struct fblockinfo *f;
3686 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3687 return 0;
3688 f = &c->u->u_fblock[c->u->u_nfblocks++];
3689 f->fb_type = t;
3690 f->fb_block = b;
3691 return 1;
3692}
3693
3694static void
3695compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3696{
3697 struct compiler_unit *u = c->u;
3698 assert(u->u_nfblocks > 0);
3699 u->u_nfblocks--;
3700 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3701 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3702}
3703
3704/* Raises a SyntaxError and returns 0.
3705 If something goes wrong, a different exception may be raised.
3706*/
3707
3708static int
3709compiler_error(struct compiler *c, const char *errstr)
3710{
3711 PyObject *loc;
3712 PyObject *u = NULL, *v = NULL;
3713
3714 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3715 if (!loc) {
3716 Py_INCREF(Py_None);
3717 loc = Py_None;
3718 }
3719 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3720 Py_None, loc);
3721 if (!u)
3722 goto exit;
3723 v = Py_BuildValue("(zO)", errstr, u);
3724 if (!v)
3725 goto exit;
3726 PyErr_SetObject(PyExc_SyntaxError, v);
3727 exit:
3728 Py_DECREF(loc);
3729 Py_XDECREF(u);
3730 Py_XDECREF(v);
3731 return 0;
3732}
3733
3734static int
3735compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003736 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003738 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003739
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740 /* XXX this code is duplicated */
3741 switch (ctx) {
3742 case AugLoad: /* fall through to Load */
3743 case Load: op = BINARY_SUBSCR; break;
3744 case AugStore:/* fall through to Store */
3745 case Store: op = STORE_SUBSCR; break;
3746 case Del: op = DELETE_SUBSCR; break;
3747 case Param:
3748 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003749 "invalid %s kind %d in subscript\n",
3750 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003751 return 0;
3752 }
3753 if (ctx == AugLoad) {
3754 ADDOP_I(c, DUP_TOPX, 2);
3755 }
3756 else if (ctx == AugStore) {
3757 ADDOP(c, ROT_THREE);
3758 }
3759 ADDOP(c, op);
3760 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761}
3762
3763static int
3764compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3765{
3766 int n = 2;
3767 assert(s->kind == Slice_kind);
3768
3769 /* only handles the cases where BUILD_SLICE is emitted */
3770 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003771 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 }
3773 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003774 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003777 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003778 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003779 }
3780 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003781 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003782 }
3783
3784 if (s->v.Slice.step) {
3785 n++;
3786 VISIT(c, expr, s->v.Slice.step);
3787 }
3788 ADDOP_I(c, BUILD_SLICE, n);
3789 return 1;
3790}
3791
3792static int
3793compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3794{
3795 int op = 0, slice_offset = 0, stack_count = 0;
3796
3797 assert(s->v.Slice.step == NULL);
3798 if (s->v.Slice.lower) {
3799 slice_offset++;
3800 stack_count++;
3801 if (ctx != AugStore)
3802 VISIT(c, expr, s->v.Slice.lower);
3803 }
3804 if (s->v.Slice.upper) {
3805 slice_offset += 2;
3806 stack_count++;
3807 if (ctx != AugStore)
3808 VISIT(c, expr, s->v.Slice.upper);
3809 }
3810
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003811 if (ctx == AugLoad) {
3812 switch (stack_count) {
3813 case 0: ADDOP(c, DUP_TOP); break;
3814 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3815 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3816 }
3817 }
3818 else if (ctx == AugStore) {
3819 switch (stack_count) {
3820 case 0: ADDOP(c, ROT_TWO); break;
3821 case 1: ADDOP(c, ROT_THREE); break;
3822 case 2: ADDOP(c, ROT_FOUR); break;
3823 }
3824 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825
3826 switch (ctx) {
3827 case AugLoad: /* fall through to Load */
3828 case Load: op = SLICE; break;
3829 case AugStore:/* fall through to Store */
3830 case Store: op = STORE_SLICE; break;
3831 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003832 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003833 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003834 PyErr_SetString(PyExc_SystemError,
3835 "param invalid in simple slice");
3836 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003837 }
3838
3839 ADDOP(c, op + slice_offset);
3840 return 1;
3841}
3842
3843static int
3844compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3845 expr_context_ty ctx)
3846{
3847 switch (s->kind) {
3848 case Ellipsis_kind:
3849 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3850 break;
3851 case Slice_kind:
3852 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 case Index_kind:
3854 VISIT(c, expr, s->v.Index.value);
3855 break;
3856 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003857 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003858 PyErr_SetString(PyExc_SystemError,
3859 "extended slice invalid in nested slice");
3860 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 }
3862 return 1;
3863}
3864
3865
3866static int
3867compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3868{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003869 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003871 case Index_kind:
3872 kindname = "index";
3873 if (ctx != AugStore) {
3874 VISIT(c, expr, s->v.Index.value);
3875 }
3876 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003878 kindname = "ellipsis";
3879 if (ctx != AugStore) {
3880 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3881 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882 break;
3883 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003884 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 if (!s->v.Slice.step)
3886 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003887 if (ctx != AugStore) {
3888 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003889 return 0;
3890 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003891 break;
3892 case ExtSlice_kind:
3893 kindname = "extended slice";
3894 if (ctx != AugStore) {
3895 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3896 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003897 slice_ty sub = (slice_ty)asdl_seq_GET(
3898 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003899 if (!compiler_visit_nested_slice(c, sub, ctx))
3900 return 0;
3901 }
3902 ADDOP_I(c, BUILD_TUPLE, n);
3903 }
3904 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003905 default:
3906 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003907 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003908 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003910 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003911}
3912
3913/* do depth-first search of basic block graph, starting with block.
3914 post records the block indices in post-order.
3915
3916 XXX must handle implicit jumps from one block to next
3917*/
3918
3919static void
3920dfs(struct compiler *c, basicblock *b, struct assembler *a)
3921{
3922 int i;
3923 struct instr *instr = NULL;
3924
3925 if (b->b_seen)
3926 return;
3927 b->b_seen = 1;
3928 if (b->b_next != NULL)
3929 dfs(c, b->b_next, a);
3930 for (i = 0; i < b->b_iused; i++) {
3931 instr = &b->b_instr[i];
3932 if (instr->i_jrel || instr->i_jabs)
3933 dfs(c, instr->i_target, a);
3934 }
3935 a->a_postorder[a->a_nblocks++] = b;
3936}
3937
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003938static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3940{
3941 int i;
3942 struct instr *instr;
3943 if (b->b_seen || b->b_startdepth >= depth)
3944 return maxdepth;
3945 b->b_seen = 1;
3946 b->b_startdepth = depth;
3947 for (i = 0; i < b->b_iused; i++) {
3948 instr = &b->b_instr[i];
3949 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3950 if (depth > maxdepth)
3951 maxdepth = depth;
3952 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3953 if (instr->i_jrel || instr->i_jabs) {
3954 maxdepth = stackdepth_walk(c, instr->i_target,
3955 depth, maxdepth);
3956 if (instr->i_opcode == JUMP_ABSOLUTE ||
3957 instr->i_opcode == JUMP_FORWARD) {
3958 goto out; /* remaining code is dead */
3959 }
3960 }
3961 }
3962 if (b->b_next)
3963 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3964out:
3965 b->b_seen = 0;
3966 return maxdepth;
3967}
3968
3969/* Find the flow path that needs the largest stack. We assume that
3970 * cycles in the flow graph have no net effect on the stack depth.
3971 */
3972static int
3973stackdepth(struct compiler *c)
3974{
3975 basicblock *b, *entryblock;
3976 entryblock = NULL;
3977 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3978 b->b_seen = 0;
3979 b->b_startdepth = INT_MIN;
3980 entryblock = b;
3981 }
3982 return stackdepth_walk(c, entryblock, 0, 0);
3983}
3984
3985static int
3986assemble_init(struct assembler *a, int nblocks, int firstlineno)
3987{
3988 memset(a, 0, sizeof(struct assembler));
3989 a->a_lineno = firstlineno;
3990 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3991 if (!a->a_bytecode)
3992 return 0;
3993 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3994 if (!a->a_lnotab)
3995 return 0;
3996 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003997 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003998 if (!a->a_postorder) {
3999 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004000 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004001 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004002 return 1;
4003}
4004
4005static void
4006assemble_free(struct assembler *a)
4007{
4008 Py_XDECREF(a->a_bytecode);
4009 Py_XDECREF(a->a_lnotab);
4010 if (a->a_postorder)
4011 PyObject_Free(a->a_postorder);
4012}
4013
4014/* Return the size of a basic block in bytes. */
4015
4016static int
4017instrsize(struct instr *instr)
4018{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004019 if (!instr->i_hasarg)
4020 return 1;
4021 if (instr->i_oparg > 0xffff)
4022 return 6;
4023 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024}
4025
4026static int
4027blocksize(basicblock *b)
4028{
4029 int i;
4030 int size = 0;
4031
4032 for (i = 0; i < b->b_iused; i++)
4033 size += instrsize(&b->b_instr[i]);
4034 return size;
4035}
4036
4037/* All about a_lnotab.
4038
4039c_lnotab is an array of unsigned bytes disguised as a Python string.
4040It is used to map bytecode offsets to source code line #s (when needed
4041for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004042
Tim Peters2a7f3842001-06-09 09:26:21 +00004043The array is conceptually a list of
4044 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004045pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004046
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004047 byte code offset source code line number
4048 0 1
4049 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004050 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004051 350 307
4052 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004053
4054The first trick is that these numbers aren't stored, only the increments
4055from one row to the next (this doesn't really work, but it's a start):
4056
4057 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4058
4059The second trick is that an unsigned byte can't hold negative values, or
4060values larger than 255, so (a) there's a deep assumption that byte code
4061offsets and their corresponding line #s both increase monotonically, and (b)
4062if at least one column jumps by more than 255 from one row to the next, more
4063than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004064from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004065part. A user of c_lnotab desiring to find the source line number
4066corresponding to a bytecode address A should do something like this
4067
4068 lineno = addr = 0
4069 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004070 addr += addr_incr
4071 if addr > A:
4072 return lineno
4073 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004074
4075In order for this to work, when the addr field increments by more than 255,
4076the line # increment in each pair generated must be 0 until the remaining addr
4077increment is < 256. So, in the example above, com_set_lineno should not (as
4078was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004079255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004080*/
4081
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004082static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004084{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085 int d_bytecode, d_lineno;
4086 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004087 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088
4089 d_bytecode = a->a_offset - a->a_lineno_off;
4090 d_lineno = i->i_lineno - a->a_lineno;
4091
4092 assert(d_bytecode >= 0);
4093 assert(d_lineno >= 0);
4094
4095 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004096 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004097
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004099 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 nbytes = a->a_lnotab_off + 2 * ncodes;
4101 len = PyString_GET_SIZE(a->a_lnotab);
4102 if (nbytes >= len) {
4103 if (len * 2 < nbytes)
4104 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004105 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106 len *= 2;
4107 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4108 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004109 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004110 lnotab = (unsigned char *)
4111 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004112 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113 *lnotab++ = 255;
4114 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004115 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116 d_bytecode -= ncodes * 255;
4117 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119 assert(d_bytecode <= 255);
4120 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004121 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122 nbytes = a->a_lnotab_off + 2 * ncodes;
4123 len = PyString_GET_SIZE(a->a_lnotab);
4124 if (nbytes >= len) {
4125 if (len * 2 < nbytes)
4126 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004127 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128 len *= 2;
4129 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4130 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004131 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004132 lnotab = (unsigned char *)
4133 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 *lnotab++ = 255;
4135 *lnotab++ = d_bytecode;
4136 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004137 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 *lnotab++ = 255;
4139 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 d_lineno -= ncodes * 255;
4142 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004143 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145 len = PyString_GET_SIZE(a->a_lnotab);
4146 if (a->a_lnotab_off + 2 >= len) {
4147 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004148 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004149 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004150 lnotab = (unsigned char *)
4151 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004152
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 a->a_lnotab_off += 2;
4154 if (d_bytecode) {
4155 *lnotab++ = d_bytecode;
4156 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004157 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004158 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 *lnotab++ = 0;
4160 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004161 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 a->a_lineno = i->i_lineno;
4163 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004164 return 1;
4165}
4166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167/* assemble_emit()
4168 Extend the bytecode with a new instruction.
4169 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004170*/
4171
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004172static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004174{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004175 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 int len = PyString_GET_SIZE(a->a_bytecode);
4177 char *code;
4178
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004179 size = instrsize(i);
4180 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004182 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004185 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004186 if (a->a_offset + size >= len) {
4187 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004188 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4191 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004192 if (size == 6) {
4193 assert(i->i_hasarg);
4194 *code++ = (char)EXTENDED_ARG;
4195 *code++ = ext & 0xff;
4196 *code++ = ext >> 8;
4197 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004200 if (i->i_hasarg) {
4201 assert(size == 3 || size == 6);
4202 *code++ = arg & 0xff;
4203 *code++ = arg >> 8;
4204 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004206}
4207
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004208static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004210{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004212 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004213 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004214
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 /* Compute the size of each block and fixup jump args.
4216 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004217start:
4218 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004219 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004220 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 bsize = blocksize(b);
4222 b->b_offset = totsize;
4223 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004224 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004225 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4227 bsize = b->b_offset;
4228 for (i = 0; i < b->b_iused; i++) {
4229 struct instr *instr = &b->b_instr[i];
4230 /* Relative jumps are computed relative to
4231 the instruction pointer after fetching
4232 the jump instruction.
4233 */
4234 bsize += instrsize(instr);
4235 if (instr->i_jabs)
4236 instr->i_oparg = instr->i_target->b_offset;
4237 else if (instr->i_jrel) {
4238 int delta = instr->i_target->b_offset - bsize;
4239 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004240 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004241 else
4242 continue;
4243 if (instr->i_oparg > 0xffff)
4244 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004245 }
4246 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004247
4248 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004249 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004250 with a better solution.
4251
4252 In the meantime, should the goto be dropped in favor
4253 of a loop?
4254
4255 The issue is that in the first loop blocksize() is called
4256 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004257 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004258 i_oparg is calculated in the second loop above.
4259
4260 So we loop until we stop seeing new EXTENDED_ARGs.
4261 The only EXTENDED_ARGs that could be popping up are
4262 ones in jump instructions. So this should converge
4263 fairly quickly.
4264 */
4265 if (last_extended_arg_count != extended_arg_count) {
4266 last_extended_arg_count = extended_arg_count;
4267 goto start;
4268 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004269}
4270
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004271static PyObject *
4272dict_keys_inorder(PyObject *dict, int offset)
4273{
4274 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004275 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004276
4277 tuple = PyTuple_New(size);
4278 if (tuple == NULL)
4279 return NULL;
4280 while (PyDict_Next(dict, &pos, &k, &v)) {
4281 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004282 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004283 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004284 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004285 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004286 PyTuple_SET_ITEM(tuple, i - offset, k);
4287 }
4288 return tuple;
4289}
4290
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004291static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004293{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004294 PySTEntryObject *ste = c->u->u_ste;
4295 int flags = 0, n;
4296 if (ste->ste_type != ModuleBlock)
4297 flags |= CO_NEWLOCALS;
4298 if (ste->ste_type == FunctionBlock) {
4299 if (!ste->ste_unoptimized)
4300 flags |= CO_OPTIMIZED;
4301 if (ste->ste_nested)
4302 flags |= CO_NESTED;
4303 if (ste->ste_generator)
4304 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004305 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306 if (ste->ste_varargs)
4307 flags |= CO_VARARGS;
4308 if (ste->ste_varkeywords)
4309 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004310 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004312
4313 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004314 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316 n = PyDict_Size(c->u->u_freevars);
4317 if (n < 0)
4318 return -1;
4319 if (n == 0) {
4320 n = PyDict_Size(c->u->u_cellvars);
4321 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004322 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323 if (n == 0) {
4324 flags |= CO_NOFREE;
4325 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004326 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004327
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004328 return flags;
4329}
4330
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331static PyCodeObject *
4332makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004333{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004334 PyObject *tmp;
4335 PyCodeObject *co = NULL;
4336 PyObject *consts = NULL;
4337 PyObject *names = NULL;
4338 PyObject *varnames = NULL;
4339 PyObject *filename = NULL;
4340 PyObject *name = NULL;
4341 PyObject *freevars = NULL;
4342 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004343 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346 tmp = dict_keys_inorder(c->u->u_consts, 0);
4347 if (!tmp)
4348 goto error;
4349 consts = PySequence_List(tmp); /* optimize_code requires a list */
4350 Py_DECREF(tmp);
4351
4352 names = dict_keys_inorder(c->u->u_names, 0);
4353 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4354 if (!consts || !names || !varnames)
4355 goto error;
4356
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004357 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4358 if (!cellvars)
4359 goto error;
4360 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4361 if (!freevars)
4362 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004363 filename = PyString_FromString(c->c_filename);
4364 if (!filename)
4365 goto error;
4366
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004367 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368 flags = compute_code_flags(c);
4369 if (flags < 0)
4370 goto error;
4371
4372 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4373 if (!bytecode)
4374 goto error;
4375
4376 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4377 if (!tmp)
4378 goto error;
4379 Py_DECREF(consts);
4380 consts = tmp;
4381
4382 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4383 bytecode, consts, names, varnames,
4384 freevars, cellvars,
4385 filename, c->u->u_name,
4386 c->u->u_firstlineno,
4387 a->a_lnotab);
4388 error:
4389 Py_XDECREF(consts);
4390 Py_XDECREF(names);
4391 Py_XDECREF(varnames);
4392 Py_XDECREF(filename);
4393 Py_XDECREF(name);
4394 Py_XDECREF(freevars);
4395 Py_XDECREF(cellvars);
4396 Py_XDECREF(bytecode);
4397 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004398}
4399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400static PyCodeObject *
4401assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004402{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004403 basicblock *b, *entryblock;
4404 struct assembler a;
4405 int i, j, nblocks;
4406 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 /* Make sure every block that falls off the end returns None.
4409 XXX NEXT_BLOCK() isn't quite right, because if the last
4410 block ends with a jump or return b_next shouldn't set.
4411 */
4412 if (!c->u->u_curblock->b_return) {
4413 NEXT_BLOCK(c);
4414 if (addNone)
4415 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4416 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004417 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004418
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419 nblocks = 0;
4420 entryblock = NULL;
4421 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4422 nblocks++;
4423 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004424 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4427 goto error;
4428 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004431 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433 /* Emit code in reverse postorder from dfs. */
4434 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004435 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436 for (j = 0; j < b->b_iused; j++)
4437 if (!assemble_emit(&a, &b->b_instr[j]))
4438 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004439 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004440
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4442 goto error;
4443 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4444 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004445
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446 co = makecode(c, &a);
4447 error:
4448 assemble_free(&a);
4449 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004450}