blob: 76c462829dc21458668b01adf6e336bcce15cf3f [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
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000146 int c_interactive; /* true if in interactive mode */
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;
Neal Norwitz84167d02006-08-12 01:45:47 +0000207 if (privateobj == NULL || !PyString_Check(privateobj) ||
208 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000209 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;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000305 if (!arena)
306 return NULL;
307 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000308 if (mod)
309 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000310 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000311 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000312}
313
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000314static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317 if (c->c_st)
318 PySymtable_Free(c->c_st);
319 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000320 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322}
323
Guido van Rossum79f25d91997-04-29 20:08:16 +0000324static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000325list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000326{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000328 PyObject *v, *k;
329 PyObject *dict = PyDict_New();
330 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000332 n = PyList_Size(list);
333 for (i = 0; i < n; i++) {
334 v = PyInt_FromLong(i);
335 if (!v) {
336 Py_DECREF(dict);
337 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000338 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000339 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000340 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
342 Py_XDECREF(k);
343 Py_DECREF(v);
344 Py_DECREF(dict);
345 return NULL;
346 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000347 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 return dict;
351}
352
353/* Return new dict containing names from src that match scope(s).
354
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000355src is a symbol table dictionary. If the scope of a name matches
356either scope_type or flag is set, insert it into the new dict. The
357values are integers, starting at offset and increasing by one for
358each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359*/
360
361static PyObject *
362dictbytype(PyObject *src, int scope_type, int flag, int offset)
363{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365 PyObject *k, *v, *dest = PyDict_New();
366
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000367 assert(offset >= 0);
368 if (dest == NULL)
369 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000370
371 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000372 /* XXX this should probably be a macro in symtable.h */
373 assert(PyInt_Check(v));
374 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000375
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000376 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
377 PyObject *tuple, *item = PyInt_FromLong(i);
378 if (item == NULL) {
379 Py_DECREF(dest);
380 return NULL;
381 }
382 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000383 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000384 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
385 Py_DECREF(item);
386 Py_DECREF(dest);
387 Py_XDECREF(tuple);
388 return NULL;
389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000391 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393 }
394 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000395}
396
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000397/* Begin: Peephole optimizations ----------------------------------------- */
398
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000399#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000400#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000401#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
402#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000403#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000405#define ISBASICBLOCK(blocks, start, bytes) \
406 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000407
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000408/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000409 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000410 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000412 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000413 Bails out with no change if one or more of the LOAD_CONSTs is missing.
414 Also works for BUILD_LIST when followed by an "in" or "not in" test.
415*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000416static int
417tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
418{
419 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000421
422 /* Pre-conditions */
423 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000424 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000426 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000427 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000428
429 /* Buildup new tuple of constants */
430 newconst = PyTuple_New(n);
431 if (newconst == NULL)
432 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 for (i=0 ; i<n ; i++) {
435 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000436 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000437 constant = PyList_GET_ITEM(consts, arg);
438 Py_INCREF(constant);
439 PyTuple_SET_ITEM(newconst, i, constant);
440 }
441
442 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000443 if (PyList_Append(consts, newconst)) {
444 Py_DECREF(newconst);
445 return 0;
446 }
447 Py_DECREF(newconst);
448
449 /* Write NOPs over old LOAD_CONSTS and
450 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
451 memset(codestr, NOP, n*3);
452 codestr[n*3] = LOAD_CONST;
453 SETARG(codestr, (n*3), len_consts);
454 return 1;
455}
456
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000457/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000458 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000459 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000460 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000461 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000462 Abandons the transformation if the folding fails (i.e. 1+'a').
463 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 is below a threshold value. That keeps pyc files from
465 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000466*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000467static int
468fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
469{
470 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000471 Py_ssize_t len_consts, size;
472 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000473
474 /* Pre-conditions */
475 assert(PyList_CheckExact(consts));
476 assert(codestr[0] == LOAD_CONST);
477 assert(codestr[3] == LOAD_CONST);
478
479 /* Create new constant */
480 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
481 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
482 opcode = codestr[6];
483 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000484 case BINARY_POWER:
485 newconst = PyNumber_Power(v, w, Py_None);
486 break;
487 case BINARY_MULTIPLY:
488 newconst = PyNumber_Multiply(v, w);
489 break;
490 case BINARY_DIVIDE:
491 /* Cannot fold this operation statically since
492 the result can depend on the run-time presence
493 of the -Qnew flag */
494 return 0;
495 case BINARY_TRUE_DIVIDE:
496 newconst = PyNumber_TrueDivide(v, w);
497 break;
498 case BINARY_FLOOR_DIVIDE:
499 newconst = PyNumber_FloorDivide(v, w);
500 break;
501 case BINARY_MODULO:
502 newconst = PyNumber_Remainder(v, w);
503 break;
504 case BINARY_ADD:
505 newconst = PyNumber_Add(v, w);
506 break;
507 case BINARY_SUBTRACT:
508 newconst = PyNumber_Subtract(v, w);
509 break;
510 case BINARY_SUBSCR:
511 newconst = PyObject_GetItem(v, w);
512 break;
513 case BINARY_LSHIFT:
514 newconst = PyNumber_Lshift(v, w);
515 break;
516 case BINARY_RSHIFT:
517 newconst = PyNumber_Rshift(v, w);
518 break;
519 case BINARY_AND:
520 newconst = PyNumber_And(v, w);
521 break;
522 case BINARY_XOR:
523 newconst = PyNumber_Xor(v, w);
524 break;
525 case BINARY_OR:
526 newconst = PyNumber_Or(v, w);
527 break;
528 default:
529 /* Called with an unknown opcode */
530 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000531 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000532 opcode);
533 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000534 }
535 if (newconst == NULL) {
536 PyErr_Clear();
537 return 0;
538 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000539 size = PyObject_Size(newconst);
540 if (size == -1)
541 PyErr_Clear();
542 else if (size > 20) {
543 Py_DECREF(newconst);
544 return 0;
545 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000546
547 /* Append folded constant into consts table */
548 len_consts = PyList_GET_SIZE(consts);
549 if (PyList_Append(consts, newconst)) {
550 Py_DECREF(newconst);
551 return 0;
552 }
553 Py_DECREF(newconst);
554
555 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
556 memset(codestr, NOP, 4);
557 codestr[4] = LOAD_CONST;
558 SETARG(codestr, 4, len_consts);
559 return 1;
560}
561
Raymond Hettinger80121492005-02-20 12:41:32 +0000562static int
563fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
564{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000565 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000566 Py_ssize_t len_consts;
567 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000568
569 /* Pre-conditions */
570 assert(PyList_CheckExact(consts));
571 assert(codestr[0] == LOAD_CONST);
572
573 /* Create new constant */
574 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
575 opcode = codestr[3];
576 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000577 case UNARY_NEGATIVE:
578 /* Preserve the sign of -0.0 */
579 if (PyObject_IsTrue(v) == 1)
580 newconst = PyNumber_Negative(v);
581 break;
582 case UNARY_CONVERT:
583 newconst = PyObject_Repr(v);
584 break;
585 case UNARY_INVERT:
586 newconst = PyNumber_Invert(v);
587 break;
588 default:
589 /* Called with an unknown opcode */
590 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000591 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000592 opcode);
593 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000594 }
595 if (newconst == NULL) {
596 PyErr_Clear();
597 return 0;
598 }
599
600 /* Append folded constant into consts table */
601 len_consts = PyList_GET_SIZE(consts);
602 if (PyList_Append(consts, newconst)) {
603 Py_DECREF(newconst);
604 return 0;
605 }
606 Py_DECREF(newconst);
607
608 /* Write NOP LOAD_CONST newconst */
609 codestr[0] = NOP;
610 codestr[1] = LOAD_CONST;
611 SETARG(codestr, 1, len_consts);
612 return 1;
613}
614
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000615static unsigned int *
616markblocks(unsigned char *code, int len)
617{
Anthony Baxter7b782b62006-04-11 12:01:56 +0000618 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000619 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000620
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000621 if (blocks == NULL) {
622 PyErr_NoMemory();
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000623 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000624 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000625 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000626
627 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000628 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
629 opcode = code[i];
630 switch (opcode) {
631 case FOR_ITER:
632 case JUMP_FORWARD:
633 case JUMP_IF_FALSE:
634 case JUMP_IF_TRUE:
635 case JUMP_ABSOLUTE:
636 case CONTINUE_LOOP:
637 case SETUP_LOOP:
638 case SETUP_EXCEPT:
639 case SETUP_FINALLY:
640 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000641 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000642 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000643 }
644 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000645 /* Build block numbers in the second pass */
646 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000647 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000648 blocks[i] = blockcnt;
649 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000650 return blocks;
651}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000652
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000653/* Perform basic peephole optimizations to components of a code object.
654 The consts object should still be in list form to allow new constants
655 to be appended.
656
657 To keep the optimizer simple, it bails out (does nothing) for code
658 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000659 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000660 the lineno table has complex encoding for gaps >= 255.
661
662 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000663 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000664 smaller. For those that reduce size, the gaps are initially filled with
665 NOPs. Later those NOPs are removed and the jump addresses retargeted in
666 a single pass. Line numbering is adjusted accordingly. */
667
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000668static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000669optimize_code(PyObject *code, PyObject* consts, PyObject *names,
670 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000671{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000672 Py_ssize_t i, j, codelen;
673 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000674 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000675 unsigned char *codestr = NULL;
676 unsigned char *lineno;
677 int *addrmap = NULL;
678 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000679 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000680 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000681 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000682
Raymond Hettingereffb3932004-10-30 08:55:08 +0000683 /* Bail out if an exception is set */
684 if (PyErr_Occurred())
685 goto exitUnchanged;
686
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000687 /* Bypass optimization when the lineno table is too complex */
688 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000689 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000690 tabsiz = PyString_GET_SIZE(lineno_obj);
691 if (memchr(lineno, 255, tabsiz) != NULL)
692 goto exitUnchanged;
693
Raymond Hettingera12fa142004-08-24 04:34:16 +0000694 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000695 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000696 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000697 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000698 goto exitUnchanged;
699
700 /* Make a modifiable copy of the code string */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000701 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000702 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000703 goto exitUnchanged;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000704 codestr = (unsigned char *)memcpy(codestr,
705 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000706
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000707 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000708 the various transformation patterns to look ahead several
709 instructions without additional checks to make sure they are not
710 looking beyond the end of the code string.
711 */
712 if (codestr[codelen-1] != RETURN_VALUE)
713 goto exitUnchanged;
714
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000715 /* Mapping to new jump targets after NOPs are removed */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000716 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000717 if (addrmap == NULL)
718 goto exitUnchanged;
719
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000720 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000721 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000722 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000723 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000724
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000725 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000726 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000727
728 lastlc = cumlc;
729 cumlc = 0;
730
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000731 switch (opcode) {
732
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000733 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
734 with JUMP_IF_TRUE POP_TOP */
735 case UNARY_NOT:
736 if (codestr[i+1] != JUMP_IF_FALSE ||
737 codestr[i+4] != POP_TOP ||
738 !ISBASICBLOCK(blocks,i,5))
739 continue;
740 tgt = GETJUMPTGT(codestr, (i+1));
741 if (codestr[tgt] != POP_TOP)
742 continue;
743 j = GETARG(codestr, i+1) + 1;
744 codestr[i] = JUMP_IF_TRUE;
745 SETARG(codestr, i, j);
746 codestr[i+3] = POP_TOP;
747 codestr[i+4] = NOP;
748 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000749
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000750 /* not a is b --> a is not b
751 not a in b --> a not in b
752 not a is not b --> a is b
753 not a not in b --> a in b
754 */
755 case COMPARE_OP:
756 j = GETARG(codestr, i);
757 if (j < 6 || j > 9 ||
758 codestr[i+3] != UNARY_NOT ||
759 !ISBASICBLOCK(blocks,i,4))
760 continue;
761 SETARG(codestr, i, (j^1));
762 codestr[i+3] = NOP;
763 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000764
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000765 /* Replace LOAD_GLOBAL/LOAD_NAME None
766 with LOAD_CONST None */
767 case LOAD_NAME:
768 case LOAD_GLOBAL:
769 j = GETARG(codestr, i);
770 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
771 if (name == NULL || strcmp(name, "None") != 0)
772 continue;
773 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
774 if (PyList_GET_ITEM(consts, j) == Py_None) {
775 codestr[i] = LOAD_CONST;
776 SETARG(codestr, i, j);
777 cumlc = lastlc + 1;
778 break;
779 }
780 }
781 break;
782
783 /* Skip over LOAD_CONST trueconst
784 JUMP_IF_FALSE xx POP_TOP */
785 case LOAD_CONST:
786 cumlc = lastlc + 1;
787 j = GETARG(codestr, i);
788 if (codestr[i+3] != JUMP_IF_FALSE ||
789 codestr[i+6] != POP_TOP ||
790 !ISBASICBLOCK(blocks,i,7) ||
791 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
792 continue;
793 memset(codestr+i, NOP, 7);
794 cumlc = 0;
795 break;
796
797 /* Try to fold tuples of constants (includes a case for lists
798 which are only used for "in" and "not in" tests).
799 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
800 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
801 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
802 case BUILD_TUPLE:
803 case BUILD_LIST:
804 j = GETARG(codestr, i);
805 h = i - 3 * j;
806 if (h >= 0 &&
807 j <= lastlc &&
808 ((opcode == BUILD_TUPLE &&
809 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
810 (opcode == BUILD_LIST &&
811 codestr[i+3]==COMPARE_OP &&
812 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
813 (GETARG(codestr,i+3)==6 ||
814 GETARG(codestr,i+3)==7))) &&
815 tuple_of_constants(&codestr[h], j, consts)) {
816 assert(codestr[i] == LOAD_CONST);
817 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000818 break;
819 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000820 if (codestr[i+3] != UNPACK_SEQUENCE ||
821 !ISBASICBLOCK(blocks,i,6) ||
822 j != GETARG(codestr, i+3))
823 continue;
824 if (j == 1) {
825 memset(codestr+i, NOP, 6);
826 } else if (j == 2) {
827 codestr[i] = ROT_TWO;
828 memset(codestr+i+1, NOP, 5);
829 } else if (j == 3) {
830 codestr[i] = ROT_THREE;
831 codestr[i+1] = ROT_TWO;
832 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000833 }
834 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000835
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000836 /* Fold binary ops on constants.
837 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
838 case BINARY_POWER:
839 case BINARY_MULTIPLY:
840 case BINARY_TRUE_DIVIDE:
841 case BINARY_FLOOR_DIVIDE:
842 case BINARY_MODULO:
843 case BINARY_ADD:
844 case BINARY_SUBTRACT:
845 case BINARY_SUBSCR:
846 case BINARY_LSHIFT:
847 case BINARY_RSHIFT:
848 case BINARY_AND:
849 case BINARY_XOR:
850 case BINARY_OR:
851 if (lastlc >= 2 &&
852 ISBASICBLOCK(blocks, i-6, 7) &&
853 fold_binops_on_constants(&codestr[i-6], consts)) {
854 i -= 2;
855 assert(codestr[i] == LOAD_CONST);
856 cumlc = 1;
857 }
858 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000859
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000860 /* Fold unary ops on constants.
861 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
862 case UNARY_NEGATIVE:
863 case UNARY_CONVERT:
864 case UNARY_INVERT:
865 if (lastlc >= 1 &&
866 ISBASICBLOCK(blocks, i-3, 4) &&
867 fold_unaryops_on_constants(&codestr[i-3], consts)) {
868 i -= 2;
869 assert(codestr[i] == LOAD_CONST);
870 cumlc = 1;
871 }
872 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000873
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000874 /* Simplify conditional jump to conditional jump where the
875 result of the first test implies the success of a similar
876 test or the failure of the opposite test.
877 Arises in code like:
878 "if a and b:"
879 "if a or b:"
880 "a and b or c"
881 "(a and b) and c"
882 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
883 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
884 where y+3 is the instruction following the second test.
885 */
886 case JUMP_IF_FALSE:
887 case JUMP_IF_TRUE:
888 tgt = GETJUMPTGT(codestr, i);
889 j = codestr[tgt];
890 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
891 if (j == opcode) {
892 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
893 SETARG(codestr, i, tgttgt);
894 } else {
895 tgt -= i;
896 SETARG(codestr, i, tgt);
897 }
898 break;
899 }
900 /* Intentional fallthrough */
901
902 /* Replace jumps to unconditional jumps */
903 case FOR_ITER:
904 case JUMP_FORWARD:
905 case JUMP_ABSOLUTE:
906 case CONTINUE_LOOP:
907 case SETUP_LOOP:
908 case SETUP_EXCEPT:
909 case SETUP_FINALLY:
910 tgt = GETJUMPTGT(codestr, i);
911 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
912 continue;
913 tgttgt = GETJUMPTGT(codestr, tgt);
914 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
915 opcode = JUMP_ABSOLUTE;
916 if (!ABSOLUTE_JUMP(opcode))
917 tgttgt -= i + 3; /* Calc relative jump addr */
918 if (tgttgt < 0) /* No backward relative jumps */
919 continue;
920 codestr[i] = opcode;
921 SETARG(codestr, i, tgttgt);
922 break;
923
924 case EXTENDED_ARG:
925 goto exitUnchanged;
926
927 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
928 case RETURN_VALUE:
929 if (i+4 >= codelen ||
930 codestr[i+4] != RETURN_VALUE ||
931 !ISBASICBLOCK(blocks,i,5))
932 continue;
933 memset(codestr+i+1, NOP, 4);
934 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000935 }
936 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000937
938 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000939 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
940 addrmap[i] = i - nops;
941 if (codestr[i] == NOP)
942 nops++;
943 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000944 cum_orig_line = 0;
945 last_line = 0;
946 for (i=0 ; i < tabsiz ; i+=2) {
947 cum_orig_line += lineno[i];
948 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000949 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000950 lineno[i] =((unsigned char)(new_line - last_line));
951 last_line = new_line;
952 }
953
954 /* Remove NOPs and fixup jump targets */
955 for (i=0, h=0 ; i<codelen ; ) {
956 opcode = codestr[i];
957 switch (opcode) {
958 case NOP:
959 i++;
960 continue;
961
962 case JUMP_ABSOLUTE:
963 case CONTINUE_LOOP:
964 j = addrmap[GETARG(codestr, i)];
965 SETARG(codestr, i, j);
966 break;
967
968 case FOR_ITER:
969 case JUMP_FORWARD:
970 case JUMP_IF_FALSE:
971 case JUMP_IF_TRUE:
972 case SETUP_LOOP:
973 case SETUP_EXCEPT:
974 case SETUP_FINALLY:
975 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
976 SETARG(codestr, i, j);
977 break;
978 }
979 adj = CODESIZE(opcode);
980 while (adj--)
981 codestr[h++] = codestr[i++];
982 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000983 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000984
985 code = PyString_FromStringAndSize((char *)codestr, h);
986 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000987 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000988 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000989 return code;
990
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000991 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000992 if (blocks != NULL)
993 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000994 if (addrmap != NULL)
995 PyMem_Free(addrmap);
996 if (codestr != NULL)
997 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000998 Py_INCREF(code);
999 return code;
1000}
1001
Raymond Hettinger2c31a052004-09-22 18:44:21 +00001002/* End: Peephole optimizations ----------------------------------------- */
1003
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001004/*
1005
1006Leave this debugging code for just a little longer.
1007
1008static void
1009compiler_display_symbols(PyObject *name, PyObject *symbols)
1010{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001011PyObject *key, *value;
1012int flags;
1013Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001014
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001015fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1016while (PyDict_Next(symbols, &pos, &key, &value)) {
1017flags = PyInt_AsLong(value);
1018fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1019if (flags & DEF_GLOBAL)
1020fprintf(stderr, " declared_global");
1021if (flags & DEF_LOCAL)
1022fprintf(stderr, " local");
1023if (flags & DEF_PARAM)
1024fprintf(stderr, " param");
1025if (flags & DEF_STAR)
1026fprintf(stderr, " stararg");
1027if (flags & DEF_DOUBLESTAR)
1028fprintf(stderr, " starstar");
1029if (flags & DEF_INTUPLE)
1030fprintf(stderr, " tuple");
1031if (flags & DEF_FREE)
1032fprintf(stderr, " free");
1033if (flags & DEF_FREE_GLOBAL)
1034fprintf(stderr, " global");
1035if (flags & DEF_FREE_CLASS)
1036fprintf(stderr, " free/class");
1037if (flags & DEF_IMPORT)
1038fprintf(stderr, " import");
1039fprintf(stderr, "\n");
1040}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001041 fprintf(stderr, "\n");
1042}
1043*/
1044
1045static void
1046compiler_unit_check(struct compiler_unit *u)
1047{
1048 basicblock *block;
1049 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1050 assert(block != (void *)0xcbcbcbcb);
1051 assert(block != (void *)0xfbfbfbfb);
1052 assert(block != (void *)0xdbdbdbdb);
1053 if (block->b_instr != NULL) {
1054 assert(block->b_ialloc > 0);
1055 assert(block->b_iused > 0);
1056 assert(block->b_ialloc >= block->b_iused);
1057 }
1058 else {
1059 assert (block->b_iused == 0);
1060 assert (block->b_ialloc == 0);
1061 }
1062 }
1063}
1064
1065static void
1066compiler_unit_free(struct compiler_unit *u)
1067{
1068 basicblock *b, *next;
1069
1070 compiler_unit_check(u);
1071 b = u->u_blocks;
1072 while (b != NULL) {
1073 if (b->b_instr)
1074 PyObject_Free((void *)b->b_instr);
1075 next = b->b_list;
1076 PyObject_Free((void *)b);
1077 b = next;
1078 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001079 Py_CLEAR(u->u_ste);
1080 Py_CLEAR(u->u_name);
1081 Py_CLEAR(u->u_consts);
1082 Py_CLEAR(u->u_names);
1083 Py_CLEAR(u->u_varnames);
1084 Py_CLEAR(u->u_freevars);
1085 Py_CLEAR(u->u_cellvars);
1086 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087 PyObject_Free(u);
1088}
1089
1090static int
1091compiler_enter_scope(struct compiler *c, identifier name, void *key,
1092 int lineno)
1093{
1094 struct compiler_unit *u;
1095
Anthony Baxter7b782b62006-04-11 12:01:56 +00001096 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1097 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001098 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001099 PyErr_NoMemory();
1100 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001101 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001102 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 u->u_argcount = 0;
1104 u->u_ste = PySymtable_Lookup(c->c_st, key);
1105 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001106 compiler_unit_free(u);
1107 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108 }
1109 Py_INCREF(name);
1110 u->u_name = name;
1111 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1112 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +00001113 if (!u->u_varnames || !u->u_cellvars) {
1114 compiler_unit_free(u);
1115 return 0;
1116 }
1117
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001119 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +00001120 if (!u->u_freevars) {
1121 compiler_unit_free(u);
1122 return 0;
1123 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
1125 u->u_blocks = NULL;
1126 u->u_tmpname = 0;
1127 u->u_nfblocks = 0;
1128 u->u_firstlineno = lineno;
1129 u->u_lineno = 0;
1130 u->u_lineno_set = false;
1131 u->u_consts = PyDict_New();
1132 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001133 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134 return 0;
1135 }
1136 u->u_names = PyDict_New();
1137 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139 return 0;
1140 }
1141
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001142 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001143
1144 /* Push the old compiler_unit on the stack. */
1145 if (c->u) {
1146 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001147 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
1148 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001149 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 return 0;
1151 }
1152 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 u->u_private = c->u->u_private;
1154 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 }
1156 c->u = u;
1157
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001158 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001159 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160 return 0;
1161
1162 return 1;
1163}
1164
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001165static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166compiler_exit_scope(struct compiler *c)
1167{
1168 int n;
1169 PyObject *wrapper;
1170
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001171 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 compiler_unit_free(c->u);
1173 /* Restore c->u to the parent unit. */
1174 n = PyList_GET_SIZE(c->c_stack) - 1;
1175 if (n >= 0) {
1176 wrapper = PyList_GET_ITEM(c->c_stack, n);
1177 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001178 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001180 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181 compiler_unit_check(c->u);
1182 }
1183 else
1184 c->u = NULL;
1185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001186}
1187
Guido van Rossumc2e20742006-02-27 22:32:47 +00001188/* Allocate a new "anonymous" local variable.
1189 Used by list comprehensions and with statements.
1190*/
1191
1192static PyObject *
1193compiler_new_tmpname(struct compiler *c)
1194{
1195 char tmpname[256];
1196 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1197 return PyString_FromString(tmpname);
1198}
1199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200/* Allocate a new block and return a pointer to it.
1201 Returns NULL on error.
1202*/
1203
1204static basicblock *
1205compiler_new_block(struct compiler *c)
1206{
1207 basicblock *b;
1208 struct compiler_unit *u;
1209
1210 u = c->u;
1211 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001212 if (b == NULL) {
1213 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001214 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001215 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001216 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001217 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218 b->b_list = u->u_blocks;
1219 u->u_blocks = b;
1220 return b;
1221}
1222
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001223static basicblock *
1224compiler_use_new_block(struct compiler *c)
1225{
1226 basicblock *block = compiler_new_block(c);
1227 if (block == NULL)
1228 return NULL;
1229 c->u->u_curblock = block;
1230 return block;
1231}
1232
1233static basicblock *
1234compiler_next_block(struct compiler *c)
1235{
1236 basicblock *block = compiler_new_block(c);
1237 if (block == NULL)
1238 return NULL;
1239 c->u->u_curblock->b_next = block;
1240 c->u->u_curblock = block;
1241 return block;
1242}
1243
1244static basicblock *
1245compiler_use_next_block(struct compiler *c, basicblock *block)
1246{
1247 assert(block != NULL);
1248 c->u->u_curblock->b_next = block;
1249 c->u->u_curblock = block;
1250 return block;
1251}
1252
1253/* Returns the offset of the next instruction in the current block's
1254 b_instr array. Resizes the b_instr as necessary.
1255 Returns -1 on failure.
1256 */
1257
1258static int
1259compiler_next_instr(struct compiler *c, basicblock *b)
1260{
1261 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001262 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001263 b->b_instr = (struct instr *)PyObject_Malloc(
1264 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 if (b->b_instr == NULL) {
1266 PyErr_NoMemory();
1267 return -1;
1268 }
1269 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1270 memset((char *)b->b_instr, 0,
1271 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001272 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001274 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 size_t oldsize, newsize;
1276 oldsize = b->b_ialloc * sizeof(struct instr);
1277 newsize = oldsize << 1;
1278 if (newsize == 0) {
1279 PyErr_NoMemory();
1280 return -1;
1281 }
1282 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001283 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +00001284 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001285 if (tmp == NULL) {
1286 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001288 }
1289 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001290 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1291 }
1292 return b->b_iused++;
1293}
1294
Jeremy Hylton12603c42006-04-01 16:18:02 +00001295/* Set the i_lineno member of the instruction at offse off if the
1296 line number for the current expression/statement (?) has not
1297 already been set. If it has been set, the call has no effect.
1298
1299 Every time a new node is b
1300 */
1301
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001302static void
1303compiler_set_lineno(struct compiler *c, int off)
1304{
1305 basicblock *b;
1306 if (c->u->u_lineno_set)
1307 return;
1308 c->u->u_lineno_set = true;
1309 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001310 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001311}
1312
1313static int
1314opcode_stack_effect(int opcode, int oparg)
1315{
1316 switch (opcode) {
1317 case POP_TOP:
1318 return -1;
1319 case ROT_TWO:
1320 case ROT_THREE:
1321 return 0;
1322 case DUP_TOP:
1323 return 1;
1324 case ROT_FOUR:
1325 return 0;
1326
1327 case UNARY_POSITIVE:
1328 case UNARY_NEGATIVE:
1329 case UNARY_NOT:
1330 case UNARY_CONVERT:
1331 case UNARY_INVERT:
1332 return 0;
1333
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001334 case LIST_APPEND:
1335 return -2;
1336
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001337 case BINARY_POWER:
1338 case BINARY_MULTIPLY:
1339 case BINARY_DIVIDE:
1340 case BINARY_MODULO:
1341 case BINARY_ADD:
1342 case BINARY_SUBTRACT:
1343 case BINARY_SUBSCR:
1344 case BINARY_FLOOR_DIVIDE:
1345 case BINARY_TRUE_DIVIDE:
1346 return -1;
1347 case INPLACE_FLOOR_DIVIDE:
1348 case INPLACE_TRUE_DIVIDE:
1349 return -1;
1350
1351 case SLICE+0:
1352 return 1;
1353 case SLICE+1:
1354 return 0;
1355 case SLICE+2:
1356 return 0;
1357 case SLICE+3:
1358 return -1;
1359
1360 case STORE_SLICE+0:
1361 return -2;
1362 case STORE_SLICE+1:
1363 return -3;
1364 case STORE_SLICE+2:
1365 return -3;
1366 case STORE_SLICE+3:
1367 return -4;
1368
1369 case DELETE_SLICE+0:
1370 return -1;
1371 case DELETE_SLICE+1:
1372 return -2;
1373 case DELETE_SLICE+2:
1374 return -2;
1375 case DELETE_SLICE+3:
1376 return -3;
1377
1378 case INPLACE_ADD:
1379 case INPLACE_SUBTRACT:
1380 case INPLACE_MULTIPLY:
1381 case INPLACE_DIVIDE:
1382 case INPLACE_MODULO:
1383 return -1;
1384 case STORE_SUBSCR:
1385 return -3;
1386 case DELETE_SUBSCR:
1387 return -2;
1388
1389 case BINARY_LSHIFT:
1390 case BINARY_RSHIFT:
1391 case BINARY_AND:
1392 case BINARY_XOR:
1393 case BINARY_OR:
1394 return -1;
1395 case INPLACE_POWER:
1396 return -1;
1397 case GET_ITER:
1398 return 0;
1399
1400 case PRINT_EXPR:
1401 return -1;
1402 case PRINT_ITEM:
1403 return -1;
1404 case PRINT_NEWLINE:
1405 return 0;
1406 case PRINT_ITEM_TO:
1407 return -2;
1408 case PRINT_NEWLINE_TO:
1409 return -1;
1410 case INPLACE_LSHIFT:
1411 case INPLACE_RSHIFT:
1412 case INPLACE_AND:
1413 case INPLACE_XOR:
1414 case INPLACE_OR:
1415 return -1;
1416 case BREAK_LOOP:
1417 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001418 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001419 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001420 case LOAD_LOCALS:
1421 return 1;
1422 case RETURN_VALUE:
1423 return -1;
1424 case IMPORT_STAR:
1425 return -1;
1426 case EXEC_STMT:
1427 return -3;
1428 case YIELD_VALUE:
1429 return 0;
1430
1431 case POP_BLOCK:
1432 return 0;
1433 case END_FINALLY:
1434 return -1; /* or -2 or -3 if exception occurred */
1435 case BUILD_CLASS:
1436 return -2;
1437
1438 case STORE_NAME:
1439 return -1;
1440 case DELETE_NAME:
1441 return 0;
1442 case UNPACK_SEQUENCE:
1443 return oparg-1;
1444 case FOR_ITER:
1445 return 1;
1446
1447 case STORE_ATTR:
1448 return -2;
1449 case DELETE_ATTR:
1450 return -1;
1451 case STORE_GLOBAL:
1452 return -1;
1453 case DELETE_GLOBAL:
1454 return 0;
1455 case DUP_TOPX:
1456 return oparg;
1457 case LOAD_CONST:
1458 return 1;
1459 case LOAD_NAME:
1460 return 1;
1461 case BUILD_TUPLE:
1462 case BUILD_LIST:
1463 return 1-oparg;
1464 case BUILD_MAP:
1465 return 1;
1466 case LOAD_ATTR:
1467 return 0;
1468 case COMPARE_OP:
1469 return -1;
1470 case IMPORT_NAME:
1471 return 0;
1472 case IMPORT_FROM:
1473 return 1;
1474
1475 case JUMP_FORWARD:
1476 case JUMP_IF_FALSE:
1477 case JUMP_IF_TRUE:
1478 case JUMP_ABSOLUTE:
1479 return 0;
1480
1481 case LOAD_GLOBAL:
1482 return 1;
1483
1484 case CONTINUE_LOOP:
1485 return 0;
1486 case SETUP_LOOP:
1487 return 0;
1488 case SETUP_EXCEPT:
1489 case SETUP_FINALLY:
1490 return 3; /* actually pushed by an exception */
1491
1492 case LOAD_FAST:
1493 return 1;
1494 case STORE_FAST:
1495 return -1;
1496 case DELETE_FAST:
1497 return 0;
1498
1499 case RAISE_VARARGS:
1500 return -oparg;
1501#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1502 case CALL_FUNCTION:
1503 return -NARGS(oparg);
1504 case CALL_FUNCTION_VAR:
1505 case CALL_FUNCTION_KW:
1506 return -NARGS(oparg)-1;
1507 case CALL_FUNCTION_VAR_KW:
1508 return -NARGS(oparg)-2;
1509#undef NARGS
1510 case MAKE_FUNCTION:
1511 return -oparg;
1512 case BUILD_SLICE:
1513 if (oparg == 3)
1514 return -2;
1515 else
1516 return -1;
1517
1518 case MAKE_CLOSURE:
1519 return -oparg;
1520 case LOAD_CLOSURE:
1521 return 1;
1522 case LOAD_DEREF:
1523 return 1;
1524 case STORE_DEREF:
1525 return -1;
1526 default:
1527 fprintf(stderr, "opcode = %d\n", opcode);
1528 Py_FatalError("opcode_stack_effect()");
1529
1530 }
1531 return 0; /* not reachable */
1532}
1533
1534/* Add an opcode with no argument.
1535 Returns 0 on failure, 1 on success.
1536*/
1537
1538static int
1539compiler_addop(struct compiler *c, int opcode)
1540{
1541 basicblock *b;
1542 struct instr *i;
1543 int off;
1544 off = compiler_next_instr(c, c->u->u_curblock);
1545 if (off < 0)
1546 return 0;
1547 b = c->u->u_curblock;
1548 i = &b->b_instr[off];
1549 i->i_opcode = opcode;
1550 i->i_hasarg = 0;
1551 if (opcode == RETURN_VALUE)
1552 b->b_return = 1;
1553 compiler_set_lineno(c, off);
1554 return 1;
1555}
1556
1557static int
1558compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1559{
1560 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001561 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001563 /* necessary to make sure types aren't coerced (e.g., int and long) */
1564 t = PyTuple_Pack(2, o, o->ob_type);
1565 if (t == NULL)
1566 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567
1568 v = PyDict_GetItem(dict, t);
1569 if (!v) {
1570 arg = PyDict_Size(dict);
1571 v = PyInt_FromLong(arg);
1572 if (!v) {
1573 Py_DECREF(t);
1574 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576 if (PyDict_SetItem(dict, t, v) < 0) {
1577 Py_DECREF(t);
1578 Py_DECREF(v);
1579 return -1;
1580 }
1581 Py_DECREF(v);
1582 }
1583 else
1584 arg = PyInt_AsLong(v);
1585 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001586 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587}
1588
1589static int
1590compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1591 PyObject *o)
1592{
1593 int arg = compiler_add_o(c, dict, o);
1594 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001595 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596 return compiler_addop_i(c, opcode, arg);
1597}
1598
1599static int
1600compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001601 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001602{
1603 int arg;
1604 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1605 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001606 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001607 arg = compiler_add_o(c, dict, mangled);
1608 Py_DECREF(mangled);
1609 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001610 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 return compiler_addop_i(c, opcode, arg);
1612}
1613
1614/* Add an opcode with an integer argument.
1615 Returns 0 on failure, 1 on success.
1616*/
1617
1618static int
1619compiler_addop_i(struct compiler *c, int opcode, int oparg)
1620{
1621 struct instr *i;
1622 int off;
1623 off = compiler_next_instr(c, c->u->u_curblock);
1624 if (off < 0)
1625 return 0;
1626 i = &c->u->u_curblock->b_instr[off];
1627 i->i_opcode = opcode;
1628 i->i_oparg = oparg;
1629 i->i_hasarg = 1;
1630 compiler_set_lineno(c, off);
1631 return 1;
1632}
1633
1634static int
1635compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1636{
1637 struct instr *i;
1638 int off;
1639
1640 assert(b != NULL);
1641 off = compiler_next_instr(c, c->u->u_curblock);
1642 if (off < 0)
1643 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644 i = &c->u->u_curblock->b_instr[off];
1645 i->i_opcode = opcode;
1646 i->i_target = b;
1647 i->i_hasarg = 1;
1648 if (absolute)
1649 i->i_jabs = 1;
1650 else
1651 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001652 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653 return 1;
1654}
1655
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001656/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1657 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001658 it as the current block. NEXT_BLOCK() also creates an implicit jump
1659 from the current block to the new block.
1660*/
1661
1662/* XXX The returns inside these macros make it impossible to decref
1663 objects created in the local function.
1664*/
1665
1666
1667#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001668 if (compiler_use_new_block((C)) == NULL) \
1669 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001670}
1671
1672#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001673 if (compiler_next_block((C)) == NULL) \
1674 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675}
1676
1677#define ADDOP(C, OP) { \
1678 if (!compiler_addop((C), (OP))) \
1679 return 0; \
1680}
1681
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001682#define ADDOP_IN_SCOPE(C, OP) { \
1683 if (!compiler_addop((C), (OP))) { \
1684 compiler_exit_scope(c); \
1685 return 0; \
1686 } \
1687}
1688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689#define ADDOP_O(C, OP, O, TYPE) { \
1690 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1691 return 0; \
1692}
1693
1694#define ADDOP_NAME(C, OP, O, TYPE) { \
1695 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1696 return 0; \
1697}
1698
1699#define ADDOP_I(C, OP, O) { \
1700 if (!compiler_addop_i((C), (OP), (O))) \
1701 return 0; \
1702}
1703
1704#define ADDOP_JABS(C, OP, O) { \
1705 if (!compiler_addop_j((C), (OP), (O), 1)) \
1706 return 0; \
1707}
1708
1709#define ADDOP_JREL(C, OP, O) { \
1710 if (!compiler_addop_j((C), (OP), (O), 0)) \
1711 return 0; \
1712}
1713
1714/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1715 the ASDL name to synthesize the name of the C type and the visit function.
1716*/
1717
1718#define VISIT(C, TYPE, V) {\
1719 if (!compiler_visit_ ## TYPE((C), (V))) \
1720 return 0; \
1721}
1722
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001723#define VISIT_IN_SCOPE(C, TYPE, V) {\
1724 if (!compiler_visit_ ## TYPE((C), (V))) { \
1725 compiler_exit_scope(c); \
1726 return 0; \
1727 } \
1728}
1729
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730#define VISIT_SLICE(C, V, CTX) {\
1731 if (!compiler_visit_slice((C), (V), (CTX))) \
1732 return 0; \
1733}
1734
1735#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001736 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001738 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001739 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001740 if (!compiler_visit_ ## TYPE((C), elt)) \
1741 return 0; \
1742 } \
1743}
1744
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001745#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001746 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001747 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001748 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001749 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001750 if (!compiler_visit_ ## TYPE((C), elt)) { \
1751 compiler_exit_scope(c); \
1752 return 0; \
1753 } \
1754 } \
1755}
1756
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001757static int
1758compiler_isdocstring(stmt_ty s)
1759{
1760 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001761 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001762 return s->v.Expr.value->kind == Str_kind;
1763}
1764
1765/* Compile a sequence of statements, checking for a docstring. */
1766
1767static int
1768compiler_body(struct compiler *c, asdl_seq *stmts)
1769{
1770 int i = 0;
1771 stmt_ty st;
1772
1773 if (!asdl_seq_LEN(stmts))
1774 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001775 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 if (compiler_isdocstring(st)) {
1777 i = 1;
1778 VISIT(c, expr, st->v.Expr.value);
1779 if (!compiler_nameop(c, __doc__, Store))
1780 return 0;
1781 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001782 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001783 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 return 1;
1785}
1786
1787static PyCodeObject *
1788compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001789{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001790 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001791 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 static PyObject *module;
1793 if (!module) {
1794 module = PyString_FromString("<module>");
1795 if (!module)
1796 return NULL;
1797 }
Neal Norwitzed657552006-07-10 00:04:44 +00001798 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1799 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001800 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801 switch (mod->kind) {
1802 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001803 if (!compiler_body(c, mod->v.Module.body)) {
1804 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001806 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 break;
1808 case Interactive_kind:
1809 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001810 VISIT_SEQ_IN_SCOPE(c, stmt,
1811 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812 break;
1813 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001814 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001815 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816 break;
1817 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001818 PyErr_SetString(PyExc_SystemError,
1819 "suite should not be possible");
1820 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001821 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001822 PyErr_Format(PyExc_SystemError,
1823 "module kind %d should not be possible",
1824 mod->kind);
1825 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001826 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 co = assemble(c, addNone);
1828 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001829 return co;
1830}
1831
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832/* The test for LOCAL must come before the test for FREE in order to
1833 handle classes where name is both local and free. The local var is
1834 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001835*/
1836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837static int
1838get_ref_type(struct compiler *c, PyObject *name)
1839{
1840 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001841 if (scope == 0) {
1842 char buf[350];
1843 PyOS_snprintf(buf, sizeof(buf),
1844 "unknown scope for %.100s in %.100s(%s) in %s\n"
1845 "symbols: %s\nlocals: %s\nglobals: %s\n",
1846 PyString_AS_STRING(name),
1847 PyString_AS_STRING(c->u->u_name),
1848 PyObject_REPR(c->u->u_ste->ste_id),
1849 c->c_filename,
1850 PyObject_REPR(c->u->u_ste->ste_symbols),
1851 PyObject_REPR(c->u->u_varnames),
1852 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001854 Py_FatalError(buf);
1855 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001856
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001857 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858}
1859
1860static int
1861compiler_lookup_arg(PyObject *dict, PyObject *name)
1862{
1863 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001864 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001866 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001868 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001870 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 return PyInt_AS_LONG(v);
1872}
1873
1874static int
1875compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1876{
1877 int i, free = PyCode_GetNumFree(co);
1878 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001879 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1880 ADDOP_I(c, MAKE_FUNCTION, args);
1881 return 1;
1882 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883 for (i = 0; i < free; ++i) {
1884 /* Bypass com_addop_varname because it will generate
1885 LOAD_DEREF but LOAD_CLOSURE is needed.
1886 */
1887 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1888 int arg, reftype;
1889
1890 /* Special case: If a class contains a method with a
1891 free variable that has the same name as a method,
1892 the name will be considered free *and* local in the
1893 class. It should be handled by the closure, as
1894 well as by the normal name loookup logic.
1895 */
1896 reftype = get_ref_type(c, name);
1897 if (reftype == CELL)
1898 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1899 else /* (reftype == FREE) */
1900 arg = compiler_lookup_arg(c->u->u_freevars, name);
1901 if (arg == -1) {
1902 printf("lookup %s in %s %d %d\n"
1903 "freevars of %s: %s\n",
1904 PyObject_REPR(name),
1905 PyString_AS_STRING(c->u->u_name),
1906 reftype, arg,
1907 PyString_AS_STRING(co->co_name),
1908 PyObject_REPR(co->co_freevars));
1909 Py_FatalError("compiler_make_closure()");
1910 }
1911 ADDOP_I(c, LOAD_CLOSURE, arg);
1912 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001913 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001915 ADDOP_I(c, MAKE_CLOSURE, args);
1916 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917}
1918
1919static int
1920compiler_decorators(struct compiler *c, asdl_seq* decos)
1921{
1922 int i;
1923
1924 if (!decos)
1925 return 1;
1926
1927 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001928 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 }
1930 return 1;
1931}
1932
1933static int
1934compiler_arguments(struct compiler *c, arguments_ty args)
1935{
1936 int i;
1937 int n = asdl_seq_LEN(args->args);
1938 /* Correctly handle nested argument lists */
1939 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001940 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001941 if (arg->kind == Tuple_kind) {
1942 PyObject *id = PyString_FromFormat(".%d", i);
1943 if (id == NULL) {
1944 return 0;
1945 }
1946 if (!compiler_nameop(c, id, Load)) {
1947 Py_DECREF(id);
1948 return 0;
1949 }
1950 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001951 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 }
1953 }
1954 return 1;
1955}
1956
1957static int
1958compiler_function(struct compiler *c, stmt_ty s)
1959{
1960 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001961 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 arguments_ty args = s->v.FunctionDef.args;
1963 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001964 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 int i, n, docstring;
1966
1967 assert(s->kind == FunctionDef_kind);
1968
1969 if (!compiler_decorators(c, decos))
1970 return 0;
1971 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001972 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001973 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1974 s->lineno))
1975 return 0;
1976
Anthony Baxter7b782b62006-04-11 12:01:56 +00001977 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001978 docstring = compiler_isdocstring(st);
1979 if (docstring)
1980 first_const = st->v.Expr.value->v.Str.s;
1981 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001982 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001983 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001984 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001986 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 compiler_arguments(c, args);
1988
1989 c->u->u_argcount = asdl_seq_LEN(args->args);
1990 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001991 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00001993 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1994 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995 }
1996 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001997 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998 if (co == NULL)
1999 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002001 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002002 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003
2004 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2005 ADDOP_I(c, CALL_FUNCTION, 1);
2006 }
2007
2008 return compiler_nameop(c, s->v.FunctionDef.name, Store);
2009}
2010
2011static int
2012compiler_class(struct compiler *c, stmt_ty s)
2013{
2014 int n;
2015 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002016 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 /* push class name on stack, needed by BUILD_CLASS */
2018 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2019 /* push the tuple of base classes on the stack */
2020 n = asdl_seq_LEN(s->v.ClassDef.bases);
2021 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002022 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 ADDOP_I(c, BUILD_TUPLE, n);
2024 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2025 s->lineno))
2026 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002027 c->u->u_private = s->v.ClassDef.name;
2028 Py_INCREF(c->u->u_private);
2029 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030 if (!str || !compiler_nameop(c, str, Load)) {
2031 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002032 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002034 }
2035
2036 Py_DECREF(str);
2037 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002038 if (!str || !compiler_nameop(c, str, Store)) {
2039 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002040 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002041 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002042 }
2043 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002044
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002045 if (!compiler_body(c, s->v.ClassDef.body)) {
2046 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002048 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002050 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2051 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002053 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 if (co == NULL)
2055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002057 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002058 Py_DECREF(co);
2059
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 ADDOP_I(c, CALL_FUNCTION, 0);
2061 ADDOP(c, BUILD_CLASS);
2062 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2063 return 0;
2064 return 1;
2065}
2066
2067static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002068compiler_ifexp(struct compiler *c, expr_ty e)
2069{
2070 basicblock *end, *next;
2071
2072 assert(e->kind == IfExp_kind);
2073 end = compiler_new_block(c);
2074 if (end == NULL)
2075 return 0;
2076 next = compiler_new_block(c);
2077 if (next == NULL)
2078 return 0;
2079 VISIT(c, expr, e->v.IfExp.test);
2080 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2081 ADDOP(c, POP_TOP);
2082 VISIT(c, expr, e->v.IfExp.body);
2083 ADDOP_JREL(c, JUMP_FORWARD, end);
2084 compiler_use_next_block(c, next);
2085 ADDOP(c, POP_TOP);
2086 VISIT(c, expr, e->v.IfExp.orelse);
2087 compiler_use_next_block(c, end);
2088 return 1;
2089}
2090
2091static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092compiler_lambda(struct compiler *c, expr_ty e)
2093{
2094 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002095 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002096 arguments_ty args = e->v.Lambda.args;
2097 assert(e->kind == Lambda_kind);
2098
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002099 if (!name) {
2100 name = PyString_InternFromString("<lambda>");
2101 if (!name)
2102 return 0;
2103 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104
2105 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002106 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002107 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2108 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002109
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002110 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 compiler_arguments(c, args);
2112
2113 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002114 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2115 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002117 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118 if (co == NULL)
2119 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002121 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002122 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123
2124 return 1;
2125}
2126
2127static int
2128compiler_print(struct compiler *c, stmt_ty s)
2129{
2130 int i, n;
2131 bool dest;
2132
2133 assert(s->kind == Print_kind);
2134 n = asdl_seq_LEN(s->v.Print.values);
2135 dest = false;
2136 if (s->v.Print.dest) {
2137 VISIT(c, expr, s->v.Print.dest);
2138 dest = true;
2139 }
2140 for (i = 0; i < n; i++) {
2141 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2142 if (dest) {
2143 ADDOP(c, DUP_TOP);
2144 VISIT(c, expr, e);
2145 ADDOP(c, ROT_TWO);
2146 ADDOP(c, PRINT_ITEM_TO);
2147 }
2148 else {
2149 VISIT(c, expr, e);
2150 ADDOP(c, PRINT_ITEM);
2151 }
2152 }
2153 if (s->v.Print.nl) {
2154 if (dest)
2155 ADDOP(c, PRINT_NEWLINE_TO)
2156 else
2157 ADDOP(c, PRINT_NEWLINE)
2158 }
2159 else if (dest)
2160 ADDOP(c, POP_TOP);
2161 return 1;
2162}
2163
2164static int
2165compiler_if(struct compiler *c, stmt_ty s)
2166{
2167 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00002168 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002169 assert(s->kind == If_kind);
2170 end = compiler_new_block(c);
2171 if (end == NULL)
2172 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002173 next = compiler_new_block(c);
2174 if (next == NULL)
2175 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00002176
2177 constant = expr_constant(s->v.If.test);
2178 /* constant = 0: "if 0"
2179 * constant = 1: "if 1", "if 2", ...
2180 * constant = -1: rest */
2181 if (constant == 0) {
2182 if (s->v.If.orelse)
2183 VISIT_SEQ(c, stmt, s->v.If.orelse);
2184 } else if (constant == 1) {
2185 VISIT_SEQ(c, stmt, s->v.If.body);
2186 } else {
2187 VISIT(c, expr, s->v.If.test);
2188 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2189 ADDOP(c, POP_TOP);
2190 VISIT_SEQ(c, stmt, s->v.If.body);
2191 ADDOP_JREL(c, JUMP_FORWARD, end);
2192 compiler_use_next_block(c, next);
2193 ADDOP(c, POP_TOP);
2194 if (s->v.If.orelse)
2195 VISIT_SEQ(c, stmt, s->v.If.orelse);
2196 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002197 compiler_use_next_block(c, end);
2198 return 1;
2199}
2200
2201static int
2202compiler_for(struct compiler *c, stmt_ty s)
2203{
2204 basicblock *start, *cleanup, *end;
2205
2206 start = compiler_new_block(c);
2207 cleanup = compiler_new_block(c);
2208 end = compiler_new_block(c);
2209 if (start == NULL || end == NULL || cleanup == NULL)
2210 return 0;
2211 ADDOP_JREL(c, SETUP_LOOP, end);
2212 if (!compiler_push_fblock(c, LOOP, start))
2213 return 0;
2214 VISIT(c, expr, s->v.For.iter);
2215 ADDOP(c, GET_ITER);
2216 compiler_use_next_block(c, start);
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002217 /* XXX(nnorwitz): is there a better way to handle this?
2218 for loops are special, we want to be able to trace them
2219 each time around, so we need to set an extra line number. */
2220 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221 ADDOP_JREL(c, FOR_ITER, cleanup);
2222 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002223 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002224 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2225 compiler_use_next_block(c, cleanup);
2226 ADDOP(c, POP_BLOCK);
2227 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002228 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229 compiler_use_next_block(c, end);
2230 return 1;
2231}
2232
2233static int
2234compiler_while(struct compiler *c, stmt_ty s)
2235{
2236 basicblock *loop, *orelse, *end, *anchor = NULL;
2237 int constant = expr_constant(s->v.While.test);
2238
2239 if (constant == 0)
2240 return 1;
2241 loop = compiler_new_block(c);
2242 end = compiler_new_block(c);
2243 if (constant == -1) {
2244 anchor = compiler_new_block(c);
2245 if (anchor == NULL)
2246 return 0;
2247 }
2248 if (loop == NULL || end == NULL)
2249 return 0;
2250 if (s->v.While.orelse) {
2251 orelse = compiler_new_block(c);
2252 if (orelse == NULL)
2253 return 0;
2254 }
2255 else
2256 orelse = NULL;
2257
2258 ADDOP_JREL(c, SETUP_LOOP, end);
2259 compiler_use_next_block(c, loop);
2260 if (!compiler_push_fblock(c, LOOP, loop))
2261 return 0;
2262 if (constant == -1) {
2263 VISIT(c, expr, s->v.While.test);
2264 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2265 ADDOP(c, POP_TOP);
2266 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002267 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2269
2270 /* XXX should the two POP instructions be in a separate block
2271 if there is no else clause ?
2272 */
2273
2274 if (constant == -1) {
2275 compiler_use_next_block(c, anchor);
2276 ADDOP(c, POP_TOP);
2277 ADDOP(c, POP_BLOCK);
2278 }
2279 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002280 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002281 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282 compiler_use_next_block(c, end);
2283
2284 return 1;
2285}
2286
2287static int
2288compiler_continue(struct compiler *c)
2289{
2290 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Georg Brandl74284b92006-10-08 07:06:29 +00002291 static const char IN_FINALLY_ERROR_MSG[] =
2292 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 int i;
2294
2295 if (!c->u->u_nfblocks)
2296 return compiler_error(c, LOOP_ERROR_MSG);
2297 i = c->u->u_nfblocks - 1;
2298 switch (c->u->u_fblock[i].fb_type) {
2299 case LOOP:
2300 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2301 break;
2302 case EXCEPT:
2303 case FINALLY_TRY:
Georg Brandl74284b92006-10-08 07:06:29 +00002304 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2305 /* Prevent try: ... finally:
2306 try: continue ... or
2307 try: ... except: continue */
2308 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2309 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2310 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 if (i == -1)
2312 return compiler_error(c, LOOP_ERROR_MSG);
2313 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2314 break;
2315 case FINALLY_END:
Georg Brandl74284b92006-10-08 07:06:29 +00002316 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002317 }
2318
2319 return 1;
2320}
2321
2322/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2323
2324 SETUP_FINALLY L
2325 <code for body>
2326 POP_BLOCK
2327 LOAD_CONST <None>
2328 L: <code for finalbody>
2329 END_FINALLY
2330
2331 The special instructions use the block stack. Each block
2332 stack entry contains the instruction that created it (here
2333 SETUP_FINALLY), the level of the value stack at the time the
2334 block stack entry was created, and a label (here L).
2335
2336 SETUP_FINALLY:
2337 Pushes the current value stack level and the label
2338 onto the block stack.
2339 POP_BLOCK:
2340 Pops en entry from the block stack, and pops the value
2341 stack until its level is the same as indicated on the
2342 block stack. (The label is ignored.)
2343 END_FINALLY:
2344 Pops a variable number of entries from the *value* stack
2345 and re-raises the exception they specify. The number of
2346 entries popped depends on the (pseudo) exception type.
2347
2348 The block stack is unwound when an exception is raised:
2349 when a SETUP_FINALLY entry is found, the exception is pushed
2350 onto the value stack (and the exception condition is cleared),
2351 and the interpreter jumps to the label gotten from the block
2352 stack.
2353*/
2354
2355static int
2356compiler_try_finally(struct compiler *c, stmt_ty s)
2357{
2358 basicblock *body, *end;
2359 body = compiler_new_block(c);
2360 end = compiler_new_block(c);
2361 if (body == NULL || end == NULL)
2362 return 0;
2363
2364 ADDOP_JREL(c, SETUP_FINALLY, end);
2365 compiler_use_next_block(c, body);
2366 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2367 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002368 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369 ADDOP(c, POP_BLOCK);
2370 compiler_pop_fblock(c, FINALLY_TRY, body);
2371
2372 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2373 compiler_use_next_block(c, end);
2374 if (!compiler_push_fblock(c, FINALLY_END, end))
2375 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002376 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377 ADDOP(c, END_FINALLY);
2378 compiler_pop_fblock(c, FINALLY_END, end);
2379
2380 return 1;
2381}
2382
2383/*
2384 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2385 (The contents of the value stack is shown in [], with the top
2386 at the right; 'tb' is trace-back info, 'val' the exception's
2387 associated value, and 'exc' the exception.)
2388
2389 Value stack Label Instruction Argument
2390 [] SETUP_EXCEPT L1
2391 [] <code for S>
2392 [] POP_BLOCK
2393 [] JUMP_FORWARD L0
2394
2395 [tb, val, exc] L1: DUP )
2396 [tb, val, exc, exc] <evaluate E1> )
2397 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2398 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2399 [tb, val, exc, 1] POP )
2400 [tb, val, exc] POP
2401 [tb, val] <assign to V1> (or POP if no V1)
2402 [tb] POP
2403 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002404 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405
2406 [tb, val, exc, 0] L2: POP
2407 [tb, val, exc] DUP
2408 .............................etc.......................
2409
2410 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002411 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412
2413 [] L0: <next statement>
2414
2415 Of course, parts are not generated if Vi or Ei is not present.
2416*/
2417static int
2418compiler_try_except(struct compiler *c, stmt_ty s)
2419{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002420 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002421 int i, n;
2422
2423 body = compiler_new_block(c);
2424 except = compiler_new_block(c);
2425 orelse = compiler_new_block(c);
2426 end = compiler_new_block(c);
2427 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2428 return 0;
2429 ADDOP_JREL(c, SETUP_EXCEPT, except);
2430 compiler_use_next_block(c, body);
2431 if (!compiler_push_fblock(c, EXCEPT, body))
2432 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002433 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434 ADDOP(c, POP_BLOCK);
2435 compiler_pop_fblock(c, EXCEPT, body);
2436 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2437 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2438 compiler_use_next_block(c, except);
2439 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002440 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 s->v.TryExcept.handlers, i);
2442 if (!handler->type && i < n-1)
2443 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00002444 c->u->u_lineno_set = false;
2445 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 except = compiler_new_block(c);
2447 if (except == NULL)
2448 return 0;
2449 if (handler->type) {
2450 ADDOP(c, DUP_TOP);
2451 VISIT(c, expr, handler->type);
2452 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2453 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2454 ADDOP(c, POP_TOP);
2455 }
2456 ADDOP(c, POP_TOP);
2457 if (handler->name) {
2458 VISIT(c, expr, handler->name);
2459 }
2460 else {
2461 ADDOP(c, POP_TOP);
2462 }
2463 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002464 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465 ADDOP_JREL(c, JUMP_FORWARD, end);
2466 compiler_use_next_block(c, except);
2467 if (handler->type)
2468 ADDOP(c, POP_TOP);
2469 }
2470 ADDOP(c, END_FINALLY);
2471 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002472 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002473 compiler_use_next_block(c, end);
2474 return 1;
2475}
2476
2477static int
2478compiler_import_as(struct compiler *c, identifier name, identifier asname)
2479{
2480 /* The IMPORT_NAME opcode was already generated. This function
2481 merely needs to bind the result to a name.
2482
2483 If there is a dot in name, we need to split it and emit a
2484 LOAD_ATTR for each name.
2485 */
2486 const char *src = PyString_AS_STRING(name);
2487 const char *dot = strchr(src, '.');
2488 if (dot) {
2489 /* Consume the base module name to get the first attribute */
2490 src = dot + 1;
2491 while (dot) {
2492 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002493 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002494 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002495 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002497 if (!attr)
2498 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002499 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002500 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 src = dot + 1;
2502 }
2503 }
2504 return compiler_nameop(c, asname, Store);
2505}
2506
2507static int
2508compiler_import(struct compiler *c, stmt_ty s)
2509{
2510 /* The Import node stores a module name like a.b.c as a single
2511 string. This is convenient for all cases except
2512 import a.b.c as d
2513 where we need to parse that string to extract the individual
2514 module names.
2515 XXX Perhaps change the representation to make this case simpler?
2516 */
2517 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002519 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002520 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002522 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002523
Neal Norwitzcbce2802006-04-03 06:26:32 +00002524 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002525 level = PyInt_FromLong(0);
2526 else
2527 level = PyInt_FromLong(-1);
2528
2529 if (level == NULL)
2530 return 0;
2531
2532 ADDOP_O(c, LOAD_CONST, level, consts);
2533 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2535 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2536
2537 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002538 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 if (!r)
2540 return r;
2541 }
2542 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 identifier tmp = alias->name;
2544 const char *base = PyString_AS_STRING(alias->name);
2545 char *dot = strchr(base, '.');
2546 if (dot)
2547 tmp = PyString_FromStringAndSize(base,
2548 dot - base);
2549 r = compiler_nameop(c, tmp, Store);
2550 if (dot) {
2551 Py_DECREF(tmp);
2552 }
2553 if (!r)
2554 return r;
2555 }
2556 }
2557 return 1;
2558}
2559
2560static int
2561compiler_from_import(struct compiler *c, stmt_ty s)
2562{
2563 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564
2565 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002566 PyObject *level;
2567
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 if (!names)
2569 return 0;
2570
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002571 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002572 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002573 level = PyInt_FromLong(-1);
2574 else
2575 level = PyInt_FromLong(s->v.ImportFrom.level);
2576
2577 if (!level) {
2578 Py_DECREF(names);
2579 return 0;
2580 }
2581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002582 /* build up the names */
2583 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002584 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002585 Py_INCREF(alias->name);
2586 PyTuple_SET_ITEM(names, i, alias->name);
2587 }
2588
2589 if (s->lineno > c->c_future->ff_lineno) {
2590 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2591 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002592 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002593 Py_DECREF(names);
2594 return compiler_error(c,
2595 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002596 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597
2598 }
2599 }
2600
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002601 ADDOP_O(c, LOAD_CONST, level, consts);
2602 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002604 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002605 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2606 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002607 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002608 identifier store_name;
2609
2610 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2611 assert(n == 1);
2612 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002613 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 }
2615
2616 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2617 store_name = alias->name;
2618 if (alias->asname)
2619 store_name = alias->asname;
2620
2621 if (!compiler_nameop(c, store_name, Store)) {
2622 Py_DECREF(names);
2623 return 0;
2624 }
2625 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002626 /* remove imported module */
2627 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 return 1;
2629}
2630
2631static int
2632compiler_assert(struct compiler *c, stmt_ty s)
2633{
2634 static PyObject *assertion_error = NULL;
2635 basicblock *end;
2636
2637 if (Py_OptimizeFlag)
2638 return 1;
2639 if (assertion_error == NULL) {
2640 assertion_error = PyString_FromString("AssertionError");
2641 if (assertion_error == NULL)
2642 return 0;
2643 }
2644 VISIT(c, expr, s->v.Assert.test);
2645 end = compiler_new_block(c);
2646 if (end == NULL)
2647 return 0;
2648 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2649 ADDOP(c, POP_TOP);
2650 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2651 if (s->v.Assert.msg) {
2652 VISIT(c, expr, s->v.Assert.msg);
2653 ADDOP_I(c, RAISE_VARARGS, 2);
2654 }
2655 else {
2656 ADDOP_I(c, RAISE_VARARGS, 1);
2657 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002658 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659 ADDOP(c, POP_TOP);
2660 return 1;
2661}
2662
2663static int
2664compiler_visit_stmt(struct compiler *c, stmt_ty s)
2665{
2666 int i, n;
2667
Jeremy Hylton12603c42006-04-01 16:18:02 +00002668 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669 c->u->u_lineno = s->lineno;
2670 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002671
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 if (c->u->u_ste->ste_type != FunctionBlock)
2679 return compiler_error(c, "'return' outside function");
2680 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 VISIT(c, expr, s->v.Return.value);
2682 }
2683 else
2684 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2685 ADDOP(c, RETURN_VALUE);
2686 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002688 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002690 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691 n = asdl_seq_LEN(s->v.Assign.targets);
2692 VISIT(c, expr, s->v.Assign.value);
2693 for (i = 0; i < n; i++) {
2694 if (i < n - 1)
2695 ADDOP(c, DUP_TOP);
2696 VISIT(c, expr,
2697 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2698 }
2699 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002702 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 n = 0;
2712 if (s->v.Raise.type) {
2713 VISIT(c, expr, s->v.Raise.type);
2714 n++;
2715 if (s->v.Raise.inst) {
2716 VISIT(c, expr, s->v.Raise.inst);
2717 n++;
2718 if (s->v.Raise.tback) {
2719 VISIT(c, expr, s->v.Raise.tback);
2720 n++;
2721 }
2722 }
2723 }
2724 ADDOP_I(c, RAISE_VARARGS, n);
2725 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002726 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002727 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002728 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002729 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002732 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002734 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002736 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 VISIT(c, expr, s->v.Exec.body);
2738 if (s->v.Exec.globals) {
2739 VISIT(c, expr, s->v.Exec.globals);
2740 if (s->v.Exec.locals) {
2741 VISIT(c, expr, s->v.Exec.locals);
2742 } else {
2743 ADDOP(c, DUP_TOP);
2744 }
2745 } else {
2746 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2747 ADDOP(c, DUP_TOP);
2748 }
2749 ADDOP(c, EXEC_STMT);
2750 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002751 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002753 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002755 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 ADDOP(c, PRINT_EXPR);
2757 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002758 else if (s->v.Expr.value->kind != Str_kind &&
2759 s->v.Expr.value->kind != Num_kind) {
2760 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 ADDOP(c, POP_TOP);
2762 }
2763 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002764 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002765 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002766 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767 if (!c->u->u_nfblocks)
2768 return compiler_error(c, "'break' outside loop");
2769 ADDOP(c, BREAK_LOOP);
2770 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002771 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002773 case With_kind:
2774 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002775 }
2776 return 1;
2777}
2778
2779static int
2780unaryop(unaryop_ty op)
2781{
2782 switch (op) {
2783 case Invert:
2784 return UNARY_INVERT;
2785 case Not:
2786 return UNARY_NOT;
2787 case UAdd:
2788 return UNARY_POSITIVE;
2789 case USub:
2790 return UNARY_NEGATIVE;
2791 }
2792 return 0;
2793}
2794
2795static int
2796binop(struct compiler *c, operator_ty op)
2797{
2798 switch (op) {
2799 case Add:
2800 return BINARY_ADD;
2801 case Sub:
2802 return BINARY_SUBTRACT;
2803 case Mult:
2804 return BINARY_MULTIPLY;
2805 case Div:
2806 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2807 return BINARY_TRUE_DIVIDE;
2808 else
2809 return BINARY_DIVIDE;
2810 case Mod:
2811 return BINARY_MODULO;
2812 case Pow:
2813 return BINARY_POWER;
2814 case LShift:
2815 return BINARY_LSHIFT;
2816 case RShift:
2817 return BINARY_RSHIFT;
2818 case BitOr:
2819 return BINARY_OR;
2820 case BitXor:
2821 return BINARY_XOR;
2822 case BitAnd:
2823 return BINARY_AND;
2824 case FloorDiv:
2825 return BINARY_FLOOR_DIVIDE;
2826 }
2827 return 0;
2828}
2829
2830static int
2831cmpop(cmpop_ty op)
2832{
2833 switch (op) {
2834 case Eq:
2835 return PyCmp_EQ;
2836 case NotEq:
2837 return PyCmp_NE;
2838 case Lt:
2839 return PyCmp_LT;
2840 case LtE:
2841 return PyCmp_LE;
2842 case Gt:
2843 return PyCmp_GT;
2844 case GtE:
2845 return PyCmp_GE;
2846 case Is:
2847 return PyCmp_IS;
2848 case IsNot:
2849 return PyCmp_IS_NOT;
2850 case In:
2851 return PyCmp_IN;
2852 case NotIn:
2853 return PyCmp_NOT_IN;
2854 }
2855 return PyCmp_BAD;
2856}
2857
2858static int
2859inplace_binop(struct compiler *c, operator_ty op)
2860{
2861 switch (op) {
2862 case Add:
2863 return INPLACE_ADD;
2864 case Sub:
2865 return INPLACE_SUBTRACT;
2866 case Mult:
2867 return INPLACE_MULTIPLY;
2868 case Div:
2869 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2870 return INPLACE_TRUE_DIVIDE;
2871 else
2872 return INPLACE_DIVIDE;
2873 case Mod:
2874 return INPLACE_MODULO;
2875 case Pow:
2876 return INPLACE_POWER;
2877 case LShift:
2878 return INPLACE_LSHIFT;
2879 case RShift:
2880 return INPLACE_RSHIFT;
2881 case BitOr:
2882 return INPLACE_OR;
2883 case BitXor:
2884 return INPLACE_XOR;
2885 case BitAnd:
2886 return INPLACE_AND;
2887 case FloorDiv:
2888 return INPLACE_FLOOR_DIVIDE;
2889 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002890 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002891 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892 return 0;
2893}
2894
2895static int
2896compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2897{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002898 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2900
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002901 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002902 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 /* XXX AugStore isn't used anywhere! */
2904
2905 /* First check for assignment to __debug__. Param? */
2906 if ((ctx == Store || ctx == AugStore || ctx == Del)
2907 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2908 return compiler_error(c, "can not assign to __debug__");
2909 }
2910
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002911 mangled = _Py_Mangle(c->u->u_private, name);
2912 if (!mangled)
2913 return 0;
2914
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915 op = 0;
2916 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002917 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002918 switch (scope) {
2919 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002920 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 optype = OP_DEREF;
2922 break;
2923 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002924 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 optype = OP_DEREF;
2926 break;
2927 case LOCAL:
2928 if (c->u->u_ste->ste_type == FunctionBlock)
2929 optype = OP_FAST;
2930 break;
2931 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002932 if (c->u->u_ste->ste_type == FunctionBlock &&
2933 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 optype = OP_GLOBAL;
2935 break;
2936 case GLOBAL_EXPLICIT:
2937 optype = OP_GLOBAL;
2938 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002939 default:
2940 /* scope can be 0 */
2941 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 }
2943
2944 /* XXX Leave assert here, but handle __doc__ and the like better */
2945 assert(scope || PyString_AS_STRING(name)[0] == '_');
2946
2947 switch (optype) {
2948 case OP_DEREF:
2949 switch (ctx) {
2950 case Load: op = LOAD_DEREF; break;
2951 case Store: op = STORE_DEREF; break;
2952 case AugLoad:
2953 case AugStore:
2954 break;
2955 case Del:
2956 PyErr_Format(PyExc_SyntaxError,
2957 "can not delete variable '%s' referenced "
2958 "in nested scope",
2959 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002960 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002963 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002964 PyErr_SetString(PyExc_SystemError,
2965 "param invalid for deref variable");
2966 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 }
2968 break;
2969 case OP_FAST:
2970 switch (ctx) {
2971 case Load: op = LOAD_FAST; break;
2972 case Store: op = STORE_FAST; break;
2973 case Del: op = DELETE_FAST; break;
2974 case AugLoad:
2975 case AugStore:
2976 break;
2977 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002978 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002979 PyErr_SetString(PyExc_SystemError,
2980 "param invalid for local variable");
2981 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002983 ADDOP_O(c, op, mangled, varnames);
2984 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 return 1;
2986 case OP_GLOBAL:
2987 switch (ctx) {
2988 case Load: op = LOAD_GLOBAL; break;
2989 case Store: op = STORE_GLOBAL; break;
2990 case Del: op = DELETE_GLOBAL; break;
2991 case AugLoad:
2992 case AugStore:
2993 break;
2994 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002995 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002996 PyErr_SetString(PyExc_SystemError,
2997 "param invalid for global variable");
2998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 }
3000 break;
3001 case OP_NAME:
3002 switch (ctx) {
3003 case Load: op = LOAD_NAME; break;
3004 case Store: op = STORE_NAME; break;
3005 case Del: op = DELETE_NAME; break;
3006 case AugLoad:
3007 case AugStore:
3008 break;
3009 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003010 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003011 PyErr_SetString(PyExc_SystemError,
3012 "param invalid for name variable");
3013 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003014 }
3015 break;
3016 }
3017
3018 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003019 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00003020 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003021 if (arg < 0)
3022 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00003023 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024}
3025
3026static int
3027compiler_boolop(struct compiler *c, expr_ty e)
3028{
3029 basicblock *end;
3030 int jumpi, i, n;
3031 asdl_seq *s;
3032
3033 assert(e->kind == BoolOp_kind);
3034 if (e->v.BoolOp.op == And)
3035 jumpi = JUMP_IF_FALSE;
3036 else
3037 jumpi = JUMP_IF_TRUE;
3038 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003039 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 return 0;
3041 s = e->v.BoolOp.values;
3042 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00003043 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003045 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003046 ADDOP_JREL(c, jumpi, end);
3047 ADDOP(c, POP_TOP)
3048 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003049 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 compiler_use_next_block(c, end);
3051 return 1;
3052}
3053
3054static int
3055compiler_list(struct compiler *c, expr_ty e)
3056{
3057 int n = asdl_seq_LEN(e->v.List.elts);
3058 if (e->v.List.ctx == Store) {
3059 ADDOP_I(c, UNPACK_SEQUENCE, n);
3060 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003061 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 if (e->v.List.ctx == Load) {
3063 ADDOP_I(c, BUILD_LIST, n);
3064 }
3065 return 1;
3066}
3067
3068static int
3069compiler_tuple(struct compiler *c, expr_ty e)
3070{
3071 int n = asdl_seq_LEN(e->v.Tuple.elts);
3072 if (e->v.Tuple.ctx == Store) {
3073 ADDOP_I(c, UNPACK_SEQUENCE, n);
3074 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003075 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 if (e->v.Tuple.ctx == Load) {
3077 ADDOP_I(c, BUILD_TUPLE, n);
3078 }
3079 return 1;
3080}
3081
3082static int
3083compiler_compare(struct compiler *c, expr_ty e)
3084{
3085 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003086 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087
3088 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3089 VISIT(c, expr, e->v.Compare.left);
3090 n = asdl_seq_LEN(e->v.Compare.ops);
3091 assert(n > 0);
3092 if (n > 1) {
3093 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 if (cleanup == NULL)
3095 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003096 VISIT(c, expr,
3097 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003098 }
3099 for (i = 1; i < n; i++) {
3100 ADDOP(c, DUP_TOP);
3101 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003102 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003103 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003104 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3106 NEXT_BLOCK(c);
3107 ADDOP(c, POP_TOP);
3108 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003109 VISIT(c, expr,
3110 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003111 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003112 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003113 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003114 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115 if (n > 1) {
3116 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003117 if (end == NULL)
3118 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119 ADDOP_JREL(c, JUMP_FORWARD, end);
3120 compiler_use_next_block(c, cleanup);
3121 ADDOP(c, ROT_TWO);
3122 ADDOP(c, POP_TOP);
3123 compiler_use_next_block(c, end);
3124 }
3125 return 1;
3126}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003127#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128
3129static int
3130compiler_call(struct compiler *c, expr_ty e)
3131{
3132 int n, code = 0;
3133
3134 VISIT(c, expr, e->v.Call.func);
3135 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003136 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003138 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3140 }
3141 if (e->v.Call.starargs) {
3142 VISIT(c, expr, e->v.Call.starargs);
3143 code |= 1;
3144 }
3145 if (e->v.Call.kwargs) {
3146 VISIT(c, expr, e->v.Call.kwargs);
3147 code |= 2;
3148 }
3149 switch (code) {
3150 case 0:
3151 ADDOP_I(c, CALL_FUNCTION, n);
3152 break;
3153 case 1:
3154 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3155 break;
3156 case 2:
3157 ADDOP_I(c, CALL_FUNCTION_KW, n);
3158 break;
3159 case 3:
3160 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3161 break;
3162 }
3163 return 1;
3164}
3165
3166static int
3167compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003168 asdl_seq *generators, int gen_index,
3169 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170{
3171 /* generate code for the iterator, then each of the ifs,
3172 and then write to the element */
3173
3174 comprehension_ty l;
3175 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177
3178 start = compiler_new_block(c);
3179 skip = compiler_new_block(c);
3180 if_cleanup = compiler_new_block(c);
3181 anchor = compiler_new_block(c);
3182
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003183 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3184 anchor == NULL)
3185 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003186
Anthony Baxter7b782b62006-04-11 12:01:56 +00003187 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 VISIT(c, expr, l->iter);
3189 ADDOP(c, GET_ITER);
3190 compiler_use_next_block(c, start);
3191 ADDOP_JREL(c, FOR_ITER, anchor);
3192 NEXT_BLOCK(c);
3193 VISIT(c, expr, l->target);
3194
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 n = asdl_seq_LEN(l->ifs);
3197 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003198 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 VISIT(c, expr, e);
3200 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3201 NEXT_BLOCK(c);
3202 ADDOP(c, POP_TOP);
3203 }
3204
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 if (++gen_index < asdl_seq_LEN(generators))
3206 if (!compiler_listcomp_generator(c, tmpname,
3207 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003209
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 /* only append after the last for generator */
3211 if (gen_index >= asdl_seq_LEN(generators)) {
3212 if (!compiler_nameop(c, tmpname, Load))
3213 return 0;
3214 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003215 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003216
3217 compiler_use_next_block(c, skip);
3218 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 for (i = 0; i < n; i++) {
3220 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 if (i == 0)
3222 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 ADDOP(c, POP_TOP);
3224 }
3225 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3226 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003229 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 return 0;
3231
3232 return 1;
3233}
3234
3235static int
3236compiler_listcomp(struct compiler *c, expr_ty e)
3237{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003239 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240 static identifier append;
3241 asdl_seq *generators = e->v.ListComp.generators;
3242
3243 assert(e->kind == ListComp_kind);
3244 if (!append) {
3245 append = PyString_InternFromString("append");
3246 if (!append)
3247 return 0;
3248 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003249 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250 if (!tmp)
3251 return 0;
3252 ADDOP_I(c, BUILD_LIST, 0);
3253 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003255 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3256 e->v.ListComp.elt);
3257 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 return rc;
3259}
3260
3261static int
3262compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 asdl_seq *generators, int gen_index,
3264 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265{
3266 /* generate code for the iterator, then each of the ifs,
3267 and then write to the element */
3268
3269 comprehension_ty ge;
3270 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003271 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272
3273 start = compiler_new_block(c);
3274 skip = compiler_new_block(c);
3275 if_cleanup = compiler_new_block(c);
3276 anchor = compiler_new_block(c);
3277 end = compiler_new_block(c);
3278
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003279 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 anchor == NULL || end == NULL)
3281 return 0;
3282
Anthony Baxter7b782b62006-04-11 12:01:56 +00003283 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 ADDOP_JREL(c, SETUP_LOOP, end);
3285 if (!compiler_push_fblock(c, LOOP, start))
3286 return 0;
3287
3288 if (gen_index == 0) {
3289 /* Receive outermost iter as an implicit argument */
3290 c->u->u_argcount = 1;
3291 ADDOP_I(c, LOAD_FAST, 0);
3292 }
3293 else {
3294 /* Sub-iter - calculate on the fly */
3295 VISIT(c, expr, ge->iter);
3296 ADDOP(c, GET_ITER);
3297 }
3298 compiler_use_next_block(c, start);
3299 ADDOP_JREL(c, FOR_ITER, anchor);
3300 NEXT_BLOCK(c);
3301 VISIT(c, expr, ge->target);
3302
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003303 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 n = asdl_seq_LEN(ge->ifs);
3305 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003306 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 VISIT(c, expr, e);
3308 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3309 NEXT_BLOCK(c);
3310 ADDOP(c, POP_TOP);
3311 }
3312
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003313 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3315 return 0;
3316
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003317 /* only append after the last 'for' generator */
3318 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319 VISIT(c, expr, elt);
3320 ADDOP(c, YIELD_VALUE);
3321 ADDOP(c, POP_TOP);
3322
3323 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003324 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 for (i = 0; i < n; i++) {
3326 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003327 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328 compiler_use_next_block(c, if_cleanup);
3329
3330 ADDOP(c, POP_TOP);
3331 }
3332 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3333 compiler_use_next_block(c, anchor);
3334 ADDOP(c, POP_BLOCK);
3335 compiler_pop_fblock(c, LOOP, start);
3336 compiler_use_next_block(c, end);
3337
3338 return 1;
3339}
3340
3341static int
3342compiler_genexp(struct compiler *c, expr_ty e)
3343{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003344 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003345 PyCodeObject *co;
3346 expr_ty outermost_iter = ((comprehension_ty)
3347 (asdl_seq_GET(e->v.GeneratorExp.generators,
3348 0)))->iter;
3349
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003350 if (!name) {
3351 name = PyString_FromString("<genexpr>");
3352 if (!name)
3353 return 0;
3354 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
3356 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3357 return 0;
3358 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3359 e->v.GeneratorExp.elt);
3360 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003361 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362 if (co == NULL)
3363 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003365 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003366 Py_DECREF(co);
3367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368 VISIT(c, expr, outermost_iter);
3369 ADDOP(c, GET_ITER);
3370 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371
3372 return 1;
3373}
3374
3375static int
3376compiler_visit_keyword(struct compiler *c, keyword_ty k)
3377{
3378 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3379 VISIT(c, expr, k->value);
3380 return 1;
3381}
3382
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003383/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 whether they are true or false.
3385
3386 Return values: 1 for true, 0 for false, -1 for non-constant.
3387 */
3388
3389static int
3390expr_constant(expr_ty e)
3391{
3392 switch (e->kind) {
3393 case Num_kind:
3394 return PyObject_IsTrue(e->v.Num.n);
3395 case Str_kind:
3396 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003397 case Name_kind:
3398 /* __debug__ is not assignable, so we can optimize
3399 * it away in if and while statements */
3400 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3401 "__debug__") == 0)
3402 return ! Py_OptimizeFlag;
3403 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003404 default:
3405 return -1;
3406 }
3407}
3408
Guido van Rossumc2e20742006-02-27 22:32:47 +00003409/*
3410 Implements the with statement from PEP 343.
3411
3412 The semantics outlined in that PEP are as follows:
3413
3414 with EXPR as VAR:
3415 BLOCK
3416
3417 It is implemented roughly as:
3418
Guido van Rossumda5b7012006-05-02 19:47:52 +00003419 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003420 exit = context.__exit__ # not calling it
3421 value = context.__enter__()
3422 try:
3423 VAR = value # if VAR present in the syntax
3424 BLOCK
3425 finally:
3426 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003427 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003428 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003429 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003430 exit(*exc)
3431 */
3432static int
3433compiler_with(struct compiler *c, stmt_ty s)
3434{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003435 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003436 basicblock *block, *finally;
3437 identifier tmpexit, tmpvalue = NULL;
3438
3439 assert(s->kind == With_kind);
3440
Guido van Rossumc2e20742006-02-27 22:32:47 +00003441 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003442 enter_attr = PyString_InternFromString("__enter__");
3443 if (!enter_attr)
3444 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003445 }
3446 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 exit_attr = PyString_InternFromString("__exit__");
3448 if (!exit_attr)
3449 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003450 }
3451
3452 block = compiler_new_block(c);
3453 finally = compiler_new_block(c);
3454 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003456
3457 /* Create a temporary variable to hold context.__exit__ */
3458 tmpexit = compiler_new_tmpname(c);
3459 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003460 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003461 PyArena_AddPyObject(c->c_arena, tmpexit);
3462
3463 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003464 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003465 We need to do this rather than preserving it on the stack
3466 because SETUP_FINALLY remembers the stack level.
3467 We need to do the assignment *inside* the try/finally
3468 so that context.__exit__() is called when the assignment
3469 fails. But we need to call context.__enter__() *before*
3470 the try/finally so that if it fails we won't call
3471 context.__exit__().
3472 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003474 if (tmpvalue == NULL)
3475 return 0;
3476 PyArena_AddPyObject(c->c_arena, tmpvalue);
3477 }
3478
Guido van Rossumda5b7012006-05-02 19:47:52 +00003479 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003480 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003481
3482 /* Squirrel away context.__exit__ */
3483 ADDOP(c, DUP_TOP);
3484 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3485 if (!compiler_nameop(c, tmpexit, Store))
3486 return 0;
3487
3488 /* Call context.__enter__() */
3489 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3490 ADDOP_I(c, CALL_FUNCTION, 0);
3491
3492 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 /* Store it in tmpvalue */
3494 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003495 return 0;
3496 }
3497 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 /* Discard result from context.__enter__() */
3499 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003500 }
3501
3502 /* Start the try block */
3503 ADDOP_JREL(c, SETUP_FINALLY, finally);
3504
3505 compiler_use_next_block(c, block);
3506 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003508 }
3509
3510 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003511 /* Bind saved result of context.__enter__() to VAR */
3512 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003513 !compiler_nameop(c, tmpvalue, Del))
3514 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003515 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003516 }
3517
3518 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003519 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003520
3521 /* End of try block; start the finally block */
3522 ADDOP(c, POP_BLOCK);
3523 compiler_pop_fblock(c, FINALLY_TRY, block);
3524
3525 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3526 compiler_use_next_block(c, finally);
3527 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003528 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003529
3530 /* Finally block starts; push tmpexit and issue our magic opcode. */
3531 if (!compiler_nameop(c, tmpexit, Load) ||
3532 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003533 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003534 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003535
3536 /* Finally block ends. */
3537 ADDOP(c, END_FINALLY);
3538 compiler_pop_fblock(c, FINALLY_END, finally);
3539 return 1;
3540}
3541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003542static int
3543compiler_visit_expr(struct compiler *c, expr_ty e)
3544{
3545 int i, n;
3546
Jeremy Hylton12603c42006-04-01 16:18:02 +00003547 /* If expr e has a different line number than the last expr/stmt,
3548 set a new line number for the next instruction.
3549 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 if (e->lineno > c->u->u_lineno) {
3551 c->u->u_lineno = e->lineno;
3552 c->u->u_lineno_set = false;
3553 }
3554 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003555 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 VISIT(c, expr, e->v.BinOp.left);
3559 VISIT(c, expr, e->v.BinOp.right);
3560 ADDOP(c, binop(c, e->v.BinOp.op));
3561 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003562 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 VISIT(c, expr, e->v.UnaryOp.operand);
3564 ADDOP(c, unaryop(e->v.UnaryOp.op));
3565 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003566 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003568 case IfExp_kind:
3569 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003570 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571 /* XXX get rid of arg? */
3572 ADDOP_I(c, BUILD_MAP, 0);
3573 n = asdl_seq_LEN(e->v.Dict.values);
3574 /* We must arrange things just right for STORE_SUBSCR.
3575 It wants the stack to look like (value) (dict) (key) */
3576 for (i = 0; i < n; i++) {
3577 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003578 VISIT(c, expr,
3579 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003581 VISIT(c, expr,
3582 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 ADDOP(c, STORE_SUBSCR);
3584 }
3585 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003586 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 return compiler_genexp(c, e);
3590 case Yield_kind:
3591 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003592 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 /*
3594 for (i = 0; i < c->u->u_nfblocks; i++) {
3595 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3596 return compiler_error(
3597 c, "'yield' not allowed in a 'try' "
3598 "block with a 'finally' clause");
3599 }
3600 */
3601 if (e->v.Yield.value) {
3602 VISIT(c, expr, e->v.Yield.value);
3603 }
3604 else {
3605 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3606 }
3607 ADDOP(c, YIELD_VALUE);
3608 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003609 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003611 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003613 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 VISIT(c, expr, e->v.Repr.value);
3615 ADDOP(c, UNARY_CONVERT);
3616 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003617 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3619 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003620 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3622 break;
3623 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003624 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003625 if (e->v.Attribute.ctx != AugStore)
3626 VISIT(c, expr, e->v.Attribute.value);
3627 switch (e->v.Attribute.ctx) {
3628 case AugLoad:
3629 ADDOP(c, DUP_TOP);
3630 /* Fall through to load */
3631 case Load:
3632 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3633 break;
3634 case AugStore:
3635 ADDOP(c, ROT_TWO);
3636 /* Fall through to save */
3637 case Store:
3638 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3639 break;
3640 case Del:
3641 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3642 break;
3643 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003644 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003645 PyErr_SetString(PyExc_SystemError,
3646 "param invalid in attribute expression");
3647 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 }
3649 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003650 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 switch (e->v.Subscript.ctx) {
3652 case AugLoad:
3653 VISIT(c, expr, e->v.Subscript.value);
3654 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3655 break;
3656 case Load:
3657 VISIT(c, expr, e->v.Subscript.value);
3658 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3659 break;
3660 case AugStore:
3661 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3662 break;
3663 case Store:
3664 VISIT(c, expr, e->v.Subscript.value);
3665 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3666 break;
3667 case Del:
3668 VISIT(c, expr, e->v.Subscript.value);
3669 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3670 break;
3671 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003672 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003673 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003674 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003676 }
3677 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003678 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3680 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003683 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003684 return compiler_tuple(c, e);
3685 }
3686 return 1;
3687}
3688
3689static int
3690compiler_augassign(struct compiler *c, stmt_ty s)
3691{
3692 expr_ty e = s->v.AugAssign.target;
3693 expr_ty auge;
3694
3695 assert(s->kind == AugAssign_kind);
3696
3697 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003698 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003699 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003700 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 if (auge == NULL)
3702 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703 VISIT(c, expr, auge);
3704 VISIT(c, expr, s->v.AugAssign.value);
3705 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3706 auge->v.Attribute.ctx = AugStore;
3707 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003708 break;
3709 case Subscript_kind:
3710 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003711 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003712 if (auge == NULL)
3713 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714 VISIT(c, expr, auge);
3715 VISIT(c, expr, s->v.AugAssign.value);
3716 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003717 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003718 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003719 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003721 if (!compiler_nameop(c, e->v.Name.id, Load))
3722 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003723 VISIT(c, expr, s->v.AugAssign.value);
3724 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3725 return compiler_nameop(c, e->v.Name.id, Store);
3726 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003727 PyErr_Format(PyExc_SystemError,
3728 "invalid node type (%d) for augmented assignment",
3729 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003730 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003731 }
3732 return 1;
3733}
3734
3735static int
3736compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3737{
3738 struct fblockinfo *f;
3739 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3740 return 0;
3741 f = &c->u->u_fblock[c->u->u_nfblocks++];
3742 f->fb_type = t;
3743 f->fb_block = b;
3744 return 1;
3745}
3746
3747static void
3748compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3749{
3750 struct compiler_unit *u = c->u;
3751 assert(u->u_nfblocks > 0);
3752 u->u_nfblocks--;
3753 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3754 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3755}
3756
3757/* Raises a SyntaxError and returns 0.
3758 If something goes wrong, a different exception may be raised.
3759*/
3760
3761static int
3762compiler_error(struct compiler *c, const char *errstr)
3763{
3764 PyObject *loc;
3765 PyObject *u = NULL, *v = NULL;
3766
3767 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3768 if (!loc) {
3769 Py_INCREF(Py_None);
3770 loc = Py_None;
3771 }
3772 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3773 Py_None, loc);
3774 if (!u)
3775 goto exit;
3776 v = Py_BuildValue("(zO)", errstr, u);
3777 if (!v)
3778 goto exit;
3779 PyErr_SetObject(PyExc_SyntaxError, v);
3780 exit:
3781 Py_DECREF(loc);
3782 Py_XDECREF(u);
3783 Py_XDECREF(v);
3784 return 0;
3785}
3786
3787static int
3788compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003789 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003791 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003792
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003793 /* XXX this code is duplicated */
3794 switch (ctx) {
3795 case AugLoad: /* fall through to Load */
3796 case Load: op = BINARY_SUBSCR; break;
3797 case AugStore:/* fall through to Store */
3798 case Store: op = STORE_SUBSCR; break;
3799 case Del: op = DELETE_SUBSCR; break;
3800 case Param:
3801 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003802 "invalid %s kind %d in subscript\n",
3803 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003804 return 0;
3805 }
3806 if (ctx == AugLoad) {
3807 ADDOP_I(c, DUP_TOPX, 2);
3808 }
3809 else if (ctx == AugStore) {
3810 ADDOP(c, ROT_THREE);
3811 }
3812 ADDOP(c, op);
3813 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814}
3815
3816static int
3817compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3818{
3819 int n = 2;
3820 assert(s->kind == Slice_kind);
3821
3822 /* only handles the cases where BUILD_SLICE is emitted */
3823 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003824 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 }
3826 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003827 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003828 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003830 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003831 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003832 }
3833 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003834 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 }
3836
3837 if (s->v.Slice.step) {
3838 n++;
3839 VISIT(c, expr, s->v.Slice.step);
3840 }
3841 ADDOP_I(c, BUILD_SLICE, n);
3842 return 1;
3843}
3844
3845static int
3846compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3847{
3848 int op = 0, slice_offset = 0, stack_count = 0;
3849
3850 assert(s->v.Slice.step == NULL);
3851 if (s->v.Slice.lower) {
3852 slice_offset++;
3853 stack_count++;
3854 if (ctx != AugStore)
3855 VISIT(c, expr, s->v.Slice.lower);
3856 }
3857 if (s->v.Slice.upper) {
3858 slice_offset += 2;
3859 stack_count++;
3860 if (ctx != AugStore)
3861 VISIT(c, expr, s->v.Slice.upper);
3862 }
3863
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003864 if (ctx == AugLoad) {
3865 switch (stack_count) {
3866 case 0: ADDOP(c, DUP_TOP); break;
3867 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3868 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3869 }
3870 }
3871 else if (ctx == AugStore) {
3872 switch (stack_count) {
3873 case 0: ADDOP(c, ROT_TWO); break;
3874 case 1: ADDOP(c, ROT_THREE); break;
3875 case 2: ADDOP(c, ROT_FOUR); break;
3876 }
3877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878
3879 switch (ctx) {
3880 case AugLoad: /* fall through to Load */
3881 case Load: op = SLICE; break;
3882 case AugStore:/* fall through to Store */
3883 case Store: op = STORE_SLICE; break;
3884 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003885 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003886 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003887 PyErr_SetString(PyExc_SystemError,
3888 "param invalid in simple slice");
3889 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 }
3891
3892 ADDOP(c, op + slice_offset);
3893 return 1;
3894}
3895
3896static int
3897compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3898 expr_context_ty ctx)
3899{
3900 switch (s->kind) {
3901 case Ellipsis_kind:
3902 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3903 break;
3904 case Slice_kind:
3905 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003906 case Index_kind:
3907 VISIT(c, expr, s->v.Index.value);
3908 break;
3909 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003910 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003911 PyErr_SetString(PyExc_SystemError,
3912 "extended slice invalid in nested slice");
3913 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 }
3915 return 1;
3916}
3917
3918
3919static int
3920compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3921{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003922 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003923 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003924 case Index_kind:
3925 kindname = "index";
3926 if (ctx != AugStore) {
3927 VISIT(c, expr, s->v.Index.value);
3928 }
3929 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003931 kindname = "ellipsis";
3932 if (ctx != AugStore) {
3933 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3934 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003935 break;
3936 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003937 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938 if (!s->v.Slice.step)
3939 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003940 if (ctx != AugStore) {
3941 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942 return 0;
3943 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003944 break;
3945 case ExtSlice_kind:
3946 kindname = "extended slice";
3947 if (ctx != AugStore) {
3948 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3949 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003950 slice_ty sub = (slice_ty)asdl_seq_GET(
3951 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003952 if (!compiler_visit_nested_slice(c, sub, ctx))
3953 return 0;
3954 }
3955 ADDOP_I(c, BUILD_TUPLE, n);
3956 }
3957 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003958 default:
3959 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003960 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003961 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003963 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964}
3965
3966/* do depth-first search of basic block graph, starting with block.
3967 post records the block indices in post-order.
3968
3969 XXX must handle implicit jumps from one block to next
3970*/
3971
3972static void
3973dfs(struct compiler *c, basicblock *b, struct assembler *a)
3974{
3975 int i;
3976 struct instr *instr = NULL;
3977
3978 if (b->b_seen)
3979 return;
3980 b->b_seen = 1;
3981 if (b->b_next != NULL)
3982 dfs(c, b->b_next, a);
3983 for (i = 0; i < b->b_iused; i++) {
3984 instr = &b->b_instr[i];
3985 if (instr->i_jrel || instr->i_jabs)
3986 dfs(c, instr->i_target, a);
3987 }
3988 a->a_postorder[a->a_nblocks++] = b;
3989}
3990
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003991static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003992stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3993{
3994 int i;
3995 struct instr *instr;
3996 if (b->b_seen || b->b_startdepth >= depth)
3997 return maxdepth;
3998 b->b_seen = 1;
3999 b->b_startdepth = depth;
4000 for (i = 0; i < b->b_iused; i++) {
4001 instr = &b->b_instr[i];
4002 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
4003 if (depth > maxdepth)
4004 maxdepth = depth;
4005 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4006 if (instr->i_jrel || instr->i_jabs) {
4007 maxdepth = stackdepth_walk(c, instr->i_target,
4008 depth, maxdepth);
4009 if (instr->i_opcode == JUMP_ABSOLUTE ||
4010 instr->i_opcode == JUMP_FORWARD) {
4011 goto out; /* remaining code is dead */
4012 }
4013 }
4014 }
4015 if (b->b_next)
4016 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
4017out:
4018 b->b_seen = 0;
4019 return maxdepth;
4020}
4021
4022/* Find the flow path that needs the largest stack. We assume that
4023 * cycles in the flow graph have no net effect on the stack depth.
4024 */
4025static int
4026stackdepth(struct compiler *c)
4027{
4028 basicblock *b, *entryblock;
4029 entryblock = NULL;
4030 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4031 b->b_seen = 0;
4032 b->b_startdepth = INT_MIN;
4033 entryblock = b;
4034 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00004035 if (!entryblock)
4036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004037 return stackdepth_walk(c, entryblock, 0, 0);
4038}
4039
4040static int
4041assemble_init(struct assembler *a, int nblocks, int firstlineno)
4042{
4043 memset(a, 0, sizeof(struct assembler));
4044 a->a_lineno = firstlineno;
4045 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4046 if (!a->a_bytecode)
4047 return 0;
4048 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4049 if (!a->a_lnotab)
4050 return 0;
4051 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004052 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004053 if (!a->a_postorder) {
4054 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004055 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004056 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057 return 1;
4058}
4059
4060static void
4061assemble_free(struct assembler *a)
4062{
4063 Py_XDECREF(a->a_bytecode);
4064 Py_XDECREF(a->a_lnotab);
4065 if (a->a_postorder)
4066 PyObject_Free(a->a_postorder);
4067}
4068
4069/* Return the size of a basic block in bytes. */
4070
4071static int
4072instrsize(struct instr *instr)
4073{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004074 if (!instr->i_hasarg)
4075 return 1;
4076 if (instr->i_oparg > 0xffff)
4077 return 6;
4078 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004079}
4080
4081static int
4082blocksize(basicblock *b)
4083{
4084 int i;
4085 int size = 0;
4086
4087 for (i = 0; i < b->b_iused; i++)
4088 size += instrsize(&b->b_instr[i]);
4089 return size;
4090}
4091
4092/* All about a_lnotab.
4093
4094c_lnotab is an array of unsigned bytes disguised as a Python string.
4095It is used to map bytecode offsets to source code line #s (when needed
4096for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004097
Tim Peters2a7f3842001-06-09 09:26:21 +00004098The array is conceptually a list of
4099 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004100pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004101
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004102 byte code offset source code line number
4103 0 1
4104 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004105 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004106 350 307
4107 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004108
4109The first trick is that these numbers aren't stored, only the increments
4110from one row to the next (this doesn't really work, but it's a start):
4111
4112 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4113
4114The second trick is that an unsigned byte can't hold negative values, or
4115values larger than 255, so (a) there's a deep assumption that byte code
4116offsets and their corresponding line #s both increase monotonically, and (b)
4117if at least one column jumps by more than 255 from one row to the next, more
4118than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004119from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004120part. A user of c_lnotab desiring to find the source line number
4121corresponding to a bytecode address A should do something like this
4122
4123 lineno = addr = 0
4124 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004125 addr += addr_incr
4126 if addr > A:
4127 return lineno
4128 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004129
4130In order for this to work, when the addr field increments by more than 255,
4131the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004132increment is < 256. So, in the example above, assemble_lnotab (it used
4133to be called com_set_lineno) should not (as was actually done until 2.2)
4134expand 300, 300 to 255, 255, 45, 45,
4135 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004136*/
4137
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004140{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 int d_bytecode, d_lineno;
4142 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004143 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144
4145 d_bytecode = a->a_offset - a->a_lineno_off;
4146 d_lineno = i->i_lineno - a->a_lineno;
4147
4148 assert(d_bytecode >= 0);
4149 assert(d_lineno >= 0);
4150
Neal Norwitz4ffedad2006-08-04 04:58:47 +00004151 /* XXX(nnorwitz): is there a better way to handle this?
4152 for loops are special, we want to be able to trace them
4153 each time around, so we need to set an extra line number. */
4154 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004155 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004156
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004157 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004158 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 nbytes = a->a_lnotab_off + 2 * ncodes;
4160 len = PyString_GET_SIZE(a->a_lnotab);
4161 if (nbytes >= len) {
4162 if (len * 2 < nbytes)
4163 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004164 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 len *= 2;
4166 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4167 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004168 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004169 lnotab = (unsigned char *)
4170 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004171 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172 *lnotab++ = 255;
4173 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175 d_bytecode -= ncodes * 255;
4176 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004177 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178 assert(d_bytecode <= 255);
4179 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004180 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 nbytes = a->a_lnotab_off + 2 * ncodes;
4182 len = PyString_GET_SIZE(a->a_lnotab);
4183 if (nbytes >= len) {
4184 if (len * 2 < nbytes)
4185 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004186 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187 len *= 2;
4188 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4189 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004190 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004191 lnotab = (unsigned char *)
4192 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004194 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004196 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004198 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004199 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 d_lineno -= ncodes * 255;
4201 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004202 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004203
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204 len = PyString_GET_SIZE(a->a_lnotab);
4205 if (a->a_lnotab_off + 2 >= len) {
4206 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004207 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004208 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004209 lnotab = (unsigned char *)
4210 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212 a->a_lnotab_off += 2;
4213 if (d_bytecode) {
4214 *lnotab++ = d_bytecode;
4215 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004216 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004217 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218 *lnotab++ = 0;
4219 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 a->a_lineno = i->i_lineno;
4222 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004223 return 1;
4224}
4225
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004226/* assemble_emit()
4227 Extend the bytecode with a new instruction.
4228 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004229*/
4230
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004231static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004232assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004233{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004234 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004235 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236 char *code;
4237
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004238 size = instrsize(i);
4239 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004241 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004243 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004244 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245 if (a->a_offset + size >= len) {
4246 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004247 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4250 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004251 if (size == 6) {
4252 assert(i->i_hasarg);
4253 *code++ = (char)EXTENDED_ARG;
4254 *code++ = ext & 0xff;
4255 *code++ = ext >> 8;
4256 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004258 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004259 if (i->i_hasarg) {
4260 assert(size == 3 || size == 6);
4261 *code++ = arg & 0xff;
4262 *code++ = arg >> 8;
4263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004264 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004265}
4266
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004267static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004269{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004270 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004271 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004272 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004274 /* Compute the size of each block and fixup jump args.
4275 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004276start:
4277 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004279 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280 bsize = blocksize(b);
4281 b->b_offset = totsize;
4282 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004283 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004284 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4286 bsize = b->b_offset;
4287 for (i = 0; i < b->b_iused; i++) {
4288 struct instr *instr = &b->b_instr[i];
4289 /* Relative jumps are computed relative to
4290 the instruction pointer after fetching
4291 the jump instruction.
4292 */
4293 bsize += instrsize(instr);
4294 if (instr->i_jabs)
4295 instr->i_oparg = instr->i_target->b_offset;
4296 else if (instr->i_jrel) {
4297 int delta = instr->i_target->b_offset - bsize;
4298 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004299 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004300 else
4301 continue;
4302 if (instr->i_oparg > 0xffff)
4303 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004304 }
4305 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004306
4307 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004308 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004309 with a better solution.
4310
4311 In the meantime, should the goto be dropped in favor
4312 of a loop?
4313
4314 The issue is that in the first loop blocksize() is called
4315 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004316 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004317 i_oparg is calculated in the second loop above.
4318
4319 So we loop until we stop seeing new EXTENDED_ARGs.
4320 The only EXTENDED_ARGs that could be popping up are
4321 ones in jump instructions. So this should converge
4322 fairly quickly.
4323 */
4324 if (last_extended_arg_count != extended_arg_count) {
4325 last_extended_arg_count = extended_arg_count;
4326 goto start;
4327 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004328}
4329
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004330static PyObject *
4331dict_keys_inorder(PyObject *dict, int offset)
4332{
4333 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004334 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004335
4336 tuple = PyTuple_New(size);
4337 if (tuple == NULL)
4338 return NULL;
4339 while (PyDict_Next(dict, &pos, &k, &v)) {
4340 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004341 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004342 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004343 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004344 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004345 PyTuple_SET_ITEM(tuple, i - offset, k);
4346 }
4347 return tuple;
4348}
4349
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004350static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004351compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004352{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353 PySTEntryObject *ste = c->u->u_ste;
4354 int flags = 0, n;
4355 if (ste->ste_type != ModuleBlock)
4356 flags |= CO_NEWLOCALS;
4357 if (ste->ste_type == FunctionBlock) {
4358 if (!ste->ste_unoptimized)
4359 flags |= CO_OPTIMIZED;
4360 if (ste->ste_nested)
4361 flags |= CO_NESTED;
4362 if (ste->ste_generator)
4363 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004364 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365 if (ste->ste_varargs)
4366 flags |= CO_VARARGS;
4367 if (ste->ste_varkeywords)
4368 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004369 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004371
4372 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004373 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004374
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375 n = PyDict_Size(c->u->u_freevars);
4376 if (n < 0)
4377 return -1;
4378 if (n == 0) {
4379 n = PyDict_Size(c->u->u_cellvars);
4380 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004381 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382 if (n == 0) {
4383 flags |= CO_NOFREE;
4384 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004385 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004386
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004387 return flags;
4388}
4389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004390static PyCodeObject *
4391makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004392{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393 PyObject *tmp;
4394 PyCodeObject *co = NULL;
4395 PyObject *consts = NULL;
4396 PyObject *names = NULL;
4397 PyObject *varnames = NULL;
4398 PyObject *filename = NULL;
4399 PyObject *name = NULL;
4400 PyObject *freevars = NULL;
4401 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004402 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004403 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405 tmp = dict_keys_inorder(c->u->u_consts, 0);
4406 if (!tmp)
4407 goto error;
4408 consts = PySequence_List(tmp); /* optimize_code requires a list */
4409 Py_DECREF(tmp);
4410
4411 names = dict_keys_inorder(c->u->u_names, 0);
4412 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4413 if (!consts || !names || !varnames)
4414 goto error;
4415
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004416 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4417 if (!cellvars)
4418 goto error;
4419 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4420 if (!freevars)
4421 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422 filename = PyString_FromString(c->c_filename);
4423 if (!filename)
4424 goto error;
4425
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004426 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004427 flags = compute_code_flags(c);
4428 if (flags < 0)
4429 goto error;
4430
4431 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4432 if (!bytecode)
4433 goto error;
4434
4435 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4436 if (!tmp)
4437 goto error;
4438 Py_DECREF(consts);
4439 consts = tmp;
4440
4441 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4442 bytecode, consts, names, varnames,
4443 freevars, cellvars,
4444 filename, c->u->u_name,
4445 c->u->u_firstlineno,
4446 a->a_lnotab);
4447 error:
4448 Py_XDECREF(consts);
4449 Py_XDECREF(names);
4450 Py_XDECREF(varnames);
4451 Py_XDECREF(filename);
4452 Py_XDECREF(name);
4453 Py_XDECREF(freevars);
4454 Py_XDECREF(cellvars);
4455 Py_XDECREF(bytecode);
4456 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004457}
4458
Neal Norwitz4ffedad2006-08-04 04:58:47 +00004459
4460/* For debugging purposes only */
4461#if 0
4462static void
4463dump_instr(const struct instr *i)
4464{
4465 const char *jrel = i->i_jrel ? "jrel " : "";
4466 const char *jabs = i->i_jabs ? "jabs " : "";
4467 char arg[128];
4468
4469 *arg = '\0';
4470 if (i->i_hasarg)
4471 sprintf(arg, "arg: %d ", i->i_oparg);
4472
4473 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4474 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4475}
4476
4477static void
4478dump_basicblock(const basicblock *b)
4479{
4480 const char *seen = b->b_seen ? "seen " : "";
4481 const char *b_return = b->b_return ? "return " : "";
4482 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4483 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4484 if (b->b_instr) {
4485 int i;
4486 for (i = 0; i < b->b_iused; i++) {
4487 fprintf(stderr, " [%02d] ", i);
4488 dump_instr(b->b_instr + i);
4489 }
4490 }
4491}
4492#endif
4493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004494static PyCodeObject *
4495assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004496{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004497 basicblock *b, *entryblock;
4498 struct assembler a;
4499 int i, j, nblocks;
4500 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004501
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004502 /* Make sure every block that falls off the end returns None.
4503 XXX NEXT_BLOCK() isn't quite right, because if the last
4504 block ends with a jump or return b_next shouldn't set.
4505 */
4506 if (!c->u->u_curblock->b_return) {
4507 NEXT_BLOCK(c);
4508 if (addNone)
4509 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4510 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004511 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004513 nblocks = 0;
4514 entryblock = NULL;
4515 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4516 nblocks++;
4517 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004518 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004519
Neal Norwitzed657552006-07-10 00:04:44 +00004520 /* Set firstlineno if it wasn't explicitly set. */
4521 if (!c->u->u_firstlineno) {
4522 if (entryblock && entryblock->b_instr)
4523 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4524 else
4525 c->u->u_firstlineno = 1;
4526 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004527 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4528 goto error;
4529 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004531 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004532 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004534 /* Emit code in reverse postorder from dfs. */
4535 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004536 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004537 for (j = 0; j < b->b_iused; j++)
4538 if (!assemble_emit(&a, &b->b_instr[j]))
4539 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004540 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4543 goto error;
4544 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4545 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004546
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004547 co = makecode(c, &a);
4548 error:
4549 assemble_free(&a);
4550 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004551}