blob: 12b190a76408a5bef543848577608a5ab25191be [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);
337 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
380 tuple = Py_BuildValue("(OO)", k, k->ob_type);
381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000394/* Begin: Peephole optimizations ----------------------------------------- */
395
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000396#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000398#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
399#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000400#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define ISBASICBLOCK(blocks, start, bytes) \
403 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000410 Bails out with no change if one or more of the LOAD_CONSTs is missing.
411 Also works for BUILD_LIST when followed by an "in" or "not in" test.
412*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413static int
414tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
415{
416 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418
419 /* Pre-conditions */
420 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000421 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000424 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425
426 /* Buildup new tuple of constants */
427 newconst = PyTuple_New(n);
428 if (newconst == NULL)
429 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 for (i=0 ; i<n ; i++) {
432 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 constant = PyList_GET_ITEM(consts, arg);
435 Py_INCREF(constant);
436 PyTuple_SET_ITEM(newconst, i, constant);
437 }
438
439 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 if (PyList_Append(consts, newconst)) {
441 Py_DECREF(newconst);
442 return 0;
443 }
444 Py_DECREF(newconst);
445
446 /* Write NOPs over old LOAD_CONSTS and
447 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
448 memset(codestr, NOP, n*3);
449 codestr[n*3] = LOAD_CONST;
450 SETARG(codestr, (n*3), len_consts);
451 return 1;
452}
453
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000458 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000459 Abandons the transformation if the folding fails (i.e. 1+'a').
460 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 is below a threshold value. That keeps pyc files from
462 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000463*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000464static int
465fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
466{
467 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t len_consts, size;
469 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000470
471 /* Pre-conditions */
472 assert(PyList_CheckExact(consts));
473 assert(codestr[0] == LOAD_CONST);
474 assert(codestr[3] == LOAD_CONST);
475
476 /* Create new constant */
477 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
478 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
479 opcode = codestr[6];
480 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 case BINARY_POWER:
482 newconst = PyNumber_Power(v, w, Py_None);
483 break;
484 case BINARY_MULTIPLY:
485 newconst = PyNumber_Multiply(v, w);
486 break;
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;
1837 k = Py_BuildValue("(OO)", name, name->ob_type);
1838 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;
2144
2145 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;
2152 VISIT(c, expr, s->v.If.test);
2153 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2154 ADDOP(c, POP_TOP);
2155 VISIT_SEQ(c, stmt, s->v.If.body);
2156 ADDOP_JREL(c, JUMP_FORWARD, end);
2157 compiler_use_next_block(c, next);
2158 ADDOP(c, POP_TOP);
2159 if (s->v.If.orelse)
2160 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161 compiler_use_next_block(c, end);
2162 return 1;
2163}
2164
2165static int
2166compiler_for(struct compiler *c, stmt_ty s)
2167{
2168 basicblock *start, *cleanup, *end;
2169
2170 start = compiler_new_block(c);
2171 cleanup = compiler_new_block(c);
2172 end = compiler_new_block(c);
2173 if (start == NULL || end == NULL || cleanup == NULL)
2174 return 0;
2175 ADDOP_JREL(c, SETUP_LOOP, end);
2176 if (!compiler_push_fblock(c, LOOP, start))
2177 return 0;
2178 VISIT(c, expr, s->v.For.iter);
2179 ADDOP(c, GET_ITER);
2180 compiler_use_next_block(c, start);
2181 ADDOP_JREL(c, FOR_ITER, cleanup);
2182 VISIT(c, expr, s->v.For.target);
2183 VISIT_SEQ(c, stmt, s->v.For.body);
2184 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2185 compiler_use_next_block(c, cleanup);
2186 ADDOP(c, POP_BLOCK);
2187 compiler_pop_fblock(c, LOOP, start);
2188 VISIT_SEQ(c, stmt, s->v.For.orelse);
2189 compiler_use_next_block(c, end);
2190 return 1;
2191}
2192
2193static int
2194compiler_while(struct compiler *c, stmt_ty s)
2195{
2196 basicblock *loop, *orelse, *end, *anchor = NULL;
2197 int constant = expr_constant(s->v.While.test);
2198
2199 if (constant == 0)
2200 return 1;
2201 loop = compiler_new_block(c);
2202 end = compiler_new_block(c);
2203 if (constant == -1) {
2204 anchor = compiler_new_block(c);
2205 if (anchor == NULL)
2206 return 0;
2207 }
2208 if (loop == NULL || end == NULL)
2209 return 0;
2210 if (s->v.While.orelse) {
2211 orelse = compiler_new_block(c);
2212 if (orelse == NULL)
2213 return 0;
2214 }
2215 else
2216 orelse = NULL;
2217
2218 ADDOP_JREL(c, SETUP_LOOP, end);
2219 compiler_use_next_block(c, loop);
2220 if (!compiler_push_fblock(c, LOOP, loop))
2221 return 0;
2222 if (constant == -1) {
2223 VISIT(c, expr, s->v.While.test);
2224 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2225 ADDOP(c, POP_TOP);
2226 }
2227 VISIT_SEQ(c, stmt, s->v.While.body);
2228 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2229
2230 /* XXX should the two POP instructions be in a separate block
2231 if there is no else clause ?
2232 */
2233
2234 if (constant == -1) {
2235 compiler_use_next_block(c, anchor);
2236 ADDOP(c, POP_TOP);
2237 ADDOP(c, POP_BLOCK);
2238 }
2239 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002240 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002241 VISIT_SEQ(c, stmt, s->v.While.orelse);
2242 compiler_use_next_block(c, end);
2243
2244 return 1;
2245}
2246
2247static int
2248compiler_continue(struct compiler *c)
2249{
2250 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2251 int i;
2252
2253 if (!c->u->u_nfblocks)
2254 return compiler_error(c, LOOP_ERROR_MSG);
2255 i = c->u->u_nfblocks - 1;
2256 switch (c->u->u_fblock[i].fb_type) {
2257 case LOOP:
2258 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2259 break;
2260 case EXCEPT:
2261 case FINALLY_TRY:
2262 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2263 ;
2264 if (i == -1)
2265 return compiler_error(c, LOOP_ERROR_MSG);
2266 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2267 break;
2268 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002269 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002270 "'continue' not supported inside 'finally' clause");
2271 }
2272
2273 return 1;
2274}
2275
2276/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2277
2278 SETUP_FINALLY L
2279 <code for body>
2280 POP_BLOCK
2281 LOAD_CONST <None>
2282 L: <code for finalbody>
2283 END_FINALLY
2284
2285 The special instructions use the block stack. Each block
2286 stack entry contains the instruction that created it (here
2287 SETUP_FINALLY), the level of the value stack at the time the
2288 block stack entry was created, and a label (here L).
2289
2290 SETUP_FINALLY:
2291 Pushes the current value stack level and the label
2292 onto the block stack.
2293 POP_BLOCK:
2294 Pops en entry from the block stack, and pops the value
2295 stack until its level is the same as indicated on the
2296 block stack. (The label is ignored.)
2297 END_FINALLY:
2298 Pops a variable number of entries from the *value* stack
2299 and re-raises the exception they specify. The number of
2300 entries popped depends on the (pseudo) exception type.
2301
2302 The block stack is unwound when an exception is raised:
2303 when a SETUP_FINALLY entry is found, the exception is pushed
2304 onto the value stack (and the exception condition is cleared),
2305 and the interpreter jumps to the label gotten from the block
2306 stack.
2307*/
2308
2309static int
2310compiler_try_finally(struct compiler *c, stmt_ty s)
2311{
2312 basicblock *body, *end;
2313 body = compiler_new_block(c);
2314 end = compiler_new_block(c);
2315 if (body == NULL || end == NULL)
2316 return 0;
2317
2318 ADDOP_JREL(c, SETUP_FINALLY, end);
2319 compiler_use_next_block(c, body);
2320 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2321 return 0;
2322 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2323 ADDOP(c, POP_BLOCK);
2324 compiler_pop_fblock(c, FINALLY_TRY, body);
2325
2326 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2327 compiler_use_next_block(c, end);
2328 if (!compiler_push_fblock(c, FINALLY_END, end))
2329 return 0;
2330 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2331 ADDOP(c, END_FINALLY);
2332 compiler_pop_fblock(c, FINALLY_END, end);
2333
2334 return 1;
2335}
2336
2337/*
2338 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2339 (The contents of the value stack is shown in [], with the top
2340 at the right; 'tb' is trace-back info, 'val' the exception's
2341 associated value, and 'exc' the exception.)
2342
2343 Value stack Label Instruction Argument
2344 [] SETUP_EXCEPT L1
2345 [] <code for S>
2346 [] POP_BLOCK
2347 [] JUMP_FORWARD L0
2348
2349 [tb, val, exc] L1: DUP )
2350 [tb, val, exc, exc] <evaluate E1> )
2351 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2352 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2353 [tb, val, exc, 1] POP )
2354 [tb, val, exc] POP
2355 [tb, val] <assign to V1> (or POP if no V1)
2356 [tb] POP
2357 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002358 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359
2360 [tb, val, exc, 0] L2: POP
2361 [tb, val, exc] DUP
2362 .............................etc.......................
2363
2364 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002365 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366
2367 [] L0: <next statement>
2368
2369 Of course, parts are not generated if Vi or Ei is not present.
2370*/
2371static int
2372compiler_try_except(struct compiler *c, stmt_ty s)
2373{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002374 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375 int i, n;
2376
2377 body = compiler_new_block(c);
2378 except = compiler_new_block(c);
2379 orelse = compiler_new_block(c);
2380 end = compiler_new_block(c);
2381 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2382 return 0;
2383 ADDOP_JREL(c, SETUP_EXCEPT, except);
2384 compiler_use_next_block(c, body);
2385 if (!compiler_push_fblock(c, EXCEPT, body))
2386 return 0;
2387 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2388 ADDOP(c, POP_BLOCK);
2389 compiler_pop_fblock(c, EXCEPT, body);
2390 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2391 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2392 compiler_use_next_block(c, except);
2393 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 s->v.TryExcept.handlers, i);
2396 if (!handler->type && i < n-1)
2397 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002398 c->u->u_lineno_set = false;
2399 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400 except = compiler_new_block(c);
2401 if (except == NULL)
2402 return 0;
2403 if (handler->type) {
2404 ADDOP(c, DUP_TOP);
2405 VISIT(c, expr, handler->type);
2406 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2407 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2408 ADDOP(c, POP_TOP);
2409 }
2410 ADDOP(c, POP_TOP);
2411 if (handler->name) {
2412 VISIT(c, expr, handler->name);
2413 }
2414 else {
2415 ADDOP(c, POP_TOP);
2416 }
2417 ADDOP(c, POP_TOP);
2418 VISIT_SEQ(c, stmt, handler->body);
2419 ADDOP_JREL(c, JUMP_FORWARD, end);
2420 compiler_use_next_block(c, except);
2421 if (handler->type)
2422 ADDOP(c, POP_TOP);
2423 }
2424 ADDOP(c, END_FINALLY);
2425 compiler_use_next_block(c, orelse);
2426 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2427 compiler_use_next_block(c, end);
2428 return 1;
2429}
2430
2431static int
2432compiler_import_as(struct compiler *c, identifier name, identifier asname)
2433{
2434 /* The IMPORT_NAME opcode was already generated. This function
2435 merely needs to bind the result to a name.
2436
2437 If there is a dot in name, we need to split it and emit a
2438 LOAD_ATTR for each name.
2439 */
2440 const char *src = PyString_AS_STRING(name);
2441 const char *dot = strchr(src, '.');
2442 if (dot) {
2443 /* Consume the base module name to get the first attribute */
2444 src = dot + 1;
2445 while (dot) {
2446 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002447 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002449 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002450 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002451 if (!attr)
2452 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002454 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 src = dot + 1;
2456 }
2457 }
2458 return compiler_nameop(c, asname, Store);
2459}
2460
2461static int
2462compiler_import(struct compiler *c, stmt_ty s)
2463{
2464 /* The Import node stores a module name like a.b.c as a single
2465 string. This is convenient for all cases except
2466 import a.b.c as d
2467 where we need to parse that string to extract the individual
2468 module names.
2469 XXX Perhaps change the representation to make this case simpler?
2470 */
2471 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002474 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002476 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477
Guido van Rossum45aecf42006-03-15 04:58:47 +00002478 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002479 if (level == NULL)
2480 return 0;
2481
2482 ADDOP_O(c, LOAD_CONST, level, consts);
2483 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2485 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2486
2487 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002488 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002489 if (!r)
2490 return r;
2491 }
2492 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 identifier tmp = alias->name;
2494 const char *base = PyString_AS_STRING(alias->name);
2495 char *dot = strchr(base, '.');
2496 if (dot)
2497 tmp = PyString_FromStringAndSize(base,
2498 dot - base);
2499 r = compiler_nameop(c, tmp, Store);
2500 if (dot) {
2501 Py_DECREF(tmp);
2502 }
2503 if (!r)
2504 return r;
2505 }
2506 }
2507 return 1;
2508}
2509
2510static int
2511compiler_from_import(struct compiler *c, stmt_ty s)
2512{
2513 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002514
2515 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002516 PyObject *level;
2517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002518 if (!names)
2519 return 0;
2520
Guido van Rossum45aecf42006-03-15 04:58:47 +00002521 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002522 if (!level) {
2523 Py_DECREF(names);
2524 return 0;
2525 }
2526
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 /* build up the names */
2528 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002529 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 Py_INCREF(alias->name);
2531 PyTuple_SET_ITEM(names, i, alias->name);
2532 }
2533
2534 if (s->lineno > c->c_future->ff_lineno) {
2535 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2536 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002537 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 Py_DECREF(names);
2539 return compiler_error(c,
2540 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002541 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542
2543 }
2544 }
2545
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002546 ADDOP_O(c, LOAD_CONST, level, consts);
2547 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002549 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2551 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002552 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 identifier store_name;
2554
2555 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2556 assert(n == 1);
2557 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002558 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 }
2560
2561 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2562 store_name = alias->name;
2563 if (alias->asname)
2564 store_name = alias->asname;
2565
2566 if (!compiler_nameop(c, store_name, Store)) {
2567 Py_DECREF(names);
2568 return 0;
2569 }
2570 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002571 /* remove imported module */
2572 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 return 1;
2574}
2575
2576static int
2577compiler_assert(struct compiler *c, stmt_ty s)
2578{
2579 static PyObject *assertion_error = NULL;
2580 basicblock *end;
2581
2582 if (Py_OptimizeFlag)
2583 return 1;
2584 if (assertion_error == NULL) {
2585 assertion_error = PyString_FromString("AssertionError");
2586 if (assertion_error == NULL)
2587 return 0;
2588 }
2589 VISIT(c, expr, s->v.Assert.test);
2590 end = compiler_new_block(c);
2591 if (end == NULL)
2592 return 0;
2593 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2594 ADDOP(c, POP_TOP);
2595 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2596 if (s->v.Assert.msg) {
2597 VISIT(c, expr, s->v.Assert.msg);
2598 ADDOP_I(c, RAISE_VARARGS, 2);
2599 }
2600 else {
2601 ADDOP_I(c, RAISE_VARARGS, 1);
2602 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002603 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604 ADDOP(c, POP_TOP);
2605 return 1;
2606}
2607
2608static int
2609compiler_visit_stmt(struct compiler *c, stmt_ty s)
2610{
2611 int i, n;
2612
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002613 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 c->u->u_lineno = s->lineno;
2615 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002618 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002620 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002622 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 if (c->u->u_ste->ste_type != FunctionBlock)
2624 return compiler_error(c, "'return' outside function");
2625 if (s->v.Return.value) {
2626 if (c->u->u_ste->ste_generator) {
2627 return compiler_error(c,
2628 "'return' with argument inside generator");
2629 }
2630 VISIT(c, expr, s->v.Return.value);
2631 }
2632 else
2633 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2634 ADDOP(c, RETURN_VALUE);
2635 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 VISIT_SEQ(c, expr, s->v.Delete.targets)
2638 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002639 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 n = asdl_seq_LEN(s->v.Assign.targets);
2641 VISIT(c, expr, s->v.Assign.value);
2642 for (i = 0; i < n; i++) {
2643 if (i < n - 1)
2644 ADDOP(c, DUP_TOP);
2645 VISIT(c, expr,
2646 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2647 }
2648 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 n = 0;
2661 if (s->v.Raise.type) {
2662 VISIT(c, expr, s->v.Raise.type);
2663 n++;
2664 if (s->v.Raise.inst) {
2665 VISIT(c, expr, s->v.Raise.inst);
2666 n++;
2667 if (s->v.Raise.tback) {
2668 VISIT(c, expr, s->v.Raise.tback);
2669 n++;
2670 }
2671 }
2672 }
2673 ADDOP_I(c, RAISE_VARARGS, n);
2674 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002679 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002681 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 VISIT(c, expr, s->v.Exec.body);
2687 if (s->v.Exec.globals) {
2688 VISIT(c, expr, s->v.Exec.globals);
2689 if (s->v.Exec.locals) {
2690 VISIT(c, expr, s->v.Exec.locals);
2691 } else {
2692 ADDOP(c, DUP_TOP);
2693 }
2694 } else {
2695 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2696 ADDOP(c, DUP_TOP);
2697 }
2698 ADDOP(c, EXEC_STMT);
2699 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 VISIT(c, expr, s->v.Expr.value);
2704 if (c->c_interactive && c->c_nestlevel <= 1) {
2705 ADDOP(c, PRINT_EXPR);
2706 }
2707 else {
2708 ADDOP(c, POP_TOP);
2709 }
2710 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 if (!c->u->u_nfblocks)
2715 return compiler_error(c, "'break' outside loop");
2716 ADDOP(c, BREAK_LOOP);
2717 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002720 case With_kind:
2721 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002722 }
2723 return 1;
2724}
2725
2726static int
2727unaryop(unaryop_ty op)
2728{
2729 switch (op) {
2730 case Invert:
2731 return UNARY_INVERT;
2732 case Not:
2733 return UNARY_NOT;
2734 case UAdd:
2735 return UNARY_POSITIVE;
2736 case USub:
2737 return UNARY_NEGATIVE;
2738 }
2739 return 0;
2740}
2741
2742static int
2743binop(struct compiler *c, operator_ty op)
2744{
2745 switch (op) {
2746 case Add:
2747 return BINARY_ADD;
2748 case Sub:
2749 return BINARY_SUBTRACT;
2750 case Mult:
2751 return BINARY_MULTIPLY;
2752 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002753 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754 case Mod:
2755 return BINARY_MODULO;
2756 case Pow:
2757 return BINARY_POWER;
2758 case LShift:
2759 return BINARY_LSHIFT;
2760 case RShift:
2761 return BINARY_RSHIFT;
2762 case BitOr:
2763 return BINARY_OR;
2764 case BitXor:
2765 return BINARY_XOR;
2766 case BitAnd:
2767 return BINARY_AND;
2768 case FloorDiv:
2769 return BINARY_FLOOR_DIVIDE;
2770 }
2771 return 0;
2772}
2773
2774static int
2775cmpop(cmpop_ty op)
2776{
2777 switch (op) {
2778 case Eq:
2779 return PyCmp_EQ;
2780 case NotEq:
2781 return PyCmp_NE;
2782 case Lt:
2783 return PyCmp_LT;
2784 case LtE:
2785 return PyCmp_LE;
2786 case Gt:
2787 return PyCmp_GT;
2788 case GtE:
2789 return PyCmp_GE;
2790 case Is:
2791 return PyCmp_IS;
2792 case IsNot:
2793 return PyCmp_IS_NOT;
2794 case In:
2795 return PyCmp_IN;
2796 case NotIn:
2797 return PyCmp_NOT_IN;
2798 }
2799 return PyCmp_BAD;
2800}
2801
2802static int
2803inplace_binop(struct compiler *c, operator_ty op)
2804{
2805 switch (op) {
2806 case Add:
2807 return INPLACE_ADD;
2808 case Sub:
2809 return INPLACE_SUBTRACT;
2810 case Mult:
2811 return INPLACE_MULTIPLY;
2812 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002813 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 case Mod:
2815 return INPLACE_MODULO;
2816 case Pow:
2817 return INPLACE_POWER;
2818 case LShift:
2819 return INPLACE_LSHIFT;
2820 case RShift:
2821 return INPLACE_RSHIFT;
2822 case BitOr:
2823 return INPLACE_OR;
2824 case BitXor:
2825 return INPLACE_XOR;
2826 case BitAnd:
2827 return INPLACE_AND;
2828 case FloorDiv:
2829 return INPLACE_FLOOR_DIVIDE;
2830 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002831 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002832 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002833 return 0;
2834}
2835
2836static int
2837compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2838{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002839 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2841
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002843 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844 /* XXX AugStore isn't used anywhere! */
2845
2846 /* First check for assignment to __debug__. Param? */
2847 if ((ctx == Store || ctx == AugStore || ctx == Del)
2848 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2849 return compiler_error(c, "can not assign to __debug__");
2850 }
2851
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002852 mangled = _Py_Mangle(c->u->u_private, name);
2853 if (!mangled)
2854 return 0;
2855
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856 op = 0;
2857 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002858 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859 switch (scope) {
2860 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002861 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862 optype = OP_DEREF;
2863 break;
2864 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 optype = OP_DEREF;
2867 break;
2868 case LOCAL:
2869 if (c->u->u_ste->ste_type == FunctionBlock)
2870 optype = OP_FAST;
2871 break;
2872 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002873 if (c->u->u_ste->ste_type == FunctionBlock &&
2874 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875 optype = OP_GLOBAL;
2876 break;
2877 case GLOBAL_EXPLICIT:
2878 optype = OP_GLOBAL;
2879 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002880 default:
2881 /* scope can be 0 */
2882 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 }
2884
2885 /* XXX Leave assert here, but handle __doc__ and the like better */
2886 assert(scope || PyString_AS_STRING(name)[0] == '_');
2887
2888 switch (optype) {
2889 case OP_DEREF:
2890 switch (ctx) {
2891 case Load: op = LOAD_DEREF; break;
2892 case Store: op = STORE_DEREF; break;
2893 case AugLoad:
2894 case AugStore:
2895 break;
2896 case Del:
2897 PyErr_Format(PyExc_SyntaxError,
2898 "can not delete variable '%s' referenced "
2899 "in nested scope",
2900 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002901 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002904 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002905 PyErr_SetString(PyExc_SystemError,
2906 "param invalid for deref variable");
2907 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002908 }
2909 break;
2910 case OP_FAST:
2911 switch (ctx) {
2912 case Load: op = LOAD_FAST; break;
2913 case Store: op = STORE_FAST; break;
2914 case Del: op = DELETE_FAST; break;
2915 case AugLoad:
2916 case AugStore:
2917 break;
2918 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002919 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002920 PyErr_SetString(PyExc_SystemError,
2921 "param invalid for local variable");
2922 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002924 ADDOP_O(c, op, mangled, varnames);
2925 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926 return 1;
2927 case OP_GLOBAL:
2928 switch (ctx) {
2929 case Load: op = LOAD_GLOBAL; break;
2930 case Store: op = STORE_GLOBAL; break;
2931 case Del: op = DELETE_GLOBAL; break;
2932 case AugLoad:
2933 case AugStore:
2934 break;
2935 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002936 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002937 PyErr_SetString(PyExc_SystemError,
2938 "param invalid for global variable");
2939 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 }
2941 break;
2942 case OP_NAME:
2943 switch (ctx) {
2944 case Load: op = LOAD_NAME; break;
2945 case Store: op = STORE_NAME; break;
2946 case Del: op = DELETE_NAME; break;
2947 case AugLoad:
2948 case AugStore:
2949 break;
2950 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002951 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002952 PyErr_SetString(PyExc_SystemError,
2953 "param invalid for name variable");
2954 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 }
2956 break;
2957 }
2958
2959 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002960 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002961 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002962 if (arg < 0)
2963 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002964 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965}
2966
2967static int
2968compiler_boolop(struct compiler *c, expr_ty e)
2969{
2970 basicblock *end;
2971 int jumpi, i, n;
2972 asdl_seq *s;
2973
2974 assert(e->kind == BoolOp_kind);
2975 if (e->v.BoolOp.op == And)
2976 jumpi = JUMP_IF_FALSE;
2977 else
2978 jumpi = JUMP_IF_TRUE;
2979 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002980 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981 return 0;
2982 s = e->v.BoolOp.values;
2983 n = asdl_seq_LEN(s) - 1;
2984 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002985 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 ADDOP_JREL(c, jumpi, end);
2987 ADDOP(c, POP_TOP)
2988 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002989 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002990 compiler_use_next_block(c, end);
2991 return 1;
2992}
2993
2994static int
2995compiler_list(struct compiler *c, expr_ty e)
2996{
2997 int n = asdl_seq_LEN(e->v.List.elts);
2998 if (e->v.List.ctx == Store) {
2999 ADDOP_I(c, UNPACK_SEQUENCE, n);
3000 }
3001 VISIT_SEQ(c, expr, e->v.List.elts);
3002 if (e->v.List.ctx == Load) {
3003 ADDOP_I(c, BUILD_LIST, n);
3004 }
3005 return 1;
3006}
3007
3008static int
3009compiler_tuple(struct compiler *c, expr_ty e)
3010{
3011 int n = asdl_seq_LEN(e->v.Tuple.elts);
3012 if (e->v.Tuple.ctx == Store) {
3013 ADDOP_I(c, UNPACK_SEQUENCE, n);
3014 }
3015 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3016 if (e->v.Tuple.ctx == Load) {
3017 ADDOP_I(c, BUILD_TUPLE, n);
3018 }
3019 return 1;
3020}
3021
3022static int
3023compiler_compare(struct compiler *c, expr_ty e)
3024{
3025 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003026 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027
3028 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3029 VISIT(c, expr, e->v.Compare.left);
3030 n = asdl_seq_LEN(e->v.Compare.ops);
3031 assert(n > 0);
3032 if (n > 1) {
3033 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003034 if (cleanup == NULL)
3035 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003036 VISIT(c, expr,
3037 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 }
3039 for (i = 1; i < n; i++) {
3040 ADDOP(c, DUP_TOP);
3041 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003043 cmpop((cmpop_ty)(asdl_seq_GET(
3044 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3046 NEXT_BLOCK(c);
3047 ADDOP(c, POP_TOP);
3048 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003049 VISIT(c, expr,
3050 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003052 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003054 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 if (n > 1) {
3056 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 if (end == NULL)
3058 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059 ADDOP_JREL(c, JUMP_FORWARD, end);
3060 compiler_use_next_block(c, cleanup);
3061 ADDOP(c, ROT_TWO);
3062 ADDOP(c, POP_TOP);
3063 compiler_use_next_block(c, end);
3064 }
3065 return 1;
3066}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003067#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003068
3069static int
3070compiler_call(struct compiler *c, expr_ty e)
3071{
3072 int n, code = 0;
3073
3074 VISIT(c, expr, e->v.Call.func);
3075 n = asdl_seq_LEN(e->v.Call.args);
3076 VISIT_SEQ(c, expr, e->v.Call.args);
3077 if (e->v.Call.keywords) {
3078 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3079 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3080 }
3081 if (e->v.Call.starargs) {
3082 VISIT(c, expr, e->v.Call.starargs);
3083 code |= 1;
3084 }
3085 if (e->v.Call.kwargs) {
3086 VISIT(c, expr, e->v.Call.kwargs);
3087 code |= 2;
3088 }
3089 switch (code) {
3090 case 0:
3091 ADDOP_I(c, CALL_FUNCTION, n);
3092 break;
3093 case 1:
3094 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3095 break;
3096 case 2:
3097 ADDOP_I(c, CALL_FUNCTION_KW, n);
3098 break;
3099 case 3:
3100 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3101 break;
3102 }
3103 return 1;
3104}
3105
3106static int
3107compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 asdl_seq *generators, int gen_index,
3109 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110{
3111 /* generate code for the iterator, then each of the ifs,
3112 and then write to the element */
3113
3114 comprehension_ty l;
3115 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117
3118 start = compiler_new_block(c);
3119 skip = compiler_new_block(c);
3120 if_cleanup = compiler_new_block(c);
3121 anchor = compiler_new_block(c);
3122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3124 anchor == NULL)
3125 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003127 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128 VISIT(c, expr, l->iter);
3129 ADDOP(c, GET_ITER);
3130 compiler_use_next_block(c, start);
3131 ADDOP_JREL(c, FOR_ITER, anchor);
3132 NEXT_BLOCK(c);
3133 VISIT(c, expr, l->target);
3134
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003135 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 n = asdl_seq_LEN(l->ifs);
3137 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003138 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 VISIT(c, expr, e);
3140 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3141 NEXT_BLOCK(c);
3142 ADDOP(c, POP_TOP);
3143 }
3144
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 if (++gen_index < asdl_seq_LEN(generators))
3146 if (!compiler_listcomp_generator(c, tmpname,
3147 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 /* only append after the last for generator */
3151 if (gen_index >= asdl_seq_LEN(generators)) {
3152 if (!compiler_nameop(c, tmpname, Load))
3153 return 0;
3154 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003155 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156
3157 compiler_use_next_block(c, skip);
3158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 for (i = 0; i < n; i++) {
3160 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 if (i == 0)
3162 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 ADDOP(c, POP_TOP);
3164 }
3165 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3166 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 return 0;
3171
3172 return 1;
3173}
3174
3175static int
3176compiler_listcomp(struct compiler *c, expr_ty e)
3177{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 static identifier append;
3181 asdl_seq *generators = e->v.ListComp.generators;
3182
3183 assert(e->kind == ListComp_kind);
3184 if (!append) {
3185 append = PyString_InternFromString("append");
3186 if (!append)
3187 return 0;
3188 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003189 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 if (!tmp)
3191 return 0;
3192 ADDOP_I(c, BUILD_LIST, 0);
3193 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3196 e->v.ListComp.elt);
3197 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 return rc;
3199}
3200
3201static int
3202compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 asdl_seq *generators, int gen_index,
3204 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003205{
3206 /* generate code for the iterator, then each of the ifs,
3207 and then write to the element */
3208
3209 comprehension_ty ge;
3210 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
3213 start = compiler_new_block(c);
3214 skip = compiler_new_block(c);
3215 if_cleanup = compiler_new_block(c);
3216 anchor = compiler_new_block(c);
3217 end = compiler_new_block(c);
3218
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 anchor == NULL || end == NULL)
3221 return 0;
3222
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003223 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003224 ADDOP_JREL(c, SETUP_LOOP, end);
3225 if (!compiler_push_fblock(c, LOOP, start))
3226 return 0;
3227
3228 if (gen_index == 0) {
3229 /* Receive outermost iter as an implicit argument */
3230 c->u->u_argcount = 1;
3231 ADDOP_I(c, LOAD_FAST, 0);
3232 }
3233 else {
3234 /* Sub-iter - calculate on the fly */
3235 VISIT(c, expr, ge->iter);
3236 ADDOP(c, GET_ITER);
3237 }
3238 compiler_use_next_block(c, start);
3239 ADDOP_JREL(c, FOR_ITER, anchor);
3240 NEXT_BLOCK(c);
3241 VISIT(c, expr, ge->target);
3242
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003243 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 n = asdl_seq_LEN(ge->ifs);
3245 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003246 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 VISIT(c, expr, e);
3248 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3249 NEXT_BLOCK(c);
3250 ADDOP(c, POP_TOP);
3251 }
3252
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003253 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3255 return 0;
3256
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003257 /* only append after the last 'for' generator */
3258 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259 VISIT(c, expr, elt);
3260 ADDOP(c, YIELD_VALUE);
3261 ADDOP(c, POP_TOP);
3262
3263 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 for (i = 0; i < n; i++) {
3266 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003267 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 compiler_use_next_block(c, if_cleanup);
3269
3270 ADDOP(c, POP_TOP);
3271 }
3272 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3273 compiler_use_next_block(c, anchor);
3274 ADDOP(c, POP_BLOCK);
3275 compiler_pop_fblock(c, LOOP, start);
3276 compiler_use_next_block(c, end);
3277
3278 return 1;
3279}
3280
3281static int
3282compiler_genexp(struct compiler *c, expr_ty e)
3283{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003284 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 PyCodeObject *co;
3286 expr_ty outermost_iter = ((comprehension_ty)
3287 (asdl_seq_GET(e->v.GeneratorExp.generators,
3288 0)))->iter;
3289
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003290 if (!name) {
3291 name = PyString_FromString("<genexpr>");
3292 if (!name)
3293 return 0;
3294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295
3296 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3297 return 0;
3298 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3299 e->v.GeneratorExp.elt);
3300 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003301 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 if (co == NULL)
3303 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003305 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003306 Py_DECREF(co);
3307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 VISIT(c, expr, outermost_iter);
3309 ADDOP(c, GET_ITER);
3310 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311
3312 return 1;
3313}
3314
3315static int
3316compiler_visit_keyword(struct compiler *c, keyword_ty k)
3317{
3318 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3319 VISIT(c, expr, k->value);
3320 return 1;
3321}
3322
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003323/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 whether they are true or false.
3325
3326 Return values: 1 for true, 0 for false, -1 for non-constant.
3327 */
3328
3329static int
3330expr_constant(expr_ty e)
3331{
3332 switch (e->kind) {
3333 case Num_kind:
3334 return PyObject_IsTrue(e->v.Num.n);
3335 case Str_kind:
3336 return PyObject_IsTrue(e->v.Str.s);
3337 default:
3338 return -1;
3339 }
3340}
3341
Guido van Rossumc2e20742006-02-27 22:32:47 +00003342/*
3343 Implements the with statement from PEP 343.
3344
3345 The semantics outlined in that PEP are as follows:
3346
3347 with EXPR as VAR:
3348 BLOCK
3349
3350 It is implemented roughly as:
3351
3352 context = (EXPR).__context__()
3353 exit = context.__exit__ # not calling it
3354 value = context.__enter__()
3355 try:
3356 VAR = value # if VAR present in the syntax
3357 BLOCK
3358 finally:
3359 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003360 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003362 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003363 exit(*exc)
3364 */
3365static int
3366compiler_with(struct compiler *c, stmt_ty s)
3367{
3368 static identifier context_attr, enter_attr, exit_attr;
3369 basicblock *block, *finally;
3370 identifier tmpexit, tmpvalue = NULL;
3371
3372 assert(s->kind == With_kind);
3373
3374 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003375 context_attr = PyString_InternFromString("__context__");
3376 if (!context_attr)
3377 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003378 }
3379 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003380 enter_attr = PyString_InternFromString("__enter__");
3381 if (!enter_attr)
3382 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003383 }
3384 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003385 exit_attr = PyString_InternFromString("__exit__");
3386 if (!exit_attr)
3387 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003388 }
3389
3390 block = compiler_new_block(c);
3391 finally = compiler_new_block(c);
3392 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003393 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003394
3395 /* Create a temporary variable to hold context.__exit__ */
3396 tmpexit = compiler_new_tmpname(c);
3397 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003398 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003399 PyArena_AddPyObject(c->c_arena, tmpexit);
3400
3401 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003402 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003403 We need to do this rather than preserving it on the stack
3404 because SETUP_FINALLY remembers the stack level.
3405 We need to do the assignment *inside* the try/finally
3406 so that context.__exit__() is called when the assignment
3407 fails. But we need to call context.__enter__() *before*
3408 the try/finally so that if it fails we won't call
3409 context.__exit__().
3410 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003411 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003412 if (tmpvalue == NULL)
3413 return 0;
3414 PyArena_AddPyObject(c->c_arena, tmpvalue);
3415 }
3416
3417 /* Evaluate (EXPR).__context__() */
3418 VISIT(c, expr, s->v.With.context_expr);
3419 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3420 ADDOP_I(c, CALL_FUNCTION, 0);
3421
3422 /* Squirrel away context.__exit__ */
3423 ADDOP(c, DUP_TOP);
3424 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3425 if (!compiler_nameop(c, tmpexit, Store))
3426 return 0;
3427
3428 /* Call context.__enter__() */
3429 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3430 ADDOP_I(c, CALL_FUNCTION, 0);
3431
3432 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 /* Store it in tmpvalue */
3434 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003435 return 0;
3436 }
3437 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003438 /* Discard result from context.__enter__() */
3439 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003440 }
3441
3442 /* Start the try block */
3443 ADDOP_JREL(c, SETUP_FINALLY, finally);
3444
3445 compiler_use_next_block(c, block);
3446 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003448 }
3449
3450 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003451 /* Bind saved result of context.__enter__() to VAR */
3452 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003453 !compiler_nameop(c, tmpvalue, Del))
3454 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003456 }
3457
3458 /* BLOCK code */
3459 VISIT_SEQ(c, stmt, s->v.With.body);
3460
3461 /* End of try block; start the finally block */
3462 ADDOP(c, POP_BLOCK);
3463 compiler_pop_fblock(c, FINALLY_TRY, block);
3464
3465 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3466 compiler_use_next_block(c, finally);
3467 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003469
3470 /* Finally block starts; push tmpexit and issue our magic opcode. */
3471 if (!compiler_nameop(c, tmpexit, Load) ||
3472 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003474 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003475
3476 /* Finally block ends. */
3477 ADDOP(c, END_FINALLY);
3478 compiler_pop_fblock(c, FINALLY_END, finally);
3479 return 1;
3480}
3481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482static int
3483compiler_visit_expr(struct compiler *c, expr_ty e)
3484{
3485 int i, n;
3486
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003487 /* If expr e has a different line number than the last expr/stmt,
3488 set a new line number for the next instruction.
3489 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490 if (e->lineno > c->u->u_lineno) {
3491 c->u->u_lineno = e->lineno;
3492 c->u->u_lineno_set = false;
3493 }
3494 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003497 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003498 VISIT(c, expr, e->v.BinOp.left);
3499 VISIT(c, expr, e->v.BinOp.right);
3500 ADDOP(c, binop(c, e->v.BinOp.op));
3501 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 VISIT(c, expr, e->v.UnaryOp.operand);
3504 ADDOP(c, unaryop(e->v.UnaryOp.op));
3505 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003508 case IfExp_kind:
3509 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003510 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003511 /* XXX get rid of arg? */
3512 ADDOP_I(c, BUILD_MAP, 0);
3513 n = asdl_seq_LEN(e->v.Dict.values);
3514 /* We must arrange things just right for STORE_SUBSCR.
3515 It wants the stack to look like (value) (dict) (key) */
3516 for (i = 0; i < n; i++) {
3517 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003518 VISIT(c, expr,
3519 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003520 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003521 VISIT(c, expr,
3522 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523 ADDOP(c, STORE_SUBSCR);
3524 }
3525 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003528 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 return compiler_genexp(c, e);
3530 case Yield_kind:
3531 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003532 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003533 /*
3534 for (i = 0; i < c->u->u_nfblocks; i++) {
3535 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3536 return compiler_error(
3537 c, "'yield' not allowed in a 'try' "
3538 "block with a 'finally' clause");
3539 }
3540 */
3541 if (e->v.Yield.value) {
3542 VISIT(c, expr, e->v.Yield.value);
3543 }
3544 else {
3545 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3546 }
3547 ADDOP(c, YIELD_VALUE);
3548 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003549 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003551 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003553 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 VISIT(c, expr, e->v.Repr.value);
3555 ADDOP(c, UNARY_CONVERT);
3556 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3559 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003560 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3562 break;
3563 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003564 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 if (e->v.Attribute.ctx != AugStore)
3566 VISIT(c, expr, e->v.Attribute.value);
3567 switch (e->v.Attribute.ctx) {
3568 case AugLoad:
3569 ADDOP(c, DUP_TOP);
3570 /* Fall through to load */
3571 case Load:
3572 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3573 break;
3574 case AugStore:
3575 ADDOP(c, ROT_TWO);
3576 /* Fall through to save */
3577 case Store:
3578 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3579 break;
3580 case Del:
3581 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3582 break;
3583 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003584 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003585 PyErr_SetString(PyExc_SystemError,
3586 "param invalid in attribute expression");
3587 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 }
3589 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003590 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003591 switch (e->v.Subscript.ctx) {
3592 case AugLoad:
3593 VISIT(c, expr, e->v.Subscript.value);
3594 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3595 break;
3596 case Load:
3597 VISIT(c, expr, e->v.Subscript.value);
3598 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3599 break;
3600 case AugStore:
3601 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3602 break;
3603 case Store:
3604 VISIT(c, expr, e->v.Subscript.value);
3605 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3606 break;
3607 case Del:
3608 VISIT(c, expr, e->v.Subscript.value);
3609 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3610 break;
3611 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003612 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003613 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003614 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003615 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 }
3617 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003618 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3620 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003623 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624 return compiler_tuple(c, e);
3625 }
3626 return 1;
3627}
3628
3629static int
3630compiler_augassign(struct compiler *c, stmt_ty s)
3631{
3632 expr_ty e = s->v.AugAssign.target;
3633 expr_ty auge;
3634
3635 assert(s->kind == AugAssign_kind);
3636
3637 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003638 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003640 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003641 if (auge == NULL)
3642 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643 VISIT(c, expr, auge);
3644 VISIT(c, expr, s->v.AugAssign.value);
3645 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3646 auge->v.Attribute.ctx = AugStore;
3647 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 break;
3649 case Subscript_kind:
3650 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003651 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003652 if (auge == NULL)
3653 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 VISIT(c, expr, auge);
3655 VISIT(c, expr, s->v.AugAssign.value);
3656 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003657 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003659 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003660 case Name_kind:
3661 VISIT(c, expr, s->v.AugAssign.target);
3662 VISIT(c, expr, s->v.AugAssign.value);
3663 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3664 return compiler_nameop(c, e->v.Name.id, Store);
3665 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003666 PyErr_Format(PyExc_SystemError,
3667 "invalid node type (%d) for augmented assignment",
3668 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 }
3671 return 1;
3672}
3673
3674static int
3675compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3676{
3677 struct fblockinfo *f;
3678 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3679 return 0;
3680 f = &c->u->u_fblock[c->u->u_nfblocks++];
3681 f->fb_type = t;
3682 f->fb_block = b;
3683 return 1;
3684}
3685
3686static void
3687compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3688{
3689 struct compiler_unit *u = c->u;
3690 assert(u->u_nfblocks > 0);
3691 u->u_nfblocks--;
3692 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3693 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3694}
3695
3696/* Raises a SyntaxError and returns 0.
3697 If something goes wrong, a different exception may be raised.
3698*/
3699
3700static int
3701compiler_error(struct compiler *c, const char *errstr)
3702{
3703 PyObject *loc;
3704 PyObject *u = NULL, *v = NULL;
3705
3706 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3707 if (!loc) {
3708 Py_INCREF(Py_None);
3709 loc = Py_None;
3710 }
3711 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3712 Py_None, loc);
3713 if (!u)
3714 goto exit;
3715 v = Py_BuildValue("(zO)", errstr, u);
3716 if (!v)
3717 goto exit;
3718 PyErr_SetObject(PyExc_SyntaxError, v);
3719 exit:
3720 Py_DECREF(loc);
3721 Py_XDECREF(u);
3722 Py_XDECREF(v);
3723 return 0;
3724}
3725
3726static int
3727compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003732 /* XXX this code is duplicated */
3733 switch (ctx) {
3734 case AugLoad: /* fall through to Load */
3735 case Load: op = BINARY_SUBSCR; break;
3736 case AugStore:/* fall through to Store */
3737 case Store: op = STORE_SUBSCR; break;
3738 case Del: op = DELETE_SUBSCR; break;
3739 case Param:
3740 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003741 "invalid %s kind %d in subscript\n",
3742 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003743 return 0;
3744 }
3745 if (ctx == AugLoad) {
3746 ADDOP_I(c, DUP_TOPX, 2);
3747 }
3748 else if (ctx == AugStore) {
3749 ADDOP(c, ROT_THREE);
3750 }
3751 ADDOP(c, op);
3752 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753}
3754
3755static int
3756compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3757{
3758 int n = 2;
3759 assert(s->kind == Slice_kind);
3760
3761 /* only handles the cases where BUILD_SLICE is emitted */
3762 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003763 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764 }
3765 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003766 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003770 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771 }
3772 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 }
3775
3776 if (s->v.Slice.step) {
3777 n++;
3778 VISIT(c, expr, s->v.Slice.step);
3779 }
3780 ADDOP_I(c, BUILD_SLICE, n);
3781 return 1;
3782}
3783
3784static int
3785compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3786{
3787 int op = 0, slice_offset = 0, stack_count = 0;
3788
3789 assert(s->v.Slice.step == NULL);
3790 if (s->v.Slice.lower) {
3791 slice_offset++;
3792 stack_count++;
3793 if (ctx != AugStore)
3794 VISIT(c, expr, s->v.Slice.lower);
3795 }
3796 if (s->v.Slice.upper) {
3797 slice_offset += 2;
3798 stack_count++;
3799 if (ctx != AugStore)
3800 VISIT(c, expr, s->v.Slice.upper);
3801 }
3802
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003803 if (ctx == AugLoad) {
3804 switch (stack_count) {
3805 case 0: ADDOP(c, DUP_TOP); break;
3806 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3807 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3808 }
3809 }
3810 else if (ctx == AugStore) {
3811 switch (stack_count) {
3812 case 0: ADDOP(c, ROT_TWO); break;
3813 case 1: ADDOP(c, ROT_THREE); break;
3814 case 2: ADDOP(c, ROT_FOUR); break;
3815 }
3816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003817
3818 switch (ctx) {
3819 case AugLoad: /* fall through to Load */
3820 case Load: op = SLICE; break;
3821 case AugStore:/* fall through to Store */
3822 case Store: op = STORE_SLICE; break;
3823 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003824 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003825 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003826 PyErr_SetString(PyExc_SystemError,
3827 "param invalid in simple slice");
3828 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003829 }
3830
3831 ADDOP(c, op + slice_offset);
3832 return 1;
3833}
3834
3835static int
3836compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3837 expr_context_ty ctx)
3838{
3839 switch (s->kind) {
3840 case Ellipsis_kind:
3841 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3842 break;
3843 case Slice_kind:
3844 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003845 case Index_kind:
3846 VISIT(c, expr, s->v.Index.value);
3847 break;
3848 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003849 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003850 PyErr_SetString(PyExc_SystemError,
3851 "extended slice invalid in nested slice");
3852 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003853 }
3854 return 1;
3855}
3856
3857
3858static int
3859compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3860{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003861 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003863 case Index_kind:
3864 kindname = "index";
3865 if (ctx != AugStore) {
3866 VISIT(c, expr, s->v.Index.value);
3867 }
3868 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003869 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003870 kindname = "ellipsis";
3871 if (ctx != AugStore) {
3872 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3873 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874 break;
3875 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003876 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 if (!s->v.Slice.step)
3878 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003879 if (ctx != AugStore) {
3880 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 return 0;
3882 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003883 break;
3884 case ExtSlice_kind:
3885 kindname = "extended slice";
3886 if (ctx != AugStore) {
3887 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3888 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003889 slice_ty sub = (slice_ty)asdl_seq_GET(
3890 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003891 if (!compiler_visit_nested_slice(c, sub, ctx))
3892 return 0;
3893 }
3894 ADDOP_I(c, BUILD_TUPLE, n);
3895 }
3896 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003897 default:
3898 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003899 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003900 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003902 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903}
3904
3905/* do depth-first search of basic block graph, starting with block.
3906 post records the block indices in post-order.
3907
3908 XXX must handle implicit jumps from one block to next
3909*/
3910
3911static void
3912dfs(struct compiler *c, basicblock *b, struct assembler *a)
3913{
3914 int i;
3915 struct instr *instr = NULL;
3916
3917 if (b->b_seen)
3918 return;
3919 b->b_seen = 1;
3920 if (b->b_next != NULL)
3921 dfs(c, b->b_next, a);
3922 for (i = 0; i < b->b_iused; i++) {
3923 instr = &b->b_instr[i];
3924 if (instr->i_jrel || instr->i_jabs)
3925 dfs(c, instr->i_target, a);
3926 }
3927 a->a_postorder[a->a_nblocks++] = b;
3928}
3929
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003930static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003931stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3932{
3933 int i;
3934 struct instr *instr;
3935 if (b->b_seen || b->b_startdepth >= depth)
3936 return maxdepth;
3937 b->b_seen = 1;
3938 b->b_startdepth = depth;
3939 for (i = 0; i < b->b_iused; i++) {
3940 instr = &b->b_instr[i];
3941 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3942 if (depth > maxdepth)
3943 maxdepth = depth;
3944 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3945 if (instr->i_jrel || instr->i_jabs) {
3946 maxdepth = stackdepth_walk(c, instr->i_target,
3947 depth, maxdepth);
3948 if (instr->i_opcode == JUMP_ABSOLUTE ||
3949 instr->i_opcode == JUMP_FORWARD) {
3950 goto out; /* remaining code is dead */
3951 }
3952 }
3953 }
3954 if (b->b_next)
3955 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3956out:
3957 b->b_seen = 0;
3958 return maxdepth;
3959}
3960
3961/* Find the flow path that needs the largest stack. We assume that
3962 * cycles in the flow graph have no net effect on the stack depth.
3963 */
3964static int
3965stackdepth(struct compiler *c)
3966{
3967 basicblock *b, *entryblock;
3968 entryblock = NULL;
3969 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3970 b->b_seen = 0;
3971 b->b_startdepth = INT_MIN;
3972 entryblock = b;
3973 }
3974 return stackdepth_walk(c, entryblock, 0, 0);
3975}
3976
3977static int
3978assemble_init(struct assembler *a, int nblocks, int firstlineno)
3979{
3980 memset(a, 0, sizeof(struct assembler));
3981 a->a_lineno = firstlineno;
3982 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3983 if (!a->a_bytecode)
3984 return 0;
3985 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3986 if (!a->a_lnotab)
3987 return 0;
3988 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003989 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003990 if (!a->a_postorder) {
3991 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003992 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003993 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994 return 1;
3995}
3996
3997static void
3998assemble_free(struct assembler *a)
3999{
4000 Py_XDECREF(a->a_bytecode);
4001 Py_XDECREF(a->a_lnotab);
4002 if (a->a_postorder)
4003 PyObject_Free(a->a_postorder);
4004}
4005
4006/* Return the size of a basic block in bytes. */
4007
4008static int
4009instrsize(struct instr *instr)
4010{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004011 if (!instr->i_hasarg)
4012 return 1;
4013 if (instr->i_oparg > 0xffff)
4014 return 6;
4015 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004016}
4017
4018static int
4019blocksize(basicblock *b)
4020{
4021 int i;
4022 int size = 0;
4023
4024 for (i = 0; i < b->b_iused; i++)
4025 size += instrsize(&b->b_instr[i]);
4026 return size;
4027}
4028
4029/* All about a_lnotab.
4030
4031c_lnotab is an array of unsigned bytes disguised as a Python string.
4032It is used to map bytecode offsets to source code line #s (when needed
4033for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004034
Tim Peters2a7f3842001-06-09 09:26:21 +00004035The array is conceptually a list of
4036 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004037pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004038
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004039 byte code offset source code line number
4040 0 1
4041 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004042 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004043 350 307
4044 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004045
4046The first trick is that these numbers aren't stored, only the increments
4047from one row to the next (this doesn't really work, but it's a start):
4048
4049 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4050
4051The second trick is that an unsigned byte can't hold negative values, or
4052values larger than 255, so (a) there's a deep assumption that byte code
4053offsets and their corresponding line #s both increase monotonically, and (b)
4054if at least one column jumps by more than 255 from one row to the next, more
4055than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004056from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004057part. A user of c_lnotab desiring to find the source line number
4058corresponding to a bytecode address A should do something like this
4059
4060 lineno = addr = 0
4061 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004062 addr += addr_incr
4063 if addr > A:
4064 return lineno
4065 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004066
4067In order for this to work, when the addr field increments by more than 255,
4068the line # increment in each pair generated must be 0 until the remaining addr
4069increment is < 256. So, in the example above, com_set_lineno should not (as
4070was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004071255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004072*/
4073
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004074static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004076{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077 int d_bytecode, d_lineno;
4078 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004079 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080
4081 d_bytecode = a->a_offset - a->a_lineno_off;
4082 d_lineno = i->i_lineno - a->a_lineno;
4083
4084 assert(d_bytecode >= 0);
4085 assert(d_lineno >= 0);
4086
4087 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004088 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004089
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004091 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004092 nbytes = a->a_lnotab_off + 2 * ncodes;
4093 len = PyString_GET_SIZE(a->a_lnotab);
4094 if (nbytes >= len) {
4095 if (len * 2 < nbytes)
4096 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004097 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 len *= 2;
4099 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4100 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004101 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004102 lnotab = (unsigned char *)
4103 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004104 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004105 *lnotab++ = 255;
4106 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004107 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004108 d_bytecode -= ncodes * 255;
4109 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004110 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 assert(d_bytecode <= 255);
4112 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004113 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 nbytes = a->a_lnotab_off + 2 * ncodes;
4115 len = PyString_GET_SIZE(a->a_lnotab);
4116 if (nbytes >= len) {
4117 if (len * 2 < nbytes)
4118 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004119 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120 len *= 2;
4121 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4122 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004123 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004124 lnotab = (unsigned char *)
4125 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126 *lnotab++ = 255;
4127 *lnotab++ = d_bytecode;
4128 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004129 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 *lnotab++ = 255;
4131 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004132 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133 d_lineno -= ncodes * 255;
4134 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004135 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 len = PyString_GET_SIZE(a->a_lnotab);
4138 if (a->a_lnotab_off + 2 >= len) {
4139 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004140 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004141 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004142 lnotab = (unsigned char *)
4143 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145 a->a_lnotab_off += 2;
4146 if (d_bytecode) {
4147 *lnotab++ = d_bytecode;
4148 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004149 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004150 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151 *lnotab++ = 0;
4152 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004153 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154 a->a_lineno = i->i_lineno;
4155 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004156 return 1;
4157}
4158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159/* assemble_emit()
4160 Extend the bytecode with a new instruction.
4161 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004162*/
4163
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004164static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004166{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004167 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168 int len = PyString_GET_SIZE(a->a_bytecode);
4169 char *code;
4170
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004171 size = instrsize(i);
4172 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004174 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004175 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004177 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178 if (a->a_offset + size >= len) {
4179 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004180 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004181 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4183 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004184 if (size == 6) {
4185 assert(i->i_hasarg);
4186 *code++ = (char)EXTENDED_ARG;
4187 *code++ = ext & 0xff;
4188 *code++ = ext >> 8;
4189 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004192 if (i->i_hasarg) {
4193 assert(size == 3 || size == 6);
4194 *code++ = arg & 0xff;
4195 *code++ = arg >> 8;
4196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004198}
4199
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004200static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004202{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004203 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004204 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004205 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004206
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207 /* Compute the size of each block and fixup jump args.
4208 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004209start:
4210 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004212 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004213 bsize = blocksize(b);
4214 b->b_offset = totsize;
4215 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004216 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004217 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4219 bsize = b->b_offset;
4220 for (i = 0; i < b->b_iused; i++) {
4221 struct instr *instr = &b->b_instr[i];
4222 /* Relative jumps are computed relative to
4223 the instruction pointer after fetching
4224 the jump instruction.
4225 */
4226 bsize += instrsize(instr);
4227 if (instr->i_jabs)
4228 instr->i_oparg = instr->i_target->b_offset;
4229 else if (instr->i_jrel) {
4230 int delta = instr->i_target->b_offset - bsize;
4231 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004232 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004233 else
4234 continue;
4235 if (instr->i_oparg > 0xffff)
4236 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004237 }
4238 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004239
4240 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004241 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004242 with a better solution.
4243
4244 In the meantime, should the goto be dropped in favor
4245 of a loop?
4246
4247 The issue is that in the first loop blocksize() is called
4248 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004249 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004250 i_oparg is calculated in the second loop above.
4251
4252 So we loop until we stop seeing new EXTENDED_ARGs.
4253 The only EXTENDED_ARGs that could be popping up are
4254 ones in jump instructions. So this should converge
4255 fairly quickly.
4256 */
4257 if (last_extended_arg_count != extended_arg_count) {
4258 last_extended_arg_count = extended_arg_count;
4259 goto start;
4260 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004261}
4262
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004263static PyObject *
4264dict_keys_inorder(PyObject *dict, int offset)
4265{
4266 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004267 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004268
4269 tuple = PyTuple_New(size);
4270 if (tuple == NULL)
4271 return NULL;
4272 while (PyDict_Next(dict, &pos, &k, &v)) {
4273 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004274 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004275 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004276 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004277 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004278 PyTuple_SET_ITEM(tuple, i - offset, k);
4279 }
4280 return tuple;
4281}
4282
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004283static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004285{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004286 PySTEntryObject *ste = c->u->u_ste;
4287 int flags = 0, n;
4288 if (ste->ste_type != ModuleBlock)
4289 flags |= CO_NEWLOCALS;
4290 if (ste->ste_type == FunctionBlock) {
4291 if (!ste->ste_unoptimized)
4292 flags |= CO_OPTIMIZED;
4293 if (ste->ste_nested)
4294 flags |= CO_NESTED;
4295 if (ste->ste_generator)
4296 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004297 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004298 if (ste->ste_varargs)
4299 flags |= CO_VARARGS;
4300 if (ste->ste_varkeywords)
4301 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004302 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004303 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004304
4305 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004306 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308 n = PyDict_Size(c->u->u_freevars);
4309 if (n < 0)
4310 return -1;
4311 if (n == 0) {
4312 n = PyDict_Size(c->u->u_cellvars);
4313 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004314 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004315 if (n == 0) {
4316 flags |= CO_NOFREE;
4317 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004318 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004319
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004320 return flags;
4321}
4322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323static PyCodeObject *
4324makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004325{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326 PyObject *tmp;
4327 PyCodeObject *co = NULL;
4328 PyObject *consts = NULL;
4329 PyObject *names = NULL;
4330 PyObject *varnames = NULL;
4331 PyObject *filename = NULL;
4332 PyObject *name = NULL;
4333 PyObject *freevars = NULL;
4334 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004335 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004336 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004338 tmp = dict_keys_inorder(c->u->u_consts, 0);
4339 if (!tmp)
4340 goto error;
4341 consts = PySequence_List(tmp); /* optimize_code requires a list */
4342 Py_DECREF(tmp);
4343
4344 names = dict_keys_inorder(c->u->u_names, 0);
4345 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4346 if (!consts || !names || !varnames)
4347 goto error;
4348
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004349 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4350 if (!cellvars)
4351 goto error;
4352 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4353 if (!freevars)
4354 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004355 filename = PyString_FromString(c->c_filename);
4356 if (!filename)
4357 goto error;
4358
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004359 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004360 flags = compute_code_flags(c);
4361 if (flags < 0)
4362 goto error;
4363
4364 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4365 if (!bytecode)
4366 goto error;
4367
4368 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4369 if (!tmp)
4370 goto error;
4371 Py_DECREF(consts);
4372 consts = tmp;
4373
4374 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4375 bytecode, consts, names, varnames,
4376 freevars, cellvars,
4377 filename, c->u->u_name,
4378 c->u->u_firstlineno,
4379 a->a_lnotab);
4380 error:
4381 Py_XDECREF(consts);
4382 Py_XDECREF(names);
4383 Py_XDECREF(varnames);
4384 Py_XDECREF(filename);
4385 Py_XDECREF(name);
4386 Py_XDECREF(freevars);
4387 Py_XDECREF(cellvars);
4388 Py_XDECREF(bytecode);
4389 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004390}
4391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004392static PyCodeObject *
4393assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004394{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395 basicblock *b, *entryblock;
4396 struct assembler a;
4397 int i, j, nblocks;
4398 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004399
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400 /* Make sure every block that falls off the end returns None.
4401 XXX NEXT_BLOCK() isn't quite right, because if the last
4402 block ends with a jump or return b_next shouldn't set.
4403 */
4404 if (!c->u->u_curblock->b_return) {
4405 NEXT_BLOCK(c);
4406 if (addNone)
4407 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4408 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004409 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411 nblocks = 0;
4412 entryblock = NULL;
4413 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4414 nblocks++;
4415 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004416 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4419 goto error;
4420 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004421
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004423 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425 /* Emit code in reverse postorder from dfs. */
4426 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004427 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428 for (j = 0; j < b->b_iused; j++)
4429 if (!assemble_emit(&a, &b->b_instr[j]))
4430 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004431 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4434 goto error;
4435 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4436 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004437
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438 co = makecode(c, &a);
4439 error:
4440 assemble_free(&a);
4441 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004442}