blob: 8341cc93bbb6e8f495531307573b1f5346d4b22f [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
146 int c_interactive;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
190
191static int inplace_binop(struct compiler *, operator_ty);
192static int expr_constant(expr_ty e);
193
Guido van Rossumc2e20742006-02-27 22:32:47 +0000194static int compiler_with(struct compiler *, stmt_ty);
195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static PyCodeObject *assemble(struct compiler *, int addNone);
197static PyObject *__doc__;
198
199PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +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;
Anthony Baxter7b782b62006-04-11 12:01:56 +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 }
Anthony Baxter7b782b62006-04-11 12:01:56 +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)
Neal Norwitz14bc4e42006-04-10 06:57:06 +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;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000337 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000380 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000394/* Begin: Peephole optimizations ----------------------------------------- */
395
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000396#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000398#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
399#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000400#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define ISBASICBLOCK(blocks, start, bytes) \
403 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000410 Bails out with no change if one or more of the LOAD_CONSTs is missing.
411 Also works for BUILD_LIST when followed by an "in" or "not in" test.
412*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413static int
414tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
415{
416 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418
419 /* Pre-conditions */
420 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000421 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000424 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425
426 /* Buildup new tuple of constants */
427 newconst = PyTuple_New(n);
428 if (newconst == NULL)
429 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 for (i=0 ; i<n ; i++) {
432 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 constant = PyList_GET_ITEM(consts, arg);
435 Py_INCREF(constant);
436 PyTuple_SET_ITEM(newconst, i, constant);
437 }
438
439 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 if (PyList_Append(consts, newconst)) {
441 Py_DECREF(newconst);
442 return 0;
443 }
444 Py_DECREF(newconst);
445
446 /* Write NOPs over old LOAD_CONSTS and
447 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
448 memset(codestr, NOP, n*3);
449 codestr[n*3] = LOAD_CONST;
450 SETARG(codestr, (n*3), len_consts);
451 return 1;
452}
453
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000458 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000459 Abandons the transformation if the folding fails (i.e. 1+'a').
460 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 is below a threshold value. That keeps pyc files from
462 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000463*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000464static int
465fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
466{
467 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t len_consts, size;
469 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000470
471 /* Pre-conditions */
472 assert(PyList_CheckExact(consts));
473 assert(codestr[0] == LOAD_CONST);
474 assert(codestr[3] == LOAD_CONST);
475
476 /* Create new constant */
477 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
478 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
479 opcode = codestr[6];
480 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 case BINARY_POWER:
482 newconst = PyNumber_Power(v, w, Py_None);
483 break;
484 case BINARY_MULTIPLY:
485 newconst = PyNumber_Multiply(v, w);
486 break;
487 case BINARY_DIVIDE:
488 /* Cannot fold this operation statically since
489 the result can depend on the run-time presence
490 of the -Qnew flag */
491 return 0;
492 case BINARY_TRUE_DIVIDE:
493 newconst = PyNumber_TrueDivide(v, w);
494 break;
495 case BINARY_FLOOR_DIVIDE:
496 newconst = PyNumber_FloorDivide(v, w);
497 break;
498 case BINARY_MODULO:
499 newconst = PyNumber_Remainder(v, w);
500 break;
501 case BINARY_ADD:
502 newconst = PyNumber_Add(v, w);
503 break;
504 case BINARY_SUBTRACT:
505 newconst = PyNumber_Subtract(v, w);
506 break;
507 case BINARY_SUBSCR:
508 newconst = PyObject_GetItem(v, w);
509 break;
510 case BINARY_LSHIFT:
511 newconst = PyNumber_Lshift(v, w);
512 break;
513 case BINARY_RSHIFT:
514 newconst = PyNumber_Rshift(v, w);
515 break;
516 case BINARY_AND:
517 newconst = PyNumber_And(v, w);
518 break;
519 case BINARY_XOR:
520 newconst = PyNumber_Xor(v, w);
521 break;
522 case BINARY_OR:
523 newconst = PyNumber_Or(v, w);
524 break;
525 default:
526 /* Called with an unknown opcode */
527 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000528 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000529 opcode);
530 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000531 }
532 if (newconst == NULL) {
533 PyErr_Clear();
534 return 0;
535 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000536 size = PyObject_Size(newconst);
537 if (size == -1)
538 PyErr_Clear();
539 else if (size > 20) {
540 Py_DECREF(newconst);
541 return 0;
542 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000543
544 /* Append folded constant into consts table */
545 len_consts = PyList_GET_SIZE(consts);
546 if (PyList_Append(consts, newconst)) {
547 Py_DECREF(newconst);
548 return 0;
549 }
550 Py_DECREF(newconst);
551
552 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
553 memset(codestr, NOP, 4);
554 codestr[4] = LOAD_CONST;
555 SETARG(codestr, 4, len_consts);
556 return 1;
557}
558
Raymond Hettinger80121492005-02-20 12:41:32 +0000559static int
560fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
561{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000562 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563 Py_ssize_t len_consts;
564 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000565
566 /* Pre-conditions */
567 assert(PyList_CheckExact(consts));
568 assert(codestr[0] == LOAD_CONST);
569
570 /* Create new constant */
571 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
572 opcode = codestr[3];
573 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000574 case UNARY_NEGATIVE:
575 /* Preserve the sign of -0.0 */
576 if (PyObject_IsTrue(v) == 1)
577 newconst = PyNumber_Negative(v);
578 break;
579 case UNARY_CONVERT:
580 newconst = PyObject_Repr(v);
581 break;
582 case UNARY_INVERT:
583 newconst = PyNumber_Invert(v);
584 break;
585 default:
586 /* Called with an unknown opcode */
587 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000588 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000589 opcode);
590 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000591 }
592 if (newconst == NULL) {
593 PyErr_Clear();
594 return 0;
595 }
596
597 /* Append folded constant into consts table */
598 len_consts = PyList_GET_SIZE(consts);
599 if (PyList_Append(consts, newconst)) {
600 Py_DECREF(newconst);
601 return 0;
602 }
603 Py_DECREF(newconst);
604
605 /* Write NOP LOAD_CONST newconst */
606 codestr[0] = NOP;
607 codestr[1] = LOAD_CONST;
608 SETARG(codestr, 1, len_consts);
609 return 1;
610}
611
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612static unsigned int *
613markblocks(unsigned char *code, int len)
614{
Anthony Baxter7b782b62006-04-11 12:01:56 +0000615 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000617
618 if (blocks == NULL)
619 return NULL;
620 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000621
622 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000623 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
624 opcode = code[i];
625 switch (opcode) {
626 case FOR_ITER:
627 case JUMP_FORWARD:
628 case JUMP_IF_FALSE:
629 case JUMP_IF_TRUE:
630 case JUMP_ABSOLUTE:
631 case CONTINUE_LOOP:
632 case SETUP_LOOP:
633 case SETUP_EXCEPT:
634 case SETUP_FINALLY:
635 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000636 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000638 }
639 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000640 /* Build block numbers in the second pass */
641 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000642 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000643 blocks[i] = blockcnt;
644 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000645 return blocks;
646}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000647
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000648/* Perform basic peephole optimizations to components of a code object.
649 The consts object should still be in list form to allow new constants
650 to be appended.
651
652 To keep the optimizer simple, it bails out (does nothing) for code
653 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000654 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000655 the lineno table has complex encoding for gaps >= 255.
656
657 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000658 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000659 smaller. For those that reduce size, the gaps are initially filled with
660 NOPs. Later those NOPs are removed and the jump addresses retargeted in
661 a single pass. Line numbering is adjusted accordingly. */
662
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000664optimize_code(PyObject *code, PyObject* consts, PyObject *names,
665 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000666{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000667 Py_ssize_t i, j, codelen;
668 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000669 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000670 unsigned char *codestr = NULL;
671 unsigned char *lineno;
672 int *addrmap = NULL;
673 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000674 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000675 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000676 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000677
Raymond Hettingereffb3932004-10-30 08:55:08 +0000678 /* Bail out if an exception is set */
679 if (PyErr_Occurred())
680 goto exitUnchanged;
681
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000682 /* Bypass optimization when the lineno table is too complex */
683 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000684 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000685 tabsiz = PyString_GET_SIZE(lineno_obj);
686 if (memchr(lineno, 255, tabsiz) != NULL)
687 goto exitUnchanged;
688
Raymond Hettingera12fa142004-08-24 04:34:16 +0000689 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000690 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000692 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000693 goto exitUnchanged;
694
695 /* Make a modifiable copy of the code string */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000696 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000697 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000698 goto exitUnchanged;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000699 codestr = (unsigned char *)memcpy(codestr,
700 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000701
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000702 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000703 the various transformation patterns to look ahead several
704 instructions without additional checks to make sure they are not
705 looking beyond the end of the code string.
706 */
707 if (codestr[codelen-1] != RETURN_VALUE)
708 goto exitUnchanged;
709
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000710 /* Mapping to new jump targets after NOPs are removed */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000711 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000712 if (addrmap == NULL)
713 goto exitUnchanged;
714
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000715 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000716 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000717 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000718 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000719
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000720 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000721 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000722
723 lastlc = cumlc;
724 cumlc = 0;
725
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000726 switch (opcode) {
727
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000728 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
729 with JUMP_IF_TRUE POP_TOP */
730 case UNARY_NOT:
731 if (codestr[i+1] != JUMP_IF_FALSE ||
732 codestr[i+4] != POP_TOP ||
733 !ISBASICBLOCK(blocks,i,5))
734 continue;
735 tgt = GETJUMPTGT(codestr, (i+1));
736 if (codestr[tgt] != POP_TOP)
737 continue;
738 j = GETARG(codestr, i+1) + 1;
739 codestr[i] = JUMP_IF_TRUE;
740 SETARG(codestr, i, j);
741 codestr[i+3] = POP_TOP;
742 codestr[i+4] = NOP;
743 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000744
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000745 /* not a is b --> a is not b
746 not a in b --> a not in b
747 not a is not b --> a is b
748 not a not in b --> a in b
749 */
750 case COMPARE_OP:
751 j = GETARG(codestr, i);
752 if (j < 6 || j > 9 ||
753 codestr[i+3] != UNARY_NOT ||
754 !ISBASICBLOCK(blocks,i,4))
755 continue;
756 SETARG(codestr, i, (j^1));
757 codestr[i+3] = NOP;
758 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000759
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000760 /* Replace LOAD_GLOBAL/LOAD_NAME None
761 with LOAD_CONST None */
762 case LOAD_NAME:
763 case LOAD_GLOBAL:
764 j = GETARG(codestr, i);
765 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
766 if (name == NULL || strcmp(name, "None") != 0)
767 continue;
768 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
769 if (PyList_GET_ITEM(consts, j) == Py_None) {
770 codestr[i] = LOAD_CONST;
771 SETARG(codestr, i, j);
772 cumlc = lastlc + 1;
773 break;
774 }
775 }
776 break;
777
778 /* Skip over LOAD_CONST trueconst
779 JUMP_IF_FALSE xx POP_TOP */
780 case LOAD_CONST:
781 cumlc = lastlc + 1;
782 j = GETARG(codestr, i);
783 if (codestr[i+3] != JUMP_IF_FALSE ||
784 codestr[i+6] != POP_TOP ||
785 !ISBASICBLOCK(blocks,i,7) ||
786 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
787 continue;
788 memset(codestr+i, NOP, 7);
789 cumlc = 0;
790 break;
791
792 /* Try to fold tuples of constants (includes a case for lists
793 which are only used for "in" and "not in" tests).
794 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
795 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
796 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
797 case BUILD_TUPLE:
798 case BUILD_LIST:
799 j = GETARG(codestr, i);
800 h = i - 3 * j;
801 if (h >= 0 &&
802 j <= lastlc &&
803 ((opcode == BUILD_TUPLE &&
804 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
805 (opcode == BUILD_LIST &&
806 codestr[i+3]==COMPARE_OP &&
807 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
808 (GETARG(codestr,i+3)==6 ||
809 GETARG(codestr,i+3)==7))) &&
810 tuple_of_constants(&codestr[h], j, consts)) {
811 assert(codestr[i] == LOAD_CONST);
812 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000813 break;
814 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000815 if (codestr[i+3] != UNPACK_SEQUENCE ||
816 !ISBASICBLOCK(blocks,i,6) ||
817 j != GETARG(codestr, i+3))
818 continue;
819 if (j == 1) {
820 memset(codestr+i, NOP, 6);
821 } else if (j == 2) {
822 codestr[i] = ROT_TWO;
823 memset(codestr+i+1, NOP, 5);
824 } else if (j == 3) {
825 codestr[i] = ROT_THREE;
826 codestr[i+1] = ROT_TWO;
827 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000828 }
829 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000830
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000831 /* Fold binary ops on constants.
832 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
833 case BINARY_POWER:
834 case BINARY_MULTIPLY:
835 case BINARY_TRUE_DIVIDE:
836 case BINARY_FLOOR_DIVIDE:
837 case BINARY_MODULO:
838 case BINARY_ADD:
839 case BINARY_SUBTRACT:
840 case BINARY_SUBSCR:
841 case BINARY_LSHIFT:
842 case BINARY_RSHIFT:
843 case BINARY_AND:
844 case BINARY_XOR:
845 case BINARY_OR:
846 if (lastlc >= 2 &&
847 ISBASICBLOCK(blocks, i-6, 7) &&
848 fold_binops_on_constants(&codestr[i-6], consts)) {
849 i -= 2;
850 assert(codestr[i] == LOAD_CONST);
851 cumlc = 1;
852 }
853 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000854
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000855 /* Fold unary ops on constants.
856 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
857 case UNARY_NEGATIVE:
858 case UNARY_CONVERT:
859 case UNARY_INVERT:
860 if (lastlc >= 1 &&
861 ISBASICBLOCK(blocks, i-3, 4) &&
862 fold_unaryops_on_constants(&codestr[i-3], consts)) {
863 i -= 2;
864 assert(codestr[i] == LOAD_CONST);
865 cumlc = 1;
866 }
867 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000868
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000869 /* Simplify conditional jump to conditional jump where the
870 result of the first test implies the success of a similar
871 test or the failure of the opposite test.
872 Arises in code like:
873 "if a and b:"
874 "if a or b:"
875 "a and b or c"
876 "(a and b) and c"
877 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
878 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
879 where y+3 is the instruction following the second test.
880 */
881 case JUMP_IF_FALSE:
882 case JUMP_IF_TRUE:
883 tgt = GETJUMPTGT(codestr, i);
884 j = codestr[tgt];
885 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
886 if (j == opcode) {
887 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
888 SETARG(codestr, i, tgttgt);
889 } else {
890 tgt -= i;
891 SETARG(codestr, i, tgt);
892 }
893 break;
894 }
895 /* Intentional fallthrough */
896
897 /* Replace jumps to unconditional jumps */
898 case FOR_ITER:
899 case JUMP_FORWARD:
900 case JUMP_ABSOLUTE:
901 case CONTINUE_LOOP:
902 case SETUP_LOOP:
903 case SETUP_EXCEPT:
904 case SETUP_FINALLY:
905 tgt = GETJUMPTGT(codestr, i);
906 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
907 continue;
908 tgttgt = GETJUMPTGT(codestr, tgt);
909 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
910 opcode = JUMP_ABSOLUTE;
911 if (!ABSOLUTE_JUMP(opcode))
912 tgttgt -= i + 3; /* Calc relative jump addr */
913 if (tgttgt < 0) /* No backward relative jumps */
914 continue;
915 codestr[i] = opcode;
916 SETARG(codestr, i, tgttgt);
917 break;
918
919 case EXTENDED_ARG:
920 goto exitUnchanged;
921
922 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
923 case RETURN_VALUE:
924 if (i+4 >= codelen ||
925 codestr[i+4] != RETURN_VALUE ||
926 !ISBASICBLOCK(blocks,i,5))
927 continue;
928 memset(codestr+i+1, NOP, 4);
929 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000930 }
931 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000932
933 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000934 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
935 addrmap[i] = i - nops;
936 if (codestr[i] == NOP)
937 nops++;
938 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000939 cum_orig_line = 0;
940 last_line = 0;
941 for (i=0 ; i < tabsiz ; i+=2) {
942 cum_orig_line += lineno[i];
943 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000944 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000945 lineno[i] =((unsigned char)(new_line - last_line));
946 last_line = new_line;
947 }
948
949 /* Remove NOPs and fixup jump targets */
950 for (i=0, h=0 ; i<codelen ; ) {
951 opcode = codestr[i];
952 switch (opcode) {
953 case NOP:
954 i++;
955 continue;
956
957 case JUMP_ABSOLUTE:
958 case CONTINUE_LOOP:
959 j = addrmap[GETARG(codestr, i)];
960 SETARG(codestr, i, j);
961 break;
962
963 case FOR_ITER:
964 case JUMP_FORWARD:
965 case JUMP_IF_FALSE:
966 case JUMP_IF_TRUE:
967 case SETUP_LOOP:
968 case SETUP_EXCEPT:
969 case SETUP_FINALLY:
970 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
971 SETARG(codestr, i, j);
972 break;
973 }
974 adj = CODESIZE(opcode);
975 while (adj--)
976 codestr[h++] = codestr[i++];
977 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000978 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000979
980 code = PyString_FromStringAndSize((char *)codestr, h);
981 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000982 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000983 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000984 return code;
985
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000987 if (blocks != NULL)
988 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000989 if (addrmap != NULL)
990 PyMem_Free(addrmap);
991 if (codestr != NULL)
992 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000993 Py_INCREF(code);
994 return code;
995}
996
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000997/* End: Peephole optimizations ----------------------------------------- */
998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999/*
1000
1001Leave this debugging code for just a little longer.
1002
1003static void
1004compiler_display_symbols(PyObject *name, PyObject *symbols)
1005{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006PyObject *key, *value;
1007int flags;
1008Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1011while (PyDict_Next(symbols, &pos, &key, &value)) {
1012flags = PyInt_AsLong(value);
1013fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1014if (flags & DEF_GLOBAL)
1015fprintf(stderr, " declared_global");
1016if (flags & DEF_LOCAL)
1017fprintf(stderr, " local");
1018if (flags & DEF_PARAM)
1019fprintf(stderr, " param");
1020if (flags & DEF_STAR)
1021fprintf(stderr, " stararg");
1022if (flags & DEF_DOUBLESTAR)
1023fprintf(stderr, " starstar");
1024if (flags & DEF_INTUPLE)
1025fprintf(stderr, " tuple");
1026if (flags & DEF_FREE)
1027fprintf(stderr, " free");
1028if (flags & DEF_FREE_GLOBAL)
1029fprintf(stderr, " global");
1030if (flags & DEF_FREE_CLASS)
1031fprintf(stderr, " free/class");
1032if (flags & DEF_IMPORT)
1033fprintf(stderr, " import");
1034fprintf(stderr, "\n");
1035}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 fprintf(stderr, "\n");
1037}
1038*/
1039
1040static void
1041compiler_unit_check(struct compiler_unit *u)
1042{
1043 basicblock *block;
1044 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1045 assert(block != (void *)0xcbcbcbcb);
1046 assert(block != (void *)0xfbfbfbfb);
1047 assert(block != (void *)0xdbdbdbdb);
1048 if (block->b_instr != NULL) {
1049 assert(block->b_ialloc > 0);
1050 assert(block->b_iused > 0);
1051 assert(block->b_ialloc >= block->b_iused);
1052 }
1053 else {
1054 assert (block->b_iused == 0);
1055 assert (block->b_ialloc == 0);
1056 }
1057 }
1058}
1059
1060static void
1061compiler_unit_free(struct compiler_unit *u)
1062{
1063 basicblock *b, *next;
1064
1065 compiler_unit_check(u);
1066 b = u->u_blocks;
1067 while (b != NULL) {
1068 if (b->b_instr)
1069 PyObject_Free((void *)b->b_instr);
1070 next = b->b_list;
1071 PyObject_Free((void *)b);
1072 b = next;
1073 }
1074 Py_XDECREF(u->u_ste);
1075 Py_XDECREF(u->u_name);
1076 Py_XDECREF(u->u_consts);
1077 Py_XDECREF(u->u_names);
1078 Py_XDECREF(u->u_varnames);
1079 Py_XDECREF(u->u_freevars);
1080 Py_XDECREF(u->u_cellvars);
1081 Py_XDECREF(u->u_private);
1082 PyObject_Free(u);
1083}
1084
1085static int
1086compiler_enter_scope(struct compiler *c, identifier name, void *key,
1087 int lineno)
1088{
1089 struct compiler_unit *u;
1090
Anthony Baxter7b782b62006-04-11 12:01:56 +00001091 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1092 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001093 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001094 PyErr_NoMemory();
1095 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001096 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 u->u_argcount = 0;
1099 u->u_ste = PySymtable_Lookup(c->c_st, key);
1100 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001101 compiler_unit_free(u);
1102 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 }
1104 Py_INCREF(name);
1105 u->u_name = name;
1106 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1107 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1108 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001109 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001110
1111 u->u_blocks = NULL;
1112 u->u_tmpname = 0;
1113 u->u_nfblocks = 0;
1114 u->u_firstlineno = lineno;
1115 u->u_lineno = 0;
1116 u->u_lineno_set = false;
1117 u->u_consts = PyDict_New();
1118 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001119 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return 0;
1121 }
1122 u->u_names = PyDict_New();
1123 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001124 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125 return 0;
1126 }
1127
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001128 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129
1130 /* Push the old compiler_unit on the stack. */
1131 if (c->u) {
1132 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1133 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001134 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 return 0;
1136 }
1137 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 u->u_private = c->u->u_private;
1139 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 }
1141 c->u = u;
1142
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001143 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001144 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 return 0;
1146
1147 return 1;
1148}
1149
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001150static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151compiler_exit_scope(struct compiler *c)
1152{
1153 int n;
1154 PyObject *wrapper;
1155
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001156 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 compiler_unit_free(c->u);
1158 /* Restore c->u to the parent unit. */
1159 n = PyList_GET_SIZE(c->c_stack) - 1;
1160 if (n >= 0) {
1161 wrapper = PyList_GET_ITEM(c->c_stack, n);
1162 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001163 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001165 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166 compiler_unit_check(c->u);
1167 }
1168 else
1169 c->u = NULL;
1170
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171}
1172
Guido van Rossumc2e20742006-02-27 22:32:47 +00001173/* Allocate a new "anonymous" local variable.
1174 Used by list comprehensions and with statements.
1175*/
1176
1177static PyObject *
1178compiler_new_tmpname(struct compiler *c)
1179{
1180 char tmpname[256];
1181 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1182 return PyString_FromString(tmpname);
1183}
1184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185/* Allocate a new block and return a pointer to it.
1186 Returns NULL on error.
1187*/
1188
1189static basicblock *
1190compiler_new_block(struct compiler *c)
1191{
1192 basicblock *b;
1193 struct compiler_unit *u;
1194
1195 u = c->u;
1196 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001197 if (b == NULL) {
1198 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001199 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001200 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001202 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203 b->b_list = u->u_blocks;
1204 u->u_blocks = b;
1205 return b;
1206}
1207
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208static basicblock *
1209compiler_use_new_block(struct compiler *c)
1210{
1211 basicblock *block = compiler_new_block(c);
1212 if (block == NULL)
1213 return NULL;
1214 c->u->u_curblock = block;
1215 return block;
1216}
1217
1218static basicblock *
1219compiler_next_block(struct compiler *c)
1220{
1221 basicblock *block = compiler_new_block(c);
1222 if (block == NULL)
1223 return NULL;
1224 c->u->u_curblock->b_next = block;
1225 c->u->u_curblock = block;
1226 return block;
1227}
1228
1229static basicblock *
1230compiler_use_next_block(struct compiler *c, basicblock *block)
1231{
1232 assert(block != NULL);
1233 c->u->u_curblock->b_next = block;
1234 c->u->u_curblock = block;
1235 return block;
1236}
1237
1238/* Returns the offset of the next instruction in the current block's
1239 b_instr array. Resizes the b_instr as necessary.
1240 Returns -1 on failure.
1241 */
1242
1243static int
1244compiler_next_instr(struct compiler *c, basicblock *b)
1245{
1246 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001247 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001248 b->b_instr = (struct instr *)PyObject_Malloc(
1249 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001250 if (b->b_instr == NULL) {
1251 PyErr_NoMemory();
1252 return -1;
1253 }
1254 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1255 memset((char *)b->b_instr, 0,
1256 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001258 else if (b->b_iused == b->b_ialloc) {
1259 size_t oldsize, newsize;
1260 oldsize = b->b_ialloc * sizeof(struct instr);
1261 newsize = oldsize << 1;
1262 if (newsize == 0) {
1263 PyErr_NoMemory();
1264 return -1;
1265 }
1266 b->b_ialloc <<= 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001267 b->b_instr = (struct instr *)PyObject_Realloc(
1268 (void *)b->b_instr, newsize);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001269 if (b->b_instr == NULL)
1270 return -1;
1271 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1272 }
1273 return b->b_iused++;
1274}
1275
Jeremy Hylton12603c42006-04-01 16:18:02 +00001276/* Set the i_lineno member of the instruction at offse off if the
1277 line number for the current expression/statement (?) has not
1278 already been set. If it has been set, the call has no effect.
1279
1280 Every time a new node is b
1281 */
1282
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283static void
1284compiler_set_lineno(struct compiler *c, int off)
1285{
1286 basicblock *b;
1287 if (c->u->u_lineno_set)
1288 return;
1289 c->u->u_lineno_set = true;
1290 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001291 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292}
1293
1294static int
1295opcode_stack_effect(int opcode, int oparg)
1296{
1297 switch (opcode) {
1298 case POP_TOP:
1299 return -1;
1300 case ROT_TWO:
1301 case ROT_THREE:
1302 return 0;
1303 case DUP_TOP:
1304 return 1;
1305 case ROT_FOUR:
1306 return 0;
1307
1308 case UNARY_POSITIVE:
1309 case UNARY_NEGATIVE:
1310 case UNARY_NOT:
1311 case UNARY_CONVERT:
1312 case UNARY_INVERT:
1313 return 0;
1314
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001315 case LIST_APPEND:
1316 return -2;
1317
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001318 case BINARY_POWER:
1319 case BINARY_MULTIPLY:
1320 case BINARY_DIVIDE:
1321 case BINARY_MODULO:
1322 case BINARY_ADD:
1323 case BINARY_SUBTRACT:
1324 case BINARY_SUBSCR:
1325 case BINARY_FLOOR_DIVIDE:
1326 case BINARY_TRUE_DIVIDE:
1327 return -1;
1328 case INPLACE_FLOOR_DIVIDE:
1329 case INPLACE_TRUE_DIVIDE:
1330 return -1;
1331
1332 case SLICE+0:
1333 return 1;
1334 case SLICE+1:
1335 return 0;
1336 case SLICE+2:
1337 return 0;
1338 case SLICE+3:
1339 return -1;
1340
1341 case STORE_SLICE+0:
1342 return -2;
1343 case STORE_SLICE+1:
1344 return -3;
1345 case STORE_SLICE+2:
1346 return -3;
1347 case STORE_SLICE+3:
1348 return -4;
1349
1350 case DELETE_SLICE+0:
1351 return -1;
1352 case DELETE_SLICE+1:
1353 return -2;
1354 case DELETE_SLICE+2:
1355 return -2;
1356 case DELETE_SLICE+3:
1357 return -3;
1358
1359 case INPLACE_ADD:
1360 case INPLACE_SUBTRACT:
1361 case INPLACE_MULTIPLY:
1362 case INPLACE_DIVIDE:
1363 case INPLACE_MODULO:
1364 return -1;
1365 case STORE_SUBSCR:
1366 return -3;
1367 case DELETE_SUBSCR:
1368 return -2;
1369
1370 case BINARY_LSHIFT:
1371 case BINARY_RSHIFT:
1372 case BINARY_AND:
1373 case BINARY_XOR:
1374 case BINARY_OR:
1375 return -1;
1376 case INPLACE_POWER:
1377 return -1;
1378 case GET_ITER:
1379 return 0;
1380
1381 case PRINT_EXPR:
1382 return -1;
1383 case PRINT_ITEM:
1384 return -1;
1385 case PRINT_NEWLINE:
1386 return 0;
1387 case PRINT_ITEM_TO:
1388 return -2;
1389 case PRINT_NEWLINE_TO:
1390 return -1;
1391 case INPLACE_LSHIFT:
1392 case INPLACE_RSHIFT:
1393 case INPLACE_AND:
1394 case INPLACE_XOR:
1395 case INPLACE_OR:
1396 return -1;
1397 case BREAK_LOOP:
1398 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001399 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001400 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001401 case LOAD_LOCALS:
1402 return 1;
1403 case RETURN_VALUE:
1404 return -1;
1405 case IMPORT_STAR:
1406 return -1;
1407 case EXEC_STMT:
1408 return -3;
1409 case YIELD_VALUE:
1410 return 0;
1411
1412 case POP_BLOCK:
1413 return 0;
1414 case END_FINALLY:
1415 return -1; /* or -2 or -3 if exception occurred */
1416 case BUILD_CLASS:
1417 return -2;
1418
1419 case STORE_NAME:
1420 return -1;
1421 case DELETE_NAME:
1422 return 0;
1423 case UNPACK_SEQUENCE:
1424 return oparg-1;
1425 case FOR_ITER:
1426 return 1;
1427
1428 case STORE_ATTR:
1429 return -2;
1430 case DELETE_ATTR:
1431 return -1;
1432 case STORE_GLOBAL:
1433 return -1;
1434 case DELETE_GLOBAL:
1435 return 0;
1436 case DUP_TOPX:
1437 return oparg;
1438 case LOAD_CONST:
1439 return 1;
1440 case LOAD_NAME:
1441 return 1;
1442 case BUILD_TUPLE:
1443 case BUILD_LIST:
1444 return 1-oparg;
1445 case BUILD_MAP:
1446 return 1;
1447 case LOAD_ATTR:
1448 return 0;
1449 case COMPARE_OP:
1450 return -1;
1451 case IMPORT_NAME:
1452 return 0;
1453 case IMPORT_FROM:
1454 return 1;
1455
1456 case JUMP_FORWARD:
1457 case JUMP_IF_FALSE:
1458 case JUMP_IF_TRUE:
1459 case JUMP_ABSOLUTE:
1460 return 0;
1461
1462 case LOAD_GLOBAL:
1463 return 1;
1464
1465 case CONTINUE_LOOP:
1466 return 0;
1467 case SETUP_LOOP:
1468 return 0;
1469 case SETUP_EXCEPT:
1470 case SETUP_FINALLY:
1471 return 3; /* actually pushed by an exception */
1472
1473 case LOAD_FAST:
1474 return 1;
1475 case STORE_FAST:
1476 return -1;
1477 case DELETE_FAST:
1478 return 0;
1479
1480 case RAISE_VARARGS:
1481 return -oparg;
1482#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1483 case CALL_FUNCTION:
1484 return -NARGS(oparg);
1485 case CALL_FUNCTION_VAR:
1486 case CALL_FUNCTION_KW:
1487 return -NARGS(oparg)-1;
1488 case CALL_FUNCTION_VAR_KW:
1489 return -NARGS(oparg)-2;
1490#undef NARGS
1491 case MAKE_FUNCTION:
1492 return -oparg;
1493 case BUILD_SLICE:
1494 if (oparg == 3)
1495 return -2;
1496 else
1497 return -1;
1498
1499 case MAKE_CLOSURE:
1500 return -oparg;
1501 case LOAD_CLOSURE:
1502 return 1;
1503 case LOAD_DEREF:
1504 return 1;
1505 case STORE_DEREF:
1506 return -1;
1507 default:
1508 fprintf(stderr, "opcode = %d\n", opcode);
1509 Py_FatalError("opcode_stack_effect()");
1510
1511 }
1512 return 0; /* not reachable */
1513}
1514
1515/* Add an opcode with no argument.
1516 Returns 0 on failure, 1 on success.
1517*/
1518
1519static int
1520compiler_addop(struct compiler *c, int opcode)
1521{
1522 basicblock *b;
1523 struct instr *i;
1524 int off;
1525 off = compiler_next_instr(c, c->u->u_curblock);
1526 if (off < 0)
1527 return 0;
1528 b = c->u->u_curblock;
1529 i = &b->b_instr[off];
1530 i->i_opcode = opcode;
1531 i->i_hasarg = 0;
1532 if (opcode == RETURN_VALUE)
1533 b->b_return = 1;
1534 compiler_set_lineno(c, off);
1535 return 1;
1536}
1537
1538static int
1539compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1540{
1541 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001542 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001543
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001544 /* necessary to make sure types aren't coerced (e.g., int and long) */
1545 t = PyTuple_Pack(2, o, o->ob_type);
1546 if (t == NULL)
1547 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548
1549 v = PyDict_GetItem(dict, t);
1550 if (!v) {
1551 arg = PyDict_Size(dict);
1552 v = PyInt_FromLong(arg);
1553 if (!v) {
1554 Py_DECREF(t);
1555 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001556 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557 if (PyDict_SetItem(dict, t, v) < 0) {
1558 Py_DECREF(t);
1559 Py_DECREF(v);
1560 return -1;
1561 }
1562 Py_DECREF(v);
1563 }
1564 else
1565 arg = PyInt_AsLong(v);
1566 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568}
1569
1570static int
1571compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1572 PyObject *o)
1573{
1574 int arg = compiler_add_o(c, dict, o);
1575 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001576 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 return compiler_addop_i(c, opcode, arg);
1578}
1579
1580static int
1581compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001582 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001583{
1584 int arg;
1585 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1586 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001587 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001588 arg = compiler_add_o(c, dict, mangled);
1589 Py_DECREF(mangled);
1590 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001591 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001592 return compiler_addop_i(c, opcode, arg);
1593}
1594
1595/* Add an opcode with an integer argument.
1596 Returns 0 on failure, 1 on success.
1597*/
1598
1599static int
1600compiler_addop_i(struct compiler *c, int opcode, int oparg)
1601{
1602 struct instr *i;
1603 int off;
1604 off = compiler_next_instr(c, c->u->u_curblock);
1605 if (off < 0)
1606 return 0;
1607 i = &c->u->u_curblock->b_instr[off];
1608 i->i_opcode = opcode;
1609 i->i_oparg = oparg;
1610 i->i_hasarg = 1;
1611 compiler_set_lineno(c, off);
1612 return 1;
1613}
1614
1615static int
1616compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1617{
1618 struct instr *i;
1619 int off;
1620
1621 assert(b != NULL);
1622 off = compiler_next_instr(c, c->u->u_curblock);
1623 if (off < 0)
1624 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001625 i = &c->u->u_curblock->b_instr[off];
1626 i->i_opcode = opcode;
1627 i->i_target = b;
1628 i->i_hasarg = 1;
1629 if (absolute)
1630 i->i_jabs = 1;
1631 else
1632 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001633 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634 return 1;
1635}
1636
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001637/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1638 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639 it as the current block. NEXT_BLOCK() also creates an implicit jump
1640 from the current block to the new block.
1641*/
1642
1643/* XXX The returns inside these macros make it impossible to decref
1644 objects created in the local function.
1645*/
1646
1647
1648#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001649 if (compiler_use_new_block((C)) == NULL) \
1650 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651}
1652
1653#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001654 if (compiler_next_block((C)) == NULL) \
1655 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656}
1657
1658#define ADDOP(C, OP) { \
1659 if (!compiler_addop((C), (OP))) \
1660 return 0; \
1661}
1662
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001663#define ADDOP_IN_SCOPE(C, OP) { \
1664 if (!compiler_addop((C), (OP))) { \
1665 compiler_exit_scope(c); \
1666 return 0; \
1667 } \
1668}
1669
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670#define ADDOP_O(C, OP, O, TYPE) { \
1671 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1672 return 0; \
1673}
1674
1675#define ADDOP_NAME(C, OP, O, TYPE) { \
1676 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1677 return 0; \
1678}
1679
1680#define ADDOP_I(C, OP, O) { \
1681 if (!compiler_addop_i((C), (OP), (O))) \
1682 return 0; \
1683}
1684
1685#define ADDOP_JABS(C, OP, O) { \
1686 if (!compiler_addop_j((C), (OP), (O), 1)) \
1687 return 0; \
1688}
1689
1690#define ADDOP_JREL(C, OP, O) { \
1691 if (!compiler_addop_j((C), (OP), (O), 0)) \
1692 return 0; \
1693}
1694
1695/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1696 the ASDL name to synthesize the name of the C type and the visit function.
1697*/
1698
1699#define VISIT(C, TYPE, V) {\
1700 if (!compiler_visit_ ## TYPE((C), (V))) \
1701 return 0; \
1702}
1703
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001704#define VISIT_IN_SCOPE(C, TYPE, V) {\
1705 if (!compiler_visit_ ## TYPE((C), (V))) { \
1706 compiler_exit_scope(c); \
1707 return 0; \
1708 } \
1709}
1710
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711#define VISIT_SLICE(C, V, CTX) {\
1712 if (!compiler_visit_slice((C), (V), (CTX))) \
1713 return 0; \
1714}
1715
1716#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001717 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001718 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001719 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001720 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001721 if (!compiler_visit_ ## TYPE((C), elt)) \
1722 return 0; \
1723 } \
1724}
1725
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001726#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001727 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001728 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001729 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001730 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001731 if (!compiler_visit_ ## TYPE((C), elt)) { \
1732 compiler_exit_scope(c); \
1733 return 0; \
1734 } \
1735 } \
1736}
1737
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001738static int
1739compiler_isdocstring(stmt_ty s)
1740{
1741 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001742 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743 return s->v.Expr.value->kind == Str_kind;
1744}
1745
1746/* Compile a sequence of statements, checking for a docstring. */
1747
1748static int
1749compiler_body(struct compiler *c, asdl_seq *stmts)
1750{
1751 int i = 0;
1752 stmt_ty st;
1753
1754 if (!asdl_seq_LEN(stmts))
1755 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001756 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757 if (compiler_isdocstring(st)) {
1758 i = 1;
1759 VISIT(c, expr, st->v.Expr.value);
1760 if (!compiler_nameop(c, __doc__, Store))
1761 return 0;
1762 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001763 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001764 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765 return 1;
1766}
1767
1768static PyCodeObject *
1769compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001770{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001771 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001772 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 static PyObject *module;
1774 if (!module) {
1775 module = PyString_FromString("<module>");
1776 if (!module)
1777 return NULL;
1778 }
Neal Norwitzed657552006-07-10 00:04:44 +00001779 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1780 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001781 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 switch (mod->kind) {
1783 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001784 if (!compiler_body(c, mod->v.Module.body)) {
1785 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001787 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 break;
1789 case Interactive_kind:
1790 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001791 VISIT_SEQ_IN_SCOPE(c, stmt,
1792 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793 break;
1794 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001795 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001796 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 break;
1798 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001799 PyErr_SetString(PyExc_SystemError,
1800 "suite should not be possible");
1801 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001802 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001803 PyErr_Format(PyExc_SystemError,
1804 "module kind %d should not be possible",
1805 mod->kind);
1806 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001807 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 co = assemble(c, addNone);
1809 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001810 return co;
1811}
1812
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001813/* The test for LOCAL must come before the test for FREE in order to
1814 handle classes where name is both local and free. The local var is
1815 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001816*/
1817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818static int
1819get_ref_type(struct compiler *c, PyObject *name)
1820{
1821 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001822 if (scope == 0) {
1823 char buf[350];
1824 PyOS_snprintf(buf, sizeof(buf),
1825 "unknown scope for %.100s in %.100s(%s) in %s\n"
1826 "symbols: %s\nlocals: %s\nglobals: %s\n",
1827 PyString_AS_STRING(name),
1828 PyString_AS_STRING(c->u->u_name),
1829 PyObject_REPR(c->u->u_ste->ste_id),
1830 c->c_filename,
1831 PyObject_REPR(c->u->u_ste->ste_symbols),
1832 PyObject_REPR(c->u->u_varnames),
1833 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001835 Py_FatalError(buf);
1836 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001837
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001838 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001839}
1840
1841static int
1842compiler_lookup_arg(PyObject *dict, PyObject *name)
1843{
1844 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001845 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001847 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001849 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001851 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852 return PyInt_AS_LONG(v);
1853}
1854
1855static int
1856compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1857{
1858 int i, free = PyCode_GetNumFree(co);
1859 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001860 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1861 ADDOP_I(c, MAKE_FUNCTION, args);
1862 return 1;
1863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 for (i = 0; i < free; ++i) {
1865 /* Bypass com_addop_varname because it will generate
1866 LOAD_DEREF but LOAD_CLOSURE is needed.
1867 */
1868 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1869 int arg, reftype;
1870
1871 /* Special case: If a class contains a method with a
1872 free variable that has the same name as a method,
1873 the name will be considered free *and* local in the
1874 class. It should be handled by the closure, as
1875 well as by the normal name loookup logic.
1876 */
1877 reftype = get_ref_type(c, name);
1878 if (reftype == CELL)
1879 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1880 else /* (reftype == FREE) */
1881 arg = compiler_lookup_arg(c->u->u_freevars, name);
1882 if (arg == -1) {
1883 printf("lookup %s in %s %d %d\n"
1884 "freevars of %s: %s\n",
1885 PyObject_REPR(name),
1886 PyString_AS_STRING(c->u->u_name),
1887 reftype, arg,
1888 PyString_AS_STRING(co->co_name),
1889 PyObject_REPR(co->co_freevars));
1890 Py_FatalError("compiler_make_closure()");
1891 }
1892 ADDOP_I(c, LOAD_CLOSURE, arg);
1893 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001894 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001896 ADDOP_I(c, MAKE_CLOSURE, args);
1897 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898}
1899
1900static int
1901compiler_decorators(struct compiler *c, asdl_seq* decos)
1902{
1903 int i;
1904
1905 if (!decos)
1906 return 1;
1907
1908 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001909 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910 }
1911 return 1;
1912}
1913
1914static int
1915compiler_arguments(struct compiler *c, arguments_ty args)
1916{
1917 int i;
1918 int n = asdl_seq_LEN(args->args);
1919 /* Correctly handle nested argument lists */
1920 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001921 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922 if (arg->kind == Tuple_kind) {
1923 PyObject *id = PyString_FromFormat(".%d", i);
1924 if (id == NULL) {
1925 return 0;
1926 }
1927 if (!compiler_nameop(c, id, Load)) {
1928 Py_DECREF(id);
1929 return 0;
1930 }
1931 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001932 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933 }
1934 }
1935 return 1;
1936}
1937
1938static int
1939compiler_function(struct compiler *c, stmt_ty s)
1940{
1941 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001942 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943 arguments_ty args = s->v.FunctionDef.args;
1944 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001945 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946 int i, n, docstring;
1947
1948 assert(s->kind == FunctionDef_kind);
1949
1950 if (!compiler_decorators(c, decos))
1951 return 0;
1952 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001953 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1955 s->lineno))
1956 return 0;
1957
Anthony Baxter7b782b62006-04-11 12:01:56 +00001958 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001959 docstring = compiler_isdocstring(st);
1960 if (docstring)
1961 first_const = st->v.Expr.value->v.Str.s;
1962 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001963 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001964 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001967 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968 compiler_arguments(c, args);
1969
1970 c->u->u_argcount = asdl_seq_LEN(args->args);
1971 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001972 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 for (i = docstring; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001974 stmt_ty s2 = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975 if (i == 0 && s2->kind == Expr_kind &&
1976 s2->v.Expr.value->kind == Str_kind)
1977 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001978 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979 }
1980 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001981 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 if (co == NULL)
1983 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001985 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001986 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987
1988 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1989 ADDOP_I(c, CALL_FUNCTION, 1);
1990 }
1991
1992 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1993}
1994
1995static int
1996compiler_class(struct compiler *c, stmt_ty s)
1997{
1998 int n;
1999 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002000 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 /* push class name on stack, needed by BUILD_CLASS */
2002 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2003 /* push the tuple of base classes on the stack */
2004 n = asdl_seq_LEN(s->v.ClassDef.bases);
2005 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002006 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 ADDOP_I(c, BUILD_TUPLE, n);
2008 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2009 s->lineno))
2010 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002011 c->u->u_private = s->v.ClassDef.name;
2012 Py_INCREF(c->u->u_private);
2013 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 if (!str || !compiler_nameop(c, str, Load)) {
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
2020 Py_DECREF(str);
2021 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022 if (!str || !compiler_nameop(c, str, Store)) {
2023 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002024 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002026 }
2027 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002029 if (!compiler_body(c, s->v.ClassDef.body)) {
2030 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002032 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002034 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2035 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002036 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002037 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 if (co == NULL)
2039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002041 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002042 Py_DECREF(co);
2043
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044 ADDOP_I(c, CALL_FUNCTION, 0);
2045 ADDOP(c, BUILD_CLASS);
2046 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2047 return 0;
2048 return 1;
2049}
2050
2051static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002052compiler_ifexp(struct compiler *c, expr_ty e)
2053{
2054 basicblock *end, *next;
2055
2056 assert(e->kind == IfExp_kind);
2057 end = compiler_new_block(c);
2058 if (end == NULL)
2059 return 0;
2060 next = compiler_new_block(c);
2061 if (next == NULL)
2062 return 0;
2063 VISIT(c, expr, e->v.IfExp.test);
2064 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2065 ADDOP(c, POP_TOP);
2066 VISIT(c, expr, e->v.IfExp.body);
2067 ADDOP_JREL(c, JUMP_FORWARD, end);
2068 compiler_use_next_block(c, next);
2069 ADDOP(c, POP_TOP);
2070 VISIT(c, expr, e->v.IfExp.orelse);
2071 compiler_use_next_block(c, end);
2072 return 1;
2073}
2074
2075static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076compiler_lambda(struct compiler *c, expr_ty e)
2077{
2078 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002079 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 arguments_ty args = e->v.Lambda.args;
2081 assert(e->kind == Lambda_kind);
2082
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002083 if (!name) {
2084 name = PyString_InternFromString("<lambda>");
2085 if (!name)
2086 return 0;
2087 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088
2089 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002090 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2092 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002093
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002094 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002095 compiler_arguments(c, args);
2096
2097 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002098 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2099 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002101 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102 if (co == NULL)
2103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002105 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002106 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107
2108 return 1;
2109}
2110
2111static int
2112compiler_print(struct compiler *c, stmt_ty s)
2113{
2114 int i, n;
2115 bool dest;
2116
2117 assert(s->kind == Print_kind);
2118 n = asdl_seq_LEN(s->v.Print.values);
2119 dest = false;
2120 if (s->v.Print.dest) {
2121 VISIT(c, expr, s->v.Print.dest);
2122 dest = true;
2123 }
2124 for (i = 0; i < n; i++) {
2125 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2126 if (dest) {
2127 ADDOP(c, DUP_TOP);
2128 VISIT(c, expr, e);
2129 ADDOP(c, ROT_TWO);
2130 ADDOP(c, PRINT_ITEM_TO);
2131 }
2132 else {
2133 VISIT(c, expr, e);
2134 ADDOP(c, PRINT_ITEM);
2135 }
2136 }
2137 if (s->v.Print.nl) {
2138 if (dest)
2139 ADDOP(c, PRINT_NEWLINE_TO)
2140 else
2141 ADDOP(c, PRINT_NEWLINE)
2142 }
2143 else if (dest)
2144 ADDOP(c, POP_TOP);
2145 return 1;
2146}
2147
2148static int
2149compiler_if(struct compiler *c, stmt_ty s)
2150{
2151 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00002152 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153 assert(s->kind == If_kind);
2154 end = compiler_new_block(c);
2155 if (end == NULL)
2156 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002157 next = compiler_new_block(c);
2158 if (next == NULL)
2159 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00002160
2161 constant = expr_constant(s->v.If.test);
2162 /* constant = 0: "if 0"
2163 * constant = 1: "if 1", "if 2", ...
2164 * constant = -1: rest */
2165 if (constant == 0) {
2166 if (s->v.If.orelse)
2167 VISIT_SEQ(c, stmt, s->v.If.orelse);
2168 } else if (constant == 1) {
2169 VISIT_SEQ(c, stmt, s->v.If.body);
2170 } else {
2171 VISIT(c, expr, s->v.If.test);
2172 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2173 ADDOP(c, POP_TOP);
2174 VISIT_SEQ(c, stmt, s->v.If.body);
2175 ADDOP_JREL(c, JUMP_FORWARD, end);
2176 compiler_use_next_block(c, next);
2177 ADDOP(c, POP_TOP);
2178 if (s->v.If.orelse)
2179 VISIT_SEQ(c, stmt, s->v.If.orelse);
2180 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002181 compiler_use_next_block(c, end);
2182 return 1;
2183}
2184
2185static int
2186compiler_for(struct compiler *c, stmt_ty s)
2187{
2188 basicblock *start, *cleanup, *end;
2189
2190 start = compiler_new_block(c);
2191 cleanup = compiler_new_block(c);
2192 end = compiler_new_block(c);
2193 if (start == NULL || end == NULL || cleanup == NULL)
2194 return 0;
2195 ADDOP_JREL(c, SETUP_LOOP, end);
2196 if (!compiler_push_fblock(c, LOOP, start))
2197 return 0;
2198 VISIT(c, expr, s->v.For.iter);
2199 ADDOP(c, GET_ITER);
2200 compiler_use_next_block(c, start);
2201 ADDOP_JREL(c, FOR_ITER, cleanup);
2202 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002203 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002204 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2205 compiler_use_next_block(c, cleanup);
2206 ADDOP(c, POP_BLOCK);
2207 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002208 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209 compiler_use_next_block(c, end);
2210 return 1;
2211}
2212
2213static int
2214compiler_while(struct compiler *c, stmt_ty s)
2215{
2216 basicblock *loop, *orelse, *end, *anchor = NULL;
2217 int constant = expr_constant(s->v.While.test);
2218
2219 if (constant == 0)
2220 return 1;
2221 loop = compiler_new_block(c);
2222 end = compiler_new_block(c);
2223 if (constant == -1) {
2224 anchor = compiler_new_block(c);
2225 if (anchor == NULL)
2226 return 0;
2227 }
2228 if (loop == NULL || end == NULL)
2229 return 0;
2230 if (s->v.While.orelse) {
2231 orelse = compiler_new_block(c);
2232 if (orelse == NULL)
2233 return 0;
2234 }
2235 else
2236 orelse = NULL;
2237
2238 ADDOP_JREL(c, SETUP_LOOP, end);
2239 compiler_use_next_block(c, loop);
2240 if (!compiler_push_fblock(c, LOOP, loop))
2241 return 0;
2242 if (constant == -1) {
2243 VISIT(c, expr, s->v.While.test);
2244 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2245 ADDOP(c, POP_TOP);
2246 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002247 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2249
2250 /* XXX should the two POP instructions be in a separate block
2251 if there is no else clause ?
2252 */
2253
2254 if (constant == -1) {
2255 compiler_use_next_block(c, anchor);
2256 ADDOP(c, POP_TOP);
2257 ADDOP(c, POP_BLOCK);
2258 }
2259 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002260 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002261 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262 compiler_use_next_block(c, end);
2263
2264 return 1;
2265}
2266
2267static int
2268compiler_continue(struct compiler *c)
2269{
2270 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2271 int i;
2272
2273 if (!c->u->u_nfblocks)
2274 return compiler_error(c, LOOP_ERROR_MSG);
2275 i = c->u->u_nfblocks - 1;
2276 switch (c->u->u_fblock[i].fb_type) {
2277 case LOOP:
2278 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2279 break;
2280 case EXCEPT:
2281 case FINALLY_TRY:
2282 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2283 ;
2284 if (i == -1)
2285 return compiler_error(c, LOOP_ERROR_MSG);
2286 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2287 break;
2288 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002289 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290 "'continue' not supported inside 'finally' clause");
2291 }
2292
2293 return 1;
2294}
2295
2296/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2297
2298 SETUP_FINALLY L
2299 <code for body>
2300 POP_BLOCK
2301 LOAD_CONST <None>
2302 L: <code for finalbody>
2303 END_FINALLY
2304
2305 The special instructions use the block stack. Each block
2306 stack entry contains the instruction that created it (here
2307 SETUP_FINALLY), the level of the value stack at the time the
2308 block stack entry was created, and a label (here L).
2309
2310 SETUP_FINALLY:
2311 Pushes the current value stack level and the label
2312 onto the block stack.
2313 POP_BLOCK:
2314 Pops en entry from the block stack, and pops the value
2315 stack until its level is the same as indicated on the
2316 block stack. (The label is ignored.)
2317 END_FINALLY:
2318 Pops a variable number of entries from the *value* stack
2319 and re-raises the exception they specify. The number of
2320 entries popped depends on the (pseudo) exception type.
2321
2322 The block stack is unwound when an exception is raised:
2323 when a SETUP_FINALLY entry is found, the exception is pushed
2324 onto the value stack (and the exception condition is cleared),
2325 and the interpreter jumps to the label gotten from the block
2326 stack.
2327*/
2328
2329static int
2330compiler_try_finally(struct compiler *c, stmt_ty s)
2331{
2332 basicblock *body, *end;
2333 body = compiler_new_block(c);
2334 end = compiler_new_block(c);
2335 if (body == NULL || end == NULL)
2336 return 0;
2337
2338 ADDOP_JREL(c, SETUP_FINALLY, end);
2339 compiler_use_next_block(c, body);
2340 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2341 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002342 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343 ADDOP(c, POP_BLOCK);
2344 compiler_pop_fblock(c, FINALLY_TRY, body);
2345
2346 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2347 compiler_use_next_block(c, end);
2348 if (!compiler_push_fblock(c, FINALLY_END, end))
2349 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002350 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351 ADDOP(c, END_FINALLY);
2352 compiler_pop_fblock(c, FINALLY_END, end);
2353
2354 return 1;
2355}
2356
2357/*
2358 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2359 (The contents of the value stack is shown in [], with the top
2360 at the right; 'tb' is trace-back info, 'val' the exception's
2361 associated value, and 'exc' the exception.)
2362
2363 Value stack Label Instruction Argument
2364 [] SETUP_EXCEPT L1
2365 [] <code for S>
2366 [] POP_BLOCK
2367 [] JUMP_FORWARD L0
2368
2369 [tb, val, exc] L1: DUP )
2370 [tb, val, exc, exc] <evaluate E1> )
2371 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2372 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2373 [tb, val, exc, 1] POP )
2374 [tb, val, exc] POP
2375 [tb, val] <assign to V1> (or POP if no V1)
2376 [tb] POP
2377 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002378 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379
2380 [tb, val, exc, 0] L2: POP
2381 [tb, val, exc] DUP
2382 .............................etc.......................
2383
2384 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002385 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386
2387 [] L0: <next statement>
2388
2389 Of course, parts are not generated if Vi or Ei is not present.
2390*/
2391static int
2392compiler_try_except(struct compiler *c, stmt_ty s)
2393{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002394 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395 int i, n;
2396
2397 body = compiler_new_block(c);
2398 except = compiler_new_block(c);
2399 orelse = compiler_new_block(c);
2400 end = compiler_new_block(c);
2401 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2402 return 0;
2403 ADDOP_JREL(c, SETUP_EXCEPT, except);
2404 compiler_use_next_block(c, body);
2405 if (!compiler_push_fblock(c, EXCEPT, body))
2406 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002407 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408 ADDOP(c, POP_BLOCK);
2409 compiler_pop_fblock(c, EXCEPT, body);
2410 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2411 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2412 compiler_use_next_block(c, except);
2413 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002414 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415 s->v.TryExcept.handlers, i);
2416 if (!handler->type && i < n-1)
2417 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00002418 c->u->u_lineno_set = false;
2419 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420 except = compiler_new_block(c);
2421 if (except == NULL)
2422 return 0;
2423 if (handler->type) {
2424 ADDOP(c, DUP_TOP);
2425 VISIT(c, expr, handler->type);
2426 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2427 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2428 ADDOP(c, POP_TOP);
2429 }
2430 ADDOP(c, POP_TOP);
2431 if (handler->name) {
2432 VISIT(c, expr, handler->name);
2433 }
2434 else {
2435 ADDOP(c, POP_TOP);
2436 }
2437 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002438 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 ADDOP_JREL(c, JUMP_FORWARD, end);
2440 compiler_use_next_block(c, except);
2441 if (handler->type)
2442 ADDOP(c, POP_TOP);
2443 }
2444 ADDOP(c, END_FINALLY);
2445 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002446 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002447 compiler_use_next_block(c, end);
2448 return 1;
2449}
2450
2451static int
2452compiler_import_as(struct compiler *c, identifier name, identifier asname)
2453{
2454 /* The IMPORT_NAME opcode was already generated. This function
2455 merely needs to bind the result to a name.
2456
2457 If there is a dot in name, we need to split it and emit a
2458 LOAD_ATTR for each name.
2459 */
2460 const char *src = PyString_AS_STRING(name);
2461 const char *dot = strchr(src, '.');
2462 if (dot) {
2463 /* Consume the base module name to get the first attribute */
2464 src = dot + 1;
2465 while (dot) {
2466 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002467 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002469 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002470 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002471 if (!attr)
2472 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002474 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 src = dot + 1;
2476 }
2477 }
2478 return compiler_nameop(c, asname, Store);
2479}
2480
2481static int
2482compiler_import(struct compiler *c, stmt_ty s)
2483{
2484 /* The Import node stores a module name like a.b.c as a single
2485 string. This is convenient for all cases except
2486 import a.b.c as d
2487 where we need to parse that string to extract the individual
2488 module names.
2489 XXX Perhaps change the representation to make this case simpler?
2490 */
2491 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002492
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002494 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002496 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497
Neal Norwitzcbce2802006-04-03 06:26:32 +00002498 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002499 level = PyInt_FromLong(0);
2500 else
2501 level = PyInt_FromLong(-1);
2502
2503 if (level == NULL)
2504 return 0;
2505
2506 ADDOP_O(c, LOAD_CONST, level, consts);
2507 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2509 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2510
2511 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002512 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002513 if (!r)
2514 return r;
2515 }
2516 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517 identifier tmp = alias->name;
2518 const char *base = PyString_AS_STRING(alias->name);
2519 char *dot = strchr(base, '.');
2520 if (dot)
2521 tmp = PyString_FromStringAndSize(base,
2522 dot - base);
2523 r = compiler_nameop(c, tmp, Store);
2524 if (dot) {
2525 Py_DECREF(tmp);
2526 }
2527 if (!r)
2528 return r;
2529 }
2530 }
2531 return 1;
2532}
2533
2534static int
2535compiler_from_import(struct compiler *c, stmt_ty s)
2536{
2537 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538
2539 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002540 PyObject *level;
2541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 if (!names)
2543 return 0;
2544
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002545 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002546 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002547 level = PyInt_FromLong(-1);
2548 else
2549 level = PyInt_FromLong(s->v.ImportFrom.level);
2550
2551 if (!level) {
2552 Py_DECREF(names);
2553 return 0;
2554 }
2555
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556 /* build up the names */
2557 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002558 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 Py_INCREF(alias->name);
2560 PyTuple_SET_ITEM(names, i, alias->name);
2561 }
2562
2563 if (s->lineno > c->c_future->ff_lineno) {
2564 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2565 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002566 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 Py_DECREF(names);
2568 return compiler_error(c,
2569 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002570 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571
2572 }
2573 }
2574
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002575 ADDOP_O(c, LOAD_CONST, level, consts);
2576 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002578 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002579 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2580 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002581 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 identifier store_name;
2583
2584 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2585 assert(n == 1);
2586 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002587 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 }
2589
2590 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2591 store_name = alias->name;
2592 if (alias->asname)
2593 store_name = alias->asname;
2594
2595 if (!compiler_nameop(c, store_name, Store)) {
2596 Py_DECREF(names);
2597 return 0;
2598 }
2599 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002600 /* remove imported module */
2601 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 return 1;
2603}
2604
2605static int
2606compiler_assert(struct compiler *c, stmt_ty s)
2607{
2608 static PyObject *assertion_error = NULL;
2609 basicblock *end;
2610
2611 if (Py_OptimizeFlag)
2612 return 1;
2613 if (assertion_error == NULL) {
2614 assertion_error = PyString_FromString("AssertionError");
2615 if (assertion_error == NULL)
2616 return 0;
2617 }
2618 VISIT(c, expr, s->v.Assert.test);
2619 end = compiler_new_block(c);
2620 if (end == NULL)
2621 return 0;
2622 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2623 ADDOP(c, POP_TOP);
2624 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2625 if (s->v.Assert.msg) {
2626 VISIT(c, expr, s->v.Assert.msg);
2627 ADDOP_I(c, RAISE_VARARGS, 2);
2628 }
2629 else {
2630 ADDOP_I(c, RAISE_VARARGS, 1);
2631 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002632 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 ADDOP(c, POP_TOP);
2634 return 1;
2635}
2636
2637static int
2638compiler_visit_stmt(struct compiler *c, stmt_ty s)
2639{
2640 int i, n;
2641
Jeremy Hylton12603c42006-04-01 16:18:02 +00002642 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 c->u->u_lineno = s->lineno;
2644 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002645
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 if (c->u->u_ste->ste_type != FunctionBlock)
2653 return compiler_error(c, "'return' outside function");
2654 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 VISIT(c, expr, s->v.Return.value);
2656 }
2657 else
2658 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2659 ADDOP(c, RETURN_VALUE);
2660 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002662 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002664 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665 n = asdl_seq_LEN(s->v.Assign.targets);
2666 VISIT(c, expr, s->v.Assign.value);
2667 for (i = 0; i < n; i++) {
2668 if (i < n - 1)
2669 ADDOP(c, DUP_TOP);
2670 VISIT(c, expr,
2671 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2672 }
2673 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002676 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002682 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002684 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685 n = 0;
2686 if (s->v.Raise.type) {
2687 VISIT(c, expr, s->v.Raise.type);
2688 n++;
2689 if (s->v.Raise.inst) {
2690 VISIT(c, expr, s->v.Raise.inst);
2691 n++;
2692 if (s->v.Raise.tback) {
2693 VISIT(c, expr, s->v.Raise.tback);
2694 n++;
2695 }
2696 }
2697 }
2698 ADDOP_I(c, RAISE_VARARGS, n);
2699 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 VISIT(c, expr, s->v.Exec.body);
2712 if (s->v.Exec.globals) {
2713 VISIT(c, expr, s->v.Exec.globals);
2714 if (s->v.Exec.locals) {
2715 VISIT(c, expr, s->v.Exec.locals);
2716 } else {
2717 ADDOP(c, DUP_TOP);
2718 }
2719 } else {
2720 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2721 ADDOP(c, DUP_TOP);
2722 }
2723 ADDOP(c, EXEC_STMT);
2724 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002725 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002726 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002727 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728 VISIT(c, expr, s->v.Expr.value);
2729 if (c->c_interactive && c->c_nestlevel <= 1) {
2730 ADDOP(c, PRINT_EXPR);
2731 }
2732 else {
2733 ADDOP(c, POP_TOP);
2734 }
2735 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002736 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002738 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 if (!c->u->u_nfblocks)
2740 return compiler_error(c, "'break' outside loop");
2741 ADDOP(c, BREAK_LOOP);
2742 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002743 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002745 case With_kind:
2746 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002747 }
2748 return 1;
2749}
2750
2751static int
2752unaryop(unaryop_ty op)
2753{
2754 switch (op) {
2755 case Invert:
2756 return UNARY_INVERT;
2757 case Not:
2758 return UNARY_NOT;
2759 case UAdd:
2760 return UNARY_POSITIVE;
2761 case USub:
2762 return UNARY_NEGATIVE;
2763 }
2764 return 0;
2765}
2766
2767static int
2768binop(struct compiler *c, operator_ty op)
2769{
2770 switch (op) {
2771 case Add:
2772 return BINARY_ADD;
2773 case Sub:
2774 return BINARY_SUBTRACT;
2775 case Mult:
2776 return BINARY_MULTIPLY;
2777 case Div:
2778 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2779 return BINARY_TRUE_DIVIDE;
2780 else
2781 return BINARY_DIVIDE;
2782 case Mod:
2783 return BINARY_MODULO;
2784 case Pow:
2785 return BINARY_POWER;
2786 case LShift:
2787 return BINARY_LSHIFT;
2788 case RShift:
2789 return BINARY_RSHIFT;
2790 case BitOr:
2791 return BINARY_OR;
2792 case BitXor:
2793 return BINARY_XOR;
2794 case BitAnd:
2795 return BINARY_AND;
2796 case FloorDiv:
2797 return BINARY_FLOOR_DIVIDE;
2798 }
2799 return 0;
2800}
2801
2802static int
2803cmpop(cmpop_ty op)
2804{
2805 switch (op) {
2806 case Eq:
2807 return PyCmp_EQ;
2808 case NotEq:
2809 return PyCmp_NE;
2810 case Lt:
2811 return PyCmp_LT;
2812 case LtE:
2813 return PyCmp_LE;
2814 case Gt:
2815 return PyCmp_GT;
2816 case GtE:
2817 return PyCmp_GE;
2818 case Is:
2819 return PyCmp_IS;
2820 case IsNot:
2821 return PyCmp_IS_NOT;
2822 case In:
2823 return PyCmp_IN;
2824 case NotIn:
2825 return PyCmp_NOT_IN;
2826 }
2827 return PyCmp_BAD;
2828}
2829
2830static int
2831inplace_binop(struct compiler *c, operator_ty op)
2832{
2833 switch (op) {
2834 case Add:
2835 return INPLACE_ADD;
2836 case Sub:
2837 return INPLACE_SUBTRACT;
2838 case Mult:
2839 return INPLACE_MULTIPLY;
2840 case Div:
2841 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2842 return INPLACE_TRUE_DIVIDE;
2843 else
2844 return INPLACE_DIVIDE;
2845 case Mod:
2846 return INPLACE_MODULO;
2847 case Pow:
2848 return INPLACE_POWER;
2849 case LShift:
2850 return INPLACE_LSHIFT;
2851 case RShift:
2852 return INPLACE_RSHIFT;
2853 case BitOr:
2854 return INPLACE_OR;
2855 case BitXor:
2856 return INPLACE_XOR;
2857 case BitAnd:
2858 return INPLACE_AND;
2859 case FloorDiv:
2860 return INPLACE_FLOOR_DIVIDE;
2861 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002862 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002863 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 return 0;
2865}
2866
2867static int
2868compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2869{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002870 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2872
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002874 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875 /* XXX AugStore isn't used anywhere! */
2876
2877 /* First check for assignment to __debug__. Param? */
2878 if ((ctx == Store || ctx == AugStore || ctx == Del)
2879 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2880 return compiler_error(c, "can not assign to __debug__");
2881 }
2882
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002883 mangled = _Py_Mangle(c->u->u_private, name);
2884 if (!mangled)
2885 return 0;
2886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887 op = 0;
2888 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002889 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 switch (scope) {
2891 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002892 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 optype = OP_DEREF;
2894 break;
2895 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 optype = OP_DEREF;
2898 break;
2899 case LOCAL:
2900 if (c->u->u_ste->ste_type == FunctionBlock)
2901 optype = OP_FAST;
2902 break;
2903 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002904 if (c->u->u_ste->ste_type == FunctionBlock &&
2905 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 optype = OP_GLOBAL;
2907 break;
2908 case GLOBAL_EXPLICIT:
2909 optype = OP_GLOBAL;
2910 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002911 default:
2912 /* scope can be 0 */
2913 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 }
2915
2916 /* XXX Leave assert here, but handle __doc__ and the like better */
2917 assert(scope || PyString_AS_STRING(name)[0] == '_');
2918
2919 switch (optype) {
2920 case OP_DEREF:
2921 switch (ctx) {
2922 case Load: op = LOAD_DEREF; break;
2923 case Store: op = STORE_DEREF; break;
2924 case AugLoad:
2925 case AugStore:
2926 break;
2927 case Del:
2928 PyErr_Format(PyExc_SyntaxError,
2929 "can not delete variable '%s' referenced "
2930 "in nested scope",
2931 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002932 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002935 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for deref variable");
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 }
2940 break;
2941 case OP_FAST:
2942 switch (ctx) {
2943 case Load: op = LOAD_FAST; break;
2944 case Store: op = STORE_FAST; break;
2945 case Del: op = DELETE_FAST; break;
2946 case AugLoad:
2947 case AugStore:
2948 break;
2949 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002950 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002951 PyErr_SetString(PyExc_SystemError,
2952 "param invalid for local variable");
2953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002955 ADDOP_O(c, op, mangled, varnames);
2956 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957 return 1;
2958 case OP_GLOBAL:
2959 switch (ctx) {
2960 case Load: op = LOAD_GLOBAL; break;
2961 case Store: op = STORE_GLOBAL; break;
2962 case Del: op = DELETE_GLOBAL; break;
2963 case AugLoad:
2964 case AugStore:
2965 break;
2966 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002967 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002968 PyErr_SetString(PyExc_SystemError,
2969 "param invalid for global variable");
2970 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 }
2972 break;
2973 case OP_NAME:
2974 switch (ctx) {
2975 case Load: op = LOAD_NAME; break;
2976 case Store: op = STORE_NAME; break;
2977 case Del: op = DELETE_NAME; break;
2978 case AugLoad:
2979 case AugStore:
2980 break;
2981 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002982 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002983 PyErr_SetString(PyExc_SystemError,
2984 "param invalid for name variable");
2985 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 }
2987 break;
2988 }
2989
2990 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002991 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002992 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002993 if (arg < 0)
2994 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002995 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996}
2997
2998static int
2999compiler_boolop(struct compiler *c, expr_ty e)
3000{
3001 basicblock *end;
3002 int jumpi, i, n;
3003 asdl_seq *s;
3004
3005 assert(e->kind == BoolOp_kind);
3006 if (e->v.BoolOp.op == And)
3007 jumpi = JUMP_IF_FALSE;
3008 else
3009 jumpi = JUMP_IF_TRUE;
3010 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003011 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 return 0;
3013 s = e->v.BoolOp.values;
3014 n = asdl_seq_LEN(s) - 1;
3015 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003016 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 ADDOP_JREL(c, jumpi, end);
3018 ADDOP(c, POP_TOP)
3019 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003020 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 compiler_use_next_block(c, end);
3022 return 1;
3023}
3024
3025static int
3026compiler_list(struct compiler *c, expr_ty e)
3027{
3028 int n = asdl_seq_LEN(e->v.List.elts);
3029 if (e->v.List.ctx == Store) {
3030 ADDOP_I(c, UNPACK_SEQUENCE, n);
3031 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003032 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003033 if (e->v.List.ctx == Load) {
3034 ADDOP_I(c, BUILD_LIST, n);
3035 }
3036 return 1;
3037}
3038
3039static int
3040compiler_tuple(struct compiler *c, expr_ty e)
3041{
3042 int n = asdl_seq_LEN(e->v.Tuple.elts);
3043 if (e->v.Tuple.ctx == Store) {
3044 ADDOP_I(c, UNPACK_SEQUENCE, n);
3045 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003046 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 if (e->v.Tuple.ctx == Load) {
3048 ADDOP_I(c, BUILD_TUPLE, n);
3049 }
3050 return 1;
3051}
3052
3053static int
3054compiler_compare(struct compiler *c, expr_ty e)
3055{
3056 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003057 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003058
3059 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3060 VISIT(c, expr, e->v.Compare.left);
3061 n = asdl_seq_LEN(e->v.Compare.ops);
3062 assert(n > 0);
3063 if (n > 1) {
3064 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003065 if (cleanup == NULL)
3066 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003067 VISIT(c, expr,
3068 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069 }
3070 for (i = 1; i < n; i++) {
3071 ADDOP(c, DUP_TOP);
3072 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003073 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003074 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003075 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3077 NEXT_BLOCK(c);
3078 ADDOP(c, POP_TOP);
3079 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003080 VISIT(c, expr,
3081 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003083 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003084 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003085 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003086 if (n > 1) {
3087 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003088 if (end == NULL)
3089 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003090 ADDOP_JREL(c, JUMP_FORWARD, end);
3091 compiler_use_next_block(c, cleanup);
3092 ADDOP(c, ROT_TWO);
3093 ADDOP(c, POP_TOP);
3094 compiler_use_next_block(c, end);
3095 }
3096 return 1;
3097}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003098#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003099
3100static int
3101compiler_call(struct compiler *c, expr_ty e)
3102{
3103 int n, code = 0;
3104
3105 VISIT(c, expr, e->v.Call.func);
3106 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003107 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003109 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3111 }
3112 if (e->v.Call.starargs) {
3113 VISIT(c, expr, e->v.Call.starargs);
3114 code |= 1;
3115 }
3116 if (e->v.Call.kwargs) {
3117 VISIT(c, expr, e->v.Call.kwargs);
3118 code |= 2;
3119 }
3120 switch (code) {
3121 case 0:
3122 ADDOP_I(c, CALL_FUNCTION, n);
3123 break;
3124 case 1:
3125 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3126 break;
3127 case 2:
3128 ADDOP_I(c, CALL_FUNCTION_KW, n);
3129 break;
3130 case 3:
3131 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3132 break;
3133 }
3134 return 1;
3135}
3136
3137static int
3138compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 asdl_seq *generators, int gen_index,
3140 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141{
3142 /* generate code for the iterator, then each of the ifs,
3143 and then write to the element */
3144
3145 comprehension_ty l;
3146 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148
3149 start = compiler_new_block(c);
3150 skip = compiler_new_block(c);
3151 if_cleanup = compiler_new_block(c);
3152 anchor = compiler_new_block(c);
3153
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003154 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3155 anchor == NULL)
3156 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157
Anthony Baxter7b782b62006-04-11 12:01:56 +00003158 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 VISIT(c, expr, l->iter);
3160 ADDOP(c, GET_ITER);
3161 compiler_use_next_block(c, start);
3162 ADDOP_JREL(c, FOR_ITER, anchor);
3163 NEXT_BLOCK(c);
3164 VISIT(c, expr, l->target);
3165
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003166 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167 n = asdl_seq_LEN(l->ifs);
3168 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003169 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 VISIT(c, expr, e);
3171 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3172 NEXT_BLOCK(c);
3173 ADDOP(c, POP_TOP);
3174 }
3175
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 if (++gen_index < asdl_seq_LEN(generators))
3177 if (!compiler_listcomp_generator(c, tmpname,
3178 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 /* only append after the last for generator */
3182 if (gen_index >= asdl_seq_LEN(generators)) {
3183 if (!compiler_nameop(c, tmpname, Load))
3184 return 0;
3185 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003186 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003187
3188 compiler_use_next_block(c, skip);
3189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 for (i = 0; i < n; i++) {
3191 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003192 if (i == 0)
3193 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 ADDOP(c, POP_TOP);
3195 }
3196 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3197 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003200 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003201 return 0;
3202
3203 return 1;
3204}
3205
3206static int
3207compiler_listcomp(struct compiler *c, expr_ty e)
3208{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211 static identifier append;
3212 asdl_seq *generators = e->v.ListComp.generators;
3213
3214 assert(e->kind == ListComp_kind);
3215 if (!append) {
3216 append = PyString_InternFromString("append");
3217 if (!append)
3218 return 0;
3219 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003220 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003221 if (!tmp)
3222 return 0;
3223 ADDOP_I(c, BUILD_LIST, 0);
3224 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003225 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003226 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3227 e->v.ListComp.elt);
3228 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 return rc;
3230}
3231
3232static int
3233compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003234 asdl_seq *generators, int gen_index,
3235 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236{
3237 /* generate code for the iterator, then each of the ifs,
3238 and then write to the element */
3239
3240 comprehension_ty ge;
3241 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003242 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003243
3244 start = compiler_new_block(c);
3245 skip = compiler_new_block(c);
3246 if_cleanup = compiler_new_block(c);
3247 anchor = compiler_new_block(c);
3248 end = compiler_new_block(c);
3249
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003250 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 anchor == NULL || end == NULL)
3252 return 0;
3253
Anthony Baxter7b782b62006-04-11 12:01:56 +00003254 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003255 ADDOP_JREL(c, SETUP_LOOP, end);
3256 if (!compiler_push_fblock(c, LOOP, start))
3257 return 0;
3258
3259 if (gen_index == 0) {
3260 /* Receive outermost iter as an implicit argument */
3261 c->u->u_argcount = 1;
3262 ADDOP_I(c, LOAD_FAST, 0);
3263 }
3264 else {
3265 /* Sub-iter - calculate on the fly */
3266 VISIT(c, expr, ge->iter);
3267 ADDOP(c, GET_ITER);
3268 }
3269 compiler_use_next_block(c, start);
3270 ADDOP_JREL(c, FOR_ITER, anchor);
3271 NEXT_BLOCK(c);
3272 VISIT(c, expr, ge->target);
3273
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003274 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275 n = asdl_seq_LEN(ge->ifs);
3276 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003277 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278 VISIT(c, expr, e);
3279 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3280 NEXT_BLOCK(c);
3281 ADDOP(c, POP_TOP);
3282 }
3283
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003284 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3286 return 0;
3287
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003288 /* only append after the last 'for' generator */
3289 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290 VISIT(c, expr, elt);
3291 ADDOP(c, YIELD_VALUE);
3292 ADDOP(c, POP_TOP);
3293
3294 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296 for (i = 0; i < n; i++) {
3297 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003298 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 compiler_use_next_block(c, if_cleanup);
3300
3301 ADDOP(c, POP_TOP);
3302 }
3303 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3304 compiler_use_next_block(c, anchor);
3305 ADDOP(c, POP_BLOCK);
3306 compiler_pop_fblock(c, LOOP, start);
3307 compiler_use_next_block(c, end);
3308
3309 return 1;
3310}
3311
3312static int
3313compiler_genexp(struct compiler *c, expr_ty e)
3314{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003315 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003316 PyCodeObject *co;
3317 expr_ty outermost_iter = ((comprehension_ty)
3318 (asdl_seq_GET(e->v.GeneratorExp.generators,
3319 0)))->iter;
3320
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003321 if (!name) {
3322 name = PyString_FromString("<genexpr>");
3323 if (!name)
3324 return 0;
3325 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326
3327 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3328 return 0;
3329 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3330 e->v.GeneratorExp.elt);
3331 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003332 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333 if (co == NULL)
3334 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003336 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003337 Py_DECREF(co);
3338
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339 VISIT(c, expr, outermost_iter);
3340 ADDOP(c, GET_ITER);
3341 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342
3343 return 1;
3344}
3345
3346static int
3347compiler_visit_keyword(struct compiler *c, keyword_ty k)
3348{
3349 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3350 VISIT(c, expr, k->value);
3351 return 1;
3352}
3353
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 whether they are true or false.
3356
3357 Return values: 1 for true, 0 for false, -1 for non-constant.
3358 */
3359
3360static int
3361expr_constant(expr_ty e)
3362{
3363 switch (e->kind) {
3364 case Num_kind:
3365 return PyObject_IsTrue(e->v.Num.n);
3366 case Str_kind:
3367 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003368 case Name_kind:
3369 /* __debug__ is not assignable, so we can optimize
3370 * it away in if and while statements */
3371 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3372 "__debug__") == 0)
3373 return ! Py_OptimizeFlag;
3374 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 default:
3376 return -1;
3377 }
3378}
3379
Guido van Rossumc2e20742006-02-27 22:32:47 +00003380/*
3381 Implements the with statement from PEP 343.
3382
3383 The semantics outlined in that PEP are as follows:
3384
3385 with EXPR as VAR:
3386 BLOCK
3387
3388 It is implemented roughly as:
3389
Guido van Rossumda5b7012006-05-02 19:47:52 +00003390 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003391 exit = context.__exit__ # not calling it
3392 value = context.__enter__()
3393 try:
3394 VAR = value # if VAR present in the syntax
3395 BLOCK
3396 finally:
3397 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003398 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003399 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003400 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003401 exit(*exc)
3402 */
3403static int
3404compiler_with(struct compiler *c, stmt_ty s)
3405{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003406 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003407 basicblock *block, *finally;
3408 identifier tmpexit, tmpvalue = NULL;
3409
3410 assert(s->kind == With_kind);
3411
Guido van Rossumc2e20742006-02-27 22:32:47 +00003412 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003413 enter_attr = PyString_InternFromString("__enter__");
3414 if (!enter_attr)
3415 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003416 }
3417 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003418 exit_attr = PyString_InternFromString("__exit__");
3419 if (!exit_attr)
3420 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003421 }
3422
3423 block = compiler_new_block(c);
3424 finally = compiler_new_block(c);
3425 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003427
3428 /* Create a temporary variable to hold context.__exit__ */
3429 tmpexit = compiler_new_tmpname(c);
3430 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003431 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003432 PyArena_AddPyObject(c->c_arena, tmpexit);
3433
3434 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003435 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003436 We need to do this rather than preserving it on the stack
3437 because SETUP_FINALLY remembers the stack level.
3438 We need to do the assignment *inside* the try/finally
3439 so that context.__exit__() is called when the assignment
3440 fails. But we need to call context.__enter__() *before*
3441 the try/finally so that if it fails we won't call
3442 context.__exit__().
3443 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003444 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003445 if (tmpvalue == NULL)
3446 return 0;
3447 PyArena_AddPyObject(c->c_arena, tmpvalue);
3448 }
3449
Guido van Rossumda5b7012006-05-02 19:47:52 +00003450 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003451 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003452
3453 /* Squirrel away context.__exit__ */
3454 ADDOP(c, DUP_TOP);
3455 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3456 if (!compiler_nameop(c, tmpexit, Store))
3457 return 0;
3458
3459 /* Call context.__enter__() */
3460 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3461 ADDOP_I(c, CALL_FUNCTION, 0);
3462
3463 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003464 /* Store it in tmpvalue */
3465 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003466 return 0;
3467 }
3468 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003469 /* Discard result from context.__enter__() */
3470 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003471 }
3472
3473 /* Start the try block */
3474 ADDOP_JREL(c, SETUP_FINALLY, finally);
3475
3476 compiler_use_next_block(c, block);
3477 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003479 }
3480
3481 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 /* Bind saved result of context.__enter__() to VAR */
3483 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003484 !compiler_nameop(c, tmpvalue, Del))
3485 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003486 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003487 }
3488
3489 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003490 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003491
3492 /* End of try block; start the finally block */
3493 ADDOP(c, POP_BLOCK);
3494 compiler_pop_fblock(c, FINALLY_TRY, block);
3495
3496 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3497 compiler_use_next_block(c, finally);
3498 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003500
3501 /* Finally block starts; push tmpexit and issue our magic opcode. */
3502 if (!compiler_nameop(c, tmpexit, Load) ||
3503 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003504 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003505 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003506
3507 /* Finally block ends. */
3508 ADDOP(c, END_FINALLY);
3509 compiler_pop_fblock(c, FINALLY_END, finally);
3510 return 1;
3511}
3512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003513static int
3514compiler_visit_expr(struct compiler *c, expr_ty e)
3515{
3516 int i, n;
3517
Jeremy Hylton12603c42006-04-01 16:18:02 +00003518 /* If expr e has a different line number than the last expr/stmt,
3519 set a new line number for the next instruction.
3520 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521 if (e->lineno > c->u->u_lineno) {
3522 c->u->u_lineno = e->lineno;
3523 c->u->u_lineno_set = false;
3524 }
3525 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003528 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 VISIT(c, expr, e->v.BinOp.left);
3530 VISIT(c, expr, e->v.BinOp.right);
3531 ADDOP(c, binop(c, e->v.BinOp.op));
3532 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003533 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 VISIT(c, expr, e->v.UnaryOp.operand);
3535 ADDOP(c, unaryop(e->v.UnaryOp.op));
3536 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003537 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003539 case IfExp_kind:
3540 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003541 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542 /* XXX get rid of arg? */
3543 ADDOP_I(c, BUILD_MAP, 0);
3544 n = asdl_seq_LEN(e->v.Dict.values);
3545 /* We must arrange things just right for STORE_SUBSCR.
3546 It wants the stack to look like (value) (dict) (key) */
3547 for (i = 0; i < n; i++) {
3548 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003549 VISIT(c, expr,
3550 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003552 VISIT(c, expr,
3553 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 ADDOP(c, STORE_SUBSCR);
3555 }
3556 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003559 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 return compiler_genexp(c, e);
3561 case Yield_kind:
3562 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 /*
3565 for (i = 0; i < c->u->u_nfblocks; i++) {
3566 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3567 return compiler_error(
3568 c, "'yield' not allowed in a 'try' "
3569 "block with a 'finally' clause");
3570 }
3571 */
3572 if (e->v.Yield.value) {
3573 VISIT(c, expr, e->v.Yield.value);
3574 }
3575 else {
3576 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3577 }
3578 ADDOP(c, YIELD_VALUE);
3579 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003580 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003581 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003582 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003584 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585 VISIT(c, expr, e->v.Repr.value);
3586 ADDOP(c, UNARY_CONVERT);
3587 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3590 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003591 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3593 break;
3594 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003595 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 if (e->v.Attribute.ctx != AugStore)
3597 VISIT(c, expr, e->v.Attribute.value);
3598 switch (e->v.Attribute.ctx) {
3599 case AugLoad:
3600 ADDOP(c, DUP_TOP);
3601 /* Fall through to load */
3602 case Load:
3603 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3604 break;
3605 case AugStore:
3606 ADDOP(c, ROT_TWO);
3607 /* Fall through to save */
3608 case Store:
3609 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3610 break;
3611 case Del:
3612 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3613 break;
3614 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003615 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003616 PyErr_SetString(PyExc_SystemError,
3617 "param invalid in attribute expression");
3618 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 }
3620 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003621 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 switch (e->v.Subscript.ctx) {
3623 case AugLoad:
3624 VISIT(c, expr, e->v.Subscript.value);
3625 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3626 break;
3627 case Load:
3628 VISIT(c, expr, e->v.Subscript.value);
3629 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3630 break;
3631 case AugStore:
3632 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3633 break;
3634 case Store:
3635 VISIT(c, expr, e->v.Subscript.value);
3636 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3637 break;
3638 case Del:
3639 VISIT(c, expr, e->v.Subscript.value);
3640 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3641 break;
3642 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003643 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003644 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003645 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003646 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647 }
3648 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003649 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3651 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003652 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 return compiler_tuple(c, e);
3656 }
3657 return 1;
3658}
3659
3660static int
3661compiler_augassign(struct compiler *c, stmt_ty s)
3662{
3663 expr_ty e = s->v.AugAssign.target;
3664 expr_ty auge;
3665
3666 assert(s->kind == AugAssign_kind);
3667
3668 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003669 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003671 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003672 if (auge == NULL)
3673 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003674 VISIT(c, expr, auge);
3675 VISIT(c, expr, s->v.AugAssign.value);
3676 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3677 auge->v.Attribute.ctx = AugStore;
3678 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 break;
3680 case Subscript_kind:
3681 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003682 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003683 if (auge == NULL)
3684 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003685 VISIT(c, expr, auge);
3686 VISIT(c, expr, s->v.AugAssign.value);
3687 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003688 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003689 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003690 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003692 if (!compiler_nameop(c, e->v.Name.id, Load))
3693 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 VISIT(c, expr, s->v.AugAssign.value);
3695 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3696 return compiler_nameop(c, e->v.Name.id, Store);
3697 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003698 PyErr_Format(PyExc_SystemError,
3699 "invalid node type (%d) for augmented assignment",
3700 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702 }
3703 return 1;
3704}
3705
3706static int
3707compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3708{
3709 struct fblockinfo *f;
3710 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3711 return 0;
3712 f = &c->u->u_fblock[c->u->u_nfblocks++];
3713 f->fb_type = t;
3714 f->fb_block = b;
3715 return 1;
3716}
3717
3718static void
3719compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3720{
3721 struct compiler_unit *u = c->u;
3722 assert(u->u_nfblocks > 0);
3723 u->u_nfblocks--;
3724 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3725 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3726}
3727
3728/* Raises a SyntaxError and returns 0.
3729 If something goes wrong, a different exception may be raised.
3730*/
3731
3732static int
3733compiler_error(struct compiler *c, const char *errstr)
3734{
3735 PyObject *loc;
3736 PyObject *u = NULL, *v = NULL;
3737
3738 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3739 if (!loc) {
3740 Py_INCREF(Py_None);
3741 loc = Py_None;
3742 }
3743 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3744 Py_None, loc);
3745 if (!u)
3746 goto exit;
3747 v = Py_BuildValue("(zO)", errstr, u);
3748 if (!v)
3749 goto exit;
3750 PyErr_SetObject(PyExc_SyntaxError, v);
3751 exit:
3752 Py_DECREF(loc);
3753 Py_XDECREF(u);
3754 Py_XDECREF(v);
3755 return 0;
3756}
3757
3758static int
3759compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003760 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003762 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003764 /* XXX this code is duplicated */
3765 switch (ctx) {
3766 case AugLoad: /* fall through to Load */
3767 case Load: op = BINARY_SUBSCR; break;
3768 case AugStore:/* fall through to Store */
3769 case Store: op = STORE_SUBSCR; break;
3770 case Del: op = DELETE_SUBSCR; break;
3771 case Param:
3772 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003773 "invalid %s kind %d in subscript\n",
3774 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003775 return 0;
3776 }
3777 if (ctx == AugLoad) {
3778 ADDOP_I(c, DUP_TOPX, 2);
3779 }
3780 else if (ctx == AugStore) {
3781 ADDOP(c, ROT_THREE);
3782 }
3783 ADDOP(c, op);
3784 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785}
3786
3787static int
3788compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3789{
3790 int n = 2;
3791 assert(s->kind == Slice_kind);
3792
3793 /* only handles the cases where BUILD_SLICE is emitted */
3794 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003795 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003796 }
3797 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003798 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003800
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003801 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003802 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803 }
3804 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003805 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806 }
3807
3808 if (s->v.Slice.step) {
3809 n++;
3810 VISIT(c, expr, s->v.Slice.step);
3811 }
3812 ADDOP_I(c, BUILD_SLICE, n);
3813 return 1;
3814}
3815
3816static int
3817compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3818{
3819 int op = 0, slice_offset = 0, stack_count = 0;
3820
3821 assert(s->v.Slice.step == NULL);
3822 if (s->v.Slice.lower) {
3823 slice_offset++;
3824 stack_count++;
3825 if (ctx != AugStore)
3826 VISIT(c, expr, s->v.Slice.lower);
3827 }
3828 if (s->v.Slice.upper) {
3829 slice_offset += 2;
3830 stack_count++;
3831 if (ctx != AugStore)
3832 VISIT(c, expr, s->v.Slice.upper);
3833 }
3834
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003835 if (ctx == AugLoad) {
3836 switch (stack_count) {
3837 case 0: ADDOP(c, DUP_TOP); break;
3838 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3839 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3840 }
3841 }
3842 else if (ctx == AugStore) {
3843 switch (stack_count) {
3844 case 0: ADDOP(c, ROT_TWO); break;
3845 case 1: ADDOP(c, ROT_THREE); break;
3846 case 2: ADDOP(c, ROT_FOUR); break;
3847 }
3848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849
3850 switch (ctx) {
3851 case AugLoad: /* fall through to Load */
3852 case Load: op = SLICE; break;
3853 case AugStore:/* fall through to Store */
3854 case Store: op = STORE_SLICE; break;
3855 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003856 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003857 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003858 PyErr_SetString(PyExc_SystemError,
3859 "param invalid in simple slice");
3860 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003861 }
3862
3863 ADDOP(c, op + slice_offset);
3864 return 1;
3865}
3866
3867static int
3868compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3869 expr_context_ty ctx)
3870{
3871 switch (s->kind) {
3872 case Ellipsis_kind:
3873 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3874 break;
3875 case Slice_kind:
3876 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003877 case Index_kind:
3878 VISIT(c, expr, s->v.Index.value);
3879 break;
3880 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003881 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003882 PyErr_SetString(PyExc_SystemError,
3883 "extended slice invalid in nested slice");
3884 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 }
3886 return 1;
3887}
3888
3889
3890static int
3891compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3892{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003893 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003895 case Index_kind:
3896 kindname = "index";
3897 if (ctx != AugStore) {
3898 VISIT(c, expr, s->v.Index.value);
3899 }
3900 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003901 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003902 kindname = "ellipsis";
3903 if (ctx != AugStore) {
3904 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3905 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 break;
3907 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003908 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003909 if (!s->v.Slice.step)
3910 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003911 if (ctx != AugStore) {
3912 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003913 return 0;
3914 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003915 break;
3916 case ExtSlice_kind:
3917 kindname = "extended slice";
3918 if (ctx != AugStore) {
3919 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3920 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003921 slice_ty sub = (slice_ty)asdl_seq_GET(
3922 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003923 if (!compiler_visit_nested_slice(c, sub, ctx))
3924 return 0;
3925 }
3926 ADDOP_I(c, BUILD_TUPLE, n);
3927 }
3928 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003929 default:
3930 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003931 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003934 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935}
3936
3937/* do depth-first search of basic block graph, starting with block.
3938 post records the block indices in post-order.
3939
3940 XXX must handle implicit jumps from one block to next
3941*/
3942
3943static void
3944dfs(struct compiler *c, basicblock *b, struct assembler *a)
3945{
3946 int i;
3947 struct instr *instr = NULL;
3948
3949 if (b->b_seen)
3950 return;
3951 b->b_seen = 1;
3952 if (b->b_next != NULL)
3953 dfs(c, b->b_next, a);
3954 for (i = 0; i < b->b_iused; i++) {
3955 instr = &b->b_instr[i];
3956 if (instr->i_jrel || instr->i_jabs)
3957 dfs(c, instr->i_target, a);
3958 }
3959 a->a_postorder[a->a_nblocks++] = b;
3960}
3961
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003962static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003963stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3964{
3965 int i;
3966 struct instr *instr;
3967 if (b->b_seen || b->b_startdepth >= depth)
3968 return maxdepth;
3969 b->b_seen = 1;
3970 b->b_startdepth = depth;
3971 for (i = 0; i < b->b_iused; i++) {
3972 instr = &b->b_instr[i];
3973 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3974 if (depth > maxdepth)
3975 maxdepth = depth;
3976 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3977 if (instr->i_jrel || instr->i_jabs) {
3978 maxdepth = stackdepth_walk(c, instr->i_target,
3979 depth, maxdepth);
3980 if (instr->i_opcode == JUMP_ABSOLUTE ||
3981 instr->i_opcode == JUMP_FORWARD) {
3982 goto out; /* remaining code is dead */
3983 }
3984 }
3985 }
3986 if (b->b_next)
3987 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3988out:
3989 b->b_seen = 0;
3990 return maxdepth;
3991}
3992
3993/* Find the flow path that needs the largest stack. We assume that
3994 * cycles in the flow graph have no net effect on the stack depth.
3995 */
3996static int
3997stackdepth(struct compiler *c)
3998{
3999 basicblock *b, *entryblock;
4000 entryblock = NULL;
4001 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4002 b->b_seen = 0;
4003 b->b_startdepth = INT_MIN;
4004 entryblock = b;
4005 }
4006 return stackdepth_walk(c, entryblock, 0, 0);
4007}
4008
4009static int
4010assemble_init(struct assembler *a, int nblocks, int firstlineno)
4011{
4012 memset(a, 0, sizeof(struct assembler));
4013 a->a_lineno = firstlineno;
4014 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4015 if (!a->a_bytecode)
4016 return 0;
4017 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4018 if (!a->a_lnotab)
4019 return 0;
4020 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004021 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004022 if (!a->a_postorder) {
4023 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004024 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004025 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004026 return 1;
4027}
4028
4029static void
4030assemble_free(struct assembler *a)
4031{
4032 Py_XDECREF(a->a_bytecode);
4033 Py_XDECREF(a->a_lnotab);
4034 if (a->a_postorder)
4035 PyObject_Free(a->a_postorder);
4036}
4037
4038/* Return the size of a basic block in bytes. */
4039
4040static int
4041instrsize(struct instr *instr)
4042{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004043 if (!instr->i_hasarg)
4044 return 1;
4045 if (instr->i_oparg > 0xffff)
4046 return 6;
4047 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048}
4049
4050static int
4051blocksize(basicblock *b)
4052{
4053 int i;
4054 int size = 0;
4055
4056 for (i = 0; i < b->b_iused; i++)
4057 size += instrsize(&b->b_instr[i]);
4058 return size;
4059}
4060
4061/* All about a_lnotab.
4062
4063c_lnotab is an array of unsigned bytes disguised as a Python string.
4064It is used to map bytecode offsets to source code line #s (when needed
4065for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004066
Tim Peters2a7f3842001-06-09 09:26:21 +00004067The array is conceptually a list of
4068 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004069pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004070
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004071 byte code offset source code line number
4072 0 1
4073 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004074 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004075 350 307
4076 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004077
4078The first trick is that these numbers aren't stored, only the increments
4079from one row to the next (this doesn't really work, but it's a start):
4080
4081 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4082
4083The second trick is that an unsigned byte can't hold negative values, or
4084values larger than 255, so (a) there's a deep assumption that byte code
4085offsets and their corresponding line #s both increase monotonically, and (b)
4086if at least one column jumps by more than 255 from one row to the next, more
4087than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004088from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004089part. A user of c_lnotab desiring to find the source line number
4090corresponding to a bytecode address A should do something like this
4091
4092 lineno = addr = 0
4093 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004094 addr += addr_incr
4095 if addr > A:
4096 return lineno
4097 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004098
4099In order for this to work, when the addr field increments by more than 255,
4100the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004101increment is < 256. So, in the example above, assemble_lnotab (it used
4102to be called com_set_lineno) should not (as was actually done until 2.2)
4103expand 300, 300 to 255, 255, 45, 45,
4104 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004105*/
4106
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004107static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004108assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004109{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110 int d_bytecode, d_lineno;
4111 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004112 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113
4114 d_bytecode = a->a_offset - a->a_lineno_off;
4115 d_lineno = i->i_lineno - a->a_lineno;
4116
4117 assert(d_bytecode >= 0);
4118 assert(d_lineno >= 0);
4119
4120 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004121 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004122
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004124 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004125 nbytes = a->a_lnotab_off + 2 * ncodes;
4126 len = PyString_GET_SIZE(a->a_lnotab);
4127 if (nbytes >= len) {
4128 if (len * 2 < nbytes)
4129 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004130 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131 len *= 2;
4132 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4133 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004134 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004135 lnotab = (unsigned char *)
4136 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004137 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 *lnotab++ = 255;
4139 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 d_bytecode -= ncodes * 255;
4142 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004143 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144 assert(d_bytecode <= 255);
4145 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004146 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 nbytes = a->a_lnotab_off + 2 * ncodes;
4148 len = PyString_GET_SIZE(a->a_lnotab);
4149 if (nbytes >= len) {
4150 if (len * 2 < nbytes)
4151 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004152 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 len *= 2;
4154 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4155 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004156 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004157 lnotab = (unsigned char *)
4158 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004160 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004162 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004164 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 d_lineno -= ncodes * 255;
4167 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004168 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004169
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170 len = PyString_GET_SIZE(a->a_lnotab);
4171 if (a->a_lnotab_off + 2 >= len) {
4172 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004173 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004174 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004175 lnotab = (unsigned char *)
4176 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178 a->a_lnotab_off += 2;
4179 if (d_bytecode) {
4180 *lnotab++ = d_bytecode;
4181 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004182 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004183 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 *lnotab++ = 0;
4185 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004186 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187 a->a_lineno = i->i_lineno;
4188 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004189 return 1;
4190}
4191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004192/* assemble_emit()
4193 Extend the bytecode with a new instruction.
4194 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004195*/
4196
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004197static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004199{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004200 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004201 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004202 char *code;
4203
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004204 size = instrsize(i);
4205 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004207 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004208 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004209 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004210 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 if (a->a_offset + size >= len) {
4212 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004213 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4216 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004217 if (size == 6) {
4218 assert(i->i_hasarg);
4219 *code++ = (char)EXTENDED_ARG;
4220 *code++ = ext & 0xff;
4221 *code++ = ext >> 8;
4222 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004225 if (i->i_hasarg) {
4226 assert(size == 3 || size == 6);
4227 *code++ = arg & 0xff;
4228 *code++ = arg >> 8;
4229 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004231}
4232
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004233static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004234assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004235{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004237 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004238 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004239
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240 /* Compute the size of each block and fixup jump args.
4241 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004242start:
4243 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004244 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004245 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246 bsize = blocksize(b);
4247 b->b_offset = totsize;
4248 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004249 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004250 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004251 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4252 bsize = b->b_offset;
4253 for (i = 0; i < b->b_iused; i++) {
4254 struct instr *instr = &b->b_instr[i];
4255 /* Relative jumps are computed relative to
4256 the instruction pointer after fetching
4257 the jump instruction.
4258 */
4259 bsize += instrsize(instr);
4260 if (instr->i_jabs)
4261 instr->i_oparg = instr->i_target->b_offset;
4262 else if (instr->i_jrel) {
4263 int delta = instr->i_target->b_offset - bsize;
4264 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004265 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004266 else
4267 continue;
4268 if (instr->i_oparg > 0xffff)
4269 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004270 }
4271 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004272
4273 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004274 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004275 with a better solution.
4276
4277 In the meantime, should the goto be dropped in favor
4278 of a loop?
4279
4280 The issue is that in the first loop blocksize() is called
4281 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004282 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004283 i_oparg is calculated in the second loop above.
4284
4285 So we loop until we stop seeing new EXTENDED_ARGs.
4286 The only EXTENDED_ARGs that could be popping up are
4287 ones in jump instructions. So this should converge
4288 fairly quickly.
4289 */
4290 if (last_extended_arg_count != extended_arg_count) {
4291 last_extended_arg_count = extended_arg_count;
4292 goto start;
4293 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004294}
4295
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004296static PyObject *
4297dict_keys_inorder(PyObject *dict, int offset)
4298{
4299 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004300 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004301
4302 tuple = PyTuple_New(size);
4303 if (tuple == NULL)
4304 return NULL;
4305 while (PyDict_Next(dict, &pos, &k, &v)) {
4306 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004307 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004308 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004309 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004310 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004311 PyTuple_SET_ITEM(tuple, i - offset, k);
4312 }
4313 return tuple;
4314}
4315
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004316static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004317compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004318{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004319 PySTEntryObject *ste = c->u->u_ste;
4320 int flags = 0, n;
4321 if (ste->ste_type != ModuleBlock)
4322 flags |= CO_NEWLOCALS;
4323 if (ste->ste_type == FunctionBlock) {
4324 if (!ste->ste_unoptimized)
4325 flags |= CO_OPTIMIZED;
4326 if (ste->ste_nested)
4327 flags |= CO_NESTED;
4328 if (ste->ste_generator)
4329 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331 if (ste->ste_varargs)
4332 flags |= CO_VARARGS;
4333 if (ste->ste_varkeywords)
4334 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004335 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004336 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004337
4338 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004339 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004341 n = PyDict_Size(c->u->u_freevars);
4342 if (n < 0)
4343 return -1;
4344 if (n == 0) {
4345 n = PyDict_Size(c->u->u_cellvars);
4346 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004347 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004348 if (n == 0) {
4349 flags |= CO_NOFREE;
4350 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004351 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004352
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004353 return flags;
4354}
4355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004356static PyCodeObject *
4357makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004358{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004359 PyObject *tmp;
4360 PyCodeObject *co = NULL;
4361 PyObject *consts = NULL;
4362 PyObject *names = NULL;
4363 PyObject *varnames = NULL;
4364 PyObject *filename = NULL;
4365 PyObject *name = NULL;
4366 PyObject *freevars = NULL;
4367 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004368 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004370
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004371 tmp = dict_keys_inorder(c->u->u_consts, 0);
4372 if (!tmp)
4373 goto error;
4374 consts = PySequence_List(tmp); /* optimize_code requires a list */
4375 Py_DECREF(tmp);
4376
4377 names = dict_keys_inorder(c->u->u_names, 0);
4378 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4379 if (!consts || !names || !varnames)
4380 goto error;
4381
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004382 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4383 if (!cellvars)
4384 goto error;
4385 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4386 if (!freevars)
4387 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004388 filename = PyString_FromString(c->c_filename);
4389 if (!filename)
4390 goto error;
4391
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004392 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393 flags = compute_code_flags(c);
4394 if (flags < 0)
4395 goto error;
4396
4397 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4398 if (!bytecode)
4399 goto error;
4400
4401 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4402 if (!tmp)
4403 goto error;
4404 Py_DECREF(consts);
4405 consts = tmp;
4406
4407 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4408 bytecode, consts, names, varnames,
4409 freevars, cellvars,
4410 filename, c->u->u_name,
4411 c->u->u_firstlineno,
4412 a->a_lnotab);
4413 error:
4414 Py_XDECREF(consts);
4415 Py_XDECREF(names);
4416 Py_XDECREF(varnames);
4417 Py_XDECREF(filename);
4418 Py_XDECREF(name);
4419 Py_XDECREF(freevars);
4420 Py_XDECREF(cellvars);
4421 Py_XDECREF(bytecode);
4422 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004423}
4424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425static PyCodeObject *
4426assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004427{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428 basicblock *b, *entryblock;
4429 struct assembler a;
4430 int i, j, nblocks;
4431 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004432
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433 /* Make sure every block that falls off the end returns None.
4434 XXX NEXT_BLOCK() isn't quite right, because if the last
4435 block ends with a jump or return b_next shouldn't set.
4436 */
4437 if (!c->u->u_curblock->b_return) {
4438 NEXT_BLOCK(c);
4439 if (addNone)
4440 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4441 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004442 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004443
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004444 nblocks = 0;
4445 entryblock = NULL;
4446 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4447 nblocks++;
4448 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004449 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004450
Neal Norwitzed657552006-07-10 00:04:44 +00004451 /* Set firstlineno if it wasn't explicitly set. */
4452 if (!c->u->u_firstlineno) {
4453 if (entryblock && entryblock->b_instr)
4454 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4455 else
4456 c->u->u_firstlineno = 1;
4457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004458 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4459 goto error;
4460 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004462 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004463 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004464
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004465 /* Emit code in reverse postorder from dfs. */
4466 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004467 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004468 for (j = 0; j < b->b_iused; j++)
4469 if (!assemble_emit(&a, &b->b_instr[j]))
4470 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004471 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004472
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004473 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4474 goto error;
4475 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4476 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004477
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004478 co = makecode(c, &a);
4479 error:
4480 assemble_free(&a);
4481 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004482}