blob: 4464882edf66070296788c82e0013075d2178499 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207 if (privateobj == NULL || name == NULL || name[0] != '_' ||
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 name[1] != '_') {
209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +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)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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);
Thomas Wouters477c8d52006-05-27 19:21:47 +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++;
Thomas Wouters477c8d52006-05-27 19:21:47 +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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000490 case BINARY_TRUE_DIVIDE:
491 newconst = PyNumber_TrueDivide(v, w);
492 break;
493 case BINARY_FLOOR_DIVIDE:
494 newconst = PyNumber_FloorDivide(v, w);
495 break;
496 case BINARY_MODULO:
497 newconst = PyNumber_Remainder(v, w);
498 break;
499 case BINARY_ADD:
500 newconst = PyNumber_Add(v, w);
501 break;
502 case BINARY_SUBTRACT:
503 newconst = PyNumber_Subtract(v, w);
504 break;
505 case BINARY_SUBSCR:
506 newconst = PyObject_GetItem(v, w);
507 break;
508 case BINARY_LSHIFT:
509 newconst = PyNumber_Lshift(v, w);
510 break;
511 case BINARY_RSHIFT:
512 newconst = PyNumber_Rshift(v, w);
513 break;
514 case BINARY_AND:
515 newconst = PyNumber_And(v, w);
516 break;
517 case BINARY_XOR:
518 newconst = PyNumber_Xor(v, w);
519 break;
520 case BINARY_OR:
521 newconst = PyNumber_Or(v, w);
522 break;
523 default:
524 /* Called with an unknown opcode */
525 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000526 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000527 opcode);
528 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000529 }
530 if (newconst == NULL) {
531 PyErr_Clear();
532 return 0;
533 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000534 size = PyObject_Size(newconst);
535 if (size == -1)
536 PyErr_Clear();
537 else if (size > 20) {
538 Py_DECREF(newconst);
539 return 0;
540 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000541
542 /* Append folded constant into consts table */
543 len_consts = PyList_GET_SIZE(consts);
544 if (PyList_Append(consts, newconst)) {
545 Py_DECREF(newconst);
546 return 0;
547 }
548 Py_DECREF(newconst);
549
550 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
551 memset(codestr, NOP, 4);
552 codestr[4] = LOAD_CONST;
553 SETARG(codestr, 4, len_consts);
554 return 1;
555}
556
Raymond Hettinger80121492005-02-20 12:41:32 +0000557static int
558fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
559{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000560 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000561 Py_ssize_t len_consts;
562 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000563
564 /* Pre-conditions */
565 assert(PyList_CheckExact(consts));
566 assert(codestr[0] == LOAD_CONST);
567
568 /* Create new constant */
569 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
570 opcode = codestr[3];
571 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000572 case UNARY_NEGATIVE:
573 /* Preserve the sign of -0.0 */
574 if (PyObject_IsTrue(v) == 1)
575 newconst = PyNumber_Negative(v);
576 break;
577 case UNARY_CONVERT:
578 newconst = PyObject_Repr(v);
579 break;
580 case UNARY_INVERT:
581 newconst = PyNumber_Invert(v);
582 break;
583 default:
584 /* Called with an unknown opcode */
585 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000586 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000587 opcode);
588 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000589 }
590 if (newconst == NULL) {
591 PyErr_Clear();
592 return 0;
593 }
594
595 /* Append folded constant into consts table */
596 len_consts = PyList_GET_SIZE(consts);
597 if (PyList_Append(consts, newconst)) {
598 Py_DECREF(newconst);
599 return 0;
600 }
601 Py_DECREF(newconst);
602
603 /* Write NOP LOAD_CONST newconst */
604 codestr[0] = NOP;
605 codestr[1] = LOAD_CONST;
606 SETARG(codestr, 1, len_consts);
607 return 1;
608}
609
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000610static unsigned int *
611markblocks(unsigned char *code, int len)
612{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000613 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000614 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000615
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616 if (blocks == NULL) {
617 PyErr_NoMemory();
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000618 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000620 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000621
622 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000623 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
624 opcode = code[i];
625 switch (opcode) {
626 case FOR_ITER:
627 case JUMP_FORWARD:
628 case JUMP_IF_FALSE:
629 case JUMP_IF_TRUE:
630 case JUMP_ABSOLUTE:
631 case CONTINUE_LOOP:
632 case SETUP_LOOP:
633 case SETUP_EXCEPT:
634 case SETUP_FINALLY:
635 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000636 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000638 }
639 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000640 /* Build block numbers in the second pass */
641 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000642 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000643 blocks[i] = blockcnt;
644 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000645 return blocks;
646}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000647
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000648/* Perform basic peephole optimizations to components of a code object.
649 The consts object should still be in list form to allow new constants
650 to be appended.
651
652 To keep the optimizer simple, it bails out (does nothing) for code
653 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000654 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000655 the lineno table has complex encoding for gaps >= 255.
656
657 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000658 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000659 smaller. For those that reduce size, the gaps are initially filled with
660 NOPs. Later those NOPs are removed and the jump addresses retargeted in
661 a single pass. Line numbering is adjusted accordingly. */
662
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000664optimize_code(PyObject *code, PyObject* consts, PyObject *names,
665 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000666{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000667 Py_ssize_t i, j, codelen;
668 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000669 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000670 unsigned char *codestr = NULL;
671 unsigned char *lineno;
672 int *addrmap = NULL;
673 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000674 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000675 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000676 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000677
Raymond Hettingereffb3932004-10-30 08:55:08 +0000678 /* Bail out if an exception is set */
679 if (PyErr_Occurred())
680 goto exitUnchanged;
681
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000682 /* Bypass optimization when the lineno table is too complex */
683 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000684 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000685 tabsiz = PyString_GET_SIZE(lineno_obj);
686 if (memchr(lineno, 255, tabsiz) != NULL)
687 goto exitUnchanged;
688
Raymond Hettingera12fa142004-08-24 04:34:16 +0000689 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000690 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000692 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000693 goto exitUnchanged;
694
695 /* Make a modifiable copy of the code string */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000697 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000698 goto exitUnchanged;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699 codestr = (unsigned char *)memcpy(codestr,
700 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000701
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000702 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000703 the various transformation patterns to look ahead several
704 instructions without additional checks to make sure they are not
705 looking beyond the end of the code string.
706 */
707 if (codestr[codelen-1] != RETURN_VALUE)
708 goto exitUnchanged;
709
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000710 /* Mapping to new jump targets after NOPs are removed */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000711 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000712 if (addrmap == NULL)
713 goto exitUnchanged;
714
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000715 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000716 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000717 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000718 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000719
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000720 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000721 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000722
723 lastlc = cumlc;
724 cumlc = 0;
725
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000726 switch (opcode) {
727
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000728 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
729 with JUMP_IF_TRUE POP_TOP */
730 case UNARY_NOT:
731 if (codestr[i+1] != JUMP_IF_FALSE ||
732 codestr[i+4] != POP_TOP ||
733 !ISBASICBLOCK(blocks,i,5))
734 continue;
735 tgt = GETJUMPTGT(codestr, (i+1));
736 if (codestr[tgt] != POP_TOP)
737 continue;
738 j = GETARG(codestr, i+1) + 1;
739 codestr[i] = JUMP_IF_TRUE;
740 SETARG(codestr, i, j);
741 codestr[i+3] = POP_TOP;
742 codestr[i+4] = NOP;
743 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000744
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000745 /* not a is b --> a is not b
746 not a in b --> a not in b
747 not a is not b --> a is b
748 not a not in b --> a in b
749 */
750 case COMPARE_OP:
751 j = GETARG(codestr, i);
752 if (j < 6 || j > 9 ||
753 codestr[i+3] != UNARY_NOT ||
754 !ISBASICBLOCK(blocks,i,4))
755 continue;
756 SETARG(codestr, i, (j^1));
757 codestr[i+3] = NOP;
758 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000759
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000760 /* Replace LOAD_GLOBAL/LOAD_NAME None
761 with LOAD_CONST None */
762 case LOAD_NAME:
763 case LOAD_GLOBAL:
764 j = GETARG(codestr, i);
765 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
766 if (name == NULL || strcmp(name, "None") != 0)
767 continue;
768 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
769 if (PyList_GET_ITEM(consts, j) == Py_None) {
770 codestr[i] = LOAD_CONST;
771 SETARG(codestr, i, j);
772 cumlc = lastlc + 1;
773 break;
774 }
775 }
776 break;
777
778 /* Skip over LOAD_CONST trueconst
779 JUMP_IF_FALSE xx POP_TOP */
780 case LOAD_CONST:
781 cumlc = lastlc + 1;
782 j = GETARG(codestr, i);
783 if (codestr[i+3] != JUMP_IF_FALSE ||
784 codestr[i+6] != POP_TOP ||
785 !ISBASICBLOCK(blocks,i,7) ||
786 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
787 continue;
788 memset(codestr+i, NOP, 7);
789 cumlc = 0;
790 break;
791
792 /* Try to fold tuples of constants (includes a case for lists
793 which are only used for "in" and "not in" tests).
794 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
795 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
796 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
797 case BUILD_TUPLE:
798 case BUILD_LIST:
799 j = GETARG(codestr, i);
800 h = i - 3 * j;
801 if (h >= 0 &&
802 j <= lastlc &&
803 ((opcode == BUILD_TUPLE &&
804 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
805 (opcode == BUILD_LIST &&
806 codestr[i+3]==COMPARE_OP &&
807 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
808 (GETARG(codestr,i+3)==6 ||
809 GETARG(codestr,i+3)==7))) &&
810 tuple_of_constants(&codestr[h], j, consts)) {
811 assert(codestr[i] == LOAD_CONST);
812 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000813 break;
814 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000815 if (codestr[i+3] != UNPACK_SEQUENCE ||
816 !ISBASICBLOCK(blocks,i,6) ||
817 j != GETARG(codestr, i+3))
818 continue;
819 if (j == 1) {
820 memset(codestr+i, NOP, 6);
821 } else if (j == 2) {
822 codestr[i] = ROT_TWO;
823 memset(codestr+i+1, NOP, 5);
824 } else if (j == 3) {
825 codestr[i] = ROT_THREE;
826 codestr[i+1] = ROT_TWO;
827 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000828 }
829 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000830
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000831 /* Fold binary ops on constants.
832 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
833 case BINARY_POWER:
834 case BINARY_MULTIPLY:
835 case BINARY_TRUE_DIVIDE:
836 case BINARY_FLOOR_DIVIDE:
837 case BINARY_MODULO:
838 case BINARY_ADD:
839 case BINARY_SUBTRACT:
840 case BINARY_SUBSCR:
841 case BINARY_LSHIFT:
842 case BINARY_RSHIFT:
843 case BINARY_AND:
844 case BINARY_XOR:
845 case BINARY_OR:
846 if (lastlc >= 2 &&
847 ISBASICBLOCK(blocks, i-6, 7) &&
848 fold_binops_on_constants(&codestr[i-6], consts)) {
849 i -= 2;
850 assert(codestr[i] == LOAD_CONST);
851 cumlc = 1;
852 }
853 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000854
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000855 /* Fold unary ops on constants.
856 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
857 case UNARY_NEGATIVE:
858 case UNARY_CONVERT:
859 case UNARY_INVERT:
860 if (lastlc >= 1 &&
861 ISBASICBLOCK(blocks, i-3, 4) &&
862 fold_unaryops_on_constants(&codestr[i-3], consts)) {
863 i -= 2;
864 assert(codestr[i] == LOAD_CONST);
865 cumlc = 1;
866 }
867 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000868
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000869 /* Simplify conditional jump to conditional jump where the
870 result of the first test implies the success of a similar
871 test or the failure of the opposite test.
872 Arises in code like:
873 "if a and b:"
874 "if a or b:"
875 "a and b or c"
876 "(a and b) and c"
877 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
878 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
879 where y+3 is the instruction following the second test.
880 */
881 case JUMP_IF_FALSE:
882 case JUMP_IF_TRUE:
883 tgt = GETJUMPTGT(codestr, i);
884 j = codestr[tgt];
885 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
886 if (j == opcode) {
887 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
888 SETARG(codestr, i, tgttgt);
889 } else {
890 tgt -= i;
891 SETARG(codestr, i, tgt);
892 }
893 break;
894 }
895 /* Intentional fallthrough */
896
897 /* Replace jumps to unconditional jumps */
898 case FOR_ITER:
899 case JUMP_FORWARD:
900 case JUMP_ABSOLUTE:
901 case CONTINUE_LOOP:
902 case SETUP_LOOP:
903 case SETUP_EXCEPT:
904 case SETUP_FINALLY:
905 tgt = GETJUMPTGT(codestr, i);
906 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
907 continue;
908 tgttgt = GETJUMPTGT(codestr, tgt);
909 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
910 opcode = JUMP_ABSOLUTE;
911 if (!ABSOLUTE_JUMP(opcode))
912 tgttgt -= i + 3; /* Calc relative jump addr */
913 if (tgttgt < 0) /* No backward relative jumps */
914 continue;
915 codestr[i] = opcode;
916 SETARG(codestr, i, tgttgt);
917 break;
918
919 case EXTENDED_ARG:
920 goto exitUnchanged;
921
922 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
923 case RETURN_VALUE:
924 if (i+4 >= codelen ||
925 codestr[i+4] != RETURN_VALUE ||
926 !ISBASICBLOCK(blocks,i,5))
927 continue;
928 memset(codestr+i+1, NOP, 4);
929 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000930 }
931 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000932
933 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000934 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
935 addrmap[i] = i - nops;
936 if (codestr[i] == NOP)
937 nops++;
938 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000939 cum_orig_line = 0;
940 last_line = 0;
941 for (i=0 ; i < tabsiz ; i+=2) {
942 cum_orig_line += lineno[i];
943 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000944 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000945 lineno[i] =((unsigned char)(new_line - last_line));
946 last_line = new_line;
947 }
948
949 /* Remove NOPs and fixup jump targets */
950 for (i=0, h=0 ; i<codelen ; ) {
951 opcode = codestr[i];
952 switch (opcode) {
953 case NOP:
954 i++;
955 continue;
956
957 case JUMP_ABSOLUTE:
958 case CONTINUE_LOOP:
959 j = addrmap[GETARG(codestr, i)];
960 SETARG(codestr, i, j);
961 break;
962
963 case FOR_ITER:
964 case JUMP_FORWARD:
965 case JUMP_IF_FALSE:
966 case JUMP_IF_TRUE:
967 case SETUP_LOOP:
968 case SETUP_EXCEPT:
969 case SETUP_FINALLY:
970 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
971 SETARG(codestr, i, j);
972 break;
973 }
974 adj = CODESIZE(opcode);
975 while (adj--)
976 codestr[h++] = codestr[i++];
977 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000978 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000979
980 code = PyString_FromStringAndSize((char *)codestr, h);
981 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000982 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000983 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000984 return code;
985
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000987 if (blocks != NULL)
988 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000989 if (addrmap != NULL)
990 PyMem_Free(addrmap);
991 if (codestr != NULL)
992 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000993 Py_INCREF(code);
994 return code;
995}
996
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000997/* End: Peephole optimizations ----------------------------------------- */
998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999/*
1000
1001Leave this debugging code for just a little longer.
1002
1003static void
1004compiler_display_symbols(PyObject *name, PyObject *symbols)
1005{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006PyObject *key, *value;
1007int flags;
1008Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1011while (PyDict_Next(symbols, &pos, &key, &value)) {
1012flags = PyInt_AsLong(value);
1013fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1014if (flags & DEF_GLOBAL)
1015fprintf(stderr, " declared_global");
1016if (flags & DEF_LOCAL)
1017fprintf(stderr, " local");
1018if (flags & DEF_PARAM)
1019fprintf(stderr, " param");
1020if (flags & DEF_STAR)
1021fprintf(stderr, " stararg");
1022if (flags & DEF_DOUBLESTAR)
1023fprintf(stderr, " starstar");
1024if (flags & DEF_INTUPLE)
1025fprintf(stderr, " tuple");
1026if (flags & DEF_FREE)
1027fprintf(stderr, " free");
1028if (flags & DEF_FREE_GLOBAL)
1029fprintf(stderr, " global");
1030if (flags & DEF_FREE_CLASS)
1031fprintf(stderr, " free/class");
1032if (flags & DEF_IMPORT)
1033fprintf(stderr, " import");
1034fprintf(stderr, "\n");
1035}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 fprintf(stderr, "\n");
1037}
1038*/
1039
1040static void
1041compiler_unit_check(struct compiler_unit *u)
1042{
1043 basicblock *block;
1044 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1045 assert(block != (void *)0xcbcbcbcb);
1046 assert(block != (void *)0xfbfbfbfb);
1047 assert(block != (void *)0xdbdbdbdb);
1048 if (block->b_instr != NULL) {
1049 assert(block->b_ialloc > 0);
1050 assert(block->b_iused > 0);
1051 assert(block->b_ialloc >= block->b_iused);
1052 }
1053 else {
1054 assert (block->b_iused == 0);
1055 assert (block->b_ialloc == 0);
1056 }
1057 }
1058}
1059
1060static void
1061compiler_unit_free(struct compiler_unit *u)
1062{
1063 basicblock *b, *next;
1064
1065 compiler_unit_check(u);
1066 b = u->u_blocks;
1067 while (b != NULL) {
1068 if (b->b_instr)
1069 PyObject_Free((void *)b->b_instr);
1070 next = b->b_list;
1071 PyObject_Free((void *)b);
1072 b = next;
1073 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001074 Py_CLEAR(u->u_ste);
1075 Py_CLEAR(u->u_name);
1076 Py_CLEAR(u->u_consts);
1077 Py_CLEAR(u->u_names);
1078 Py_CLEAR(u->u_varnames);
1079 Py_CLEAR(u->u_freevars);
1080 Py_CLEAR(u->u_cellvars);
1081 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082 PyObject_Free(u);
1083}
1084
1085static int
1086compiler_enter_scope(struct compiler *c, identifier name, void *key,
1087 int lineno)
1088{
1089 struct compiler_unit *u;
1090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001091 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1092 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001093 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001094 PyErr_NoMemory();
1095 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001096 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 u->u_argcount = 0;
1099 u->u_ste = PySymtable_Lookup(c->c_st, key);
1100 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001101 compiler_unit_free(u);
1102 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 }
1104 Py_INCREF(name);
1105 u->u_name = name;
1106 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1107 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001108 if (!u->u_varnames || !u->u_cellvars) {
1109 compiler_unit_free(u);
1110 return 0;
1111 }
1112
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001114 PyDict_Size(u->u_cellvars));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001115 if (!u->u_freevars) {
1116 compiler_unit_free(u);
1117 return 0;
1118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001119
1120 u->u_blocks = NULL;
1121 u->u_tmpname = 0;
1122 u->u_nfblocks = 0;
1123 u->u_firstlineno = lineno;
1124 u->u_lineno = 0;
1125 u->u_lineno_set = false;
1126 u->u_consts = PyDict_New();
1127 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001128 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001129 return 0;
1130 }
1131 u->u_names = PyDict_New();
1132 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001133 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001134 return 0;
1135 }
1136
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001137 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138
1139 /* Push the old compiler_unit on the stack. */
1140 if (c->u) {
1141 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001142 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
1143 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001144 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 return 0;
1146 }
1147 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001148 u->u_private = c->u->u_private;
1149 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 }
1151 c->u = u;
1152
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001153 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001154 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155 return 0;
1156
1157 return 1;
1158}
1159
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001160static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161compiler_exit_scope(struct compiler *c)
1162{
1163 int n;
1164 PyObject *wrapper;
1165
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001166 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 compiler_unit_free(c->u);
1168 /* Restore c->u to the parent unit. */
1169 n = PyList_GET_SIZE(c->c_stack) - 1;
1170 if (n >= 0) {
1171 wrapper = PyList_GET_ITEM(c->c_stack, n);
1172 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001173 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001174 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001175 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176 compiler_unit_check(c->u);
1177 }
1178 else
1179 c->u = NULL;
1180
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001181}
1182
Guido van Rossumc2e20742006-02-27 22:32:47 +00001183/* Allocate a new "anonymous" local variable.
1184 Used by list comprehensions and with statements.
1185*/
1186
1187static PyObject *
1188compiler_new_tmpname(struct compiler *c)
1189{
1190 char tmpname[256];
1191 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1192 return PyString_FromString(tmpname);
1193}
1194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001195/* Allocate a new block and return a pointer to it.
1196 Returns NULL on error.
1197*/
1198
1199static basicblock *
1200compiler_new_block(struct compiler *c)
1201{
1202 basicblock *b;
1203 struct compiler_unit *u;
1204
1205 u = c->u;
1206 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001207 if (b == NULL) {
1208 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001210 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001211 memset((void *)b, 0, sizeof(basicblock));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001212 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213 b->b_list = u->u_blocks;
1214 u->u_blocks = b;
1215 return b;
1216}
1217
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218static basicblock *
1219compiler_use_new_block(struct compiler *c)
1220{
1221 basicblock *block = compiler_new_block(c);
1222 if (block == NULL)
1223 return NULL;
1224 c->u->u_curblock = block;
1225 return block;
1226}
1227
1228static basicblock *
1229compiler_next_block(struct compiler *c)
1230{
1231 basicblock *block = compiler_new_block(c);
1232 if (block == NULL)
1233 return NULL;
1234 c->u->u_curblock->b_next = block;
1235 c->u->u_curblock = block;
1236 return block;
1237}
1238
1239static basicblock *
1240compiler_use_next_block(struct compiler *c, basicblock *block)
1241{
1242 assert(block != NULL);
1243 c->u->u_curblock->b_next = block;
1244 c->u->u_curblock = block;
1245 return block;
1246}
1247
1248/* Returns the offset of the next instruction in the current block's
1249 b_instr array. Resizes the b_instr as necessary.
1250 Returns -1 on failure.
1251 */
1252
1253static int
1254compiler_next_instr(struct compiler *c, basicblock *b)
1255{
1256 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001257 if (b->b_instr == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 b->b_instr = (struct instr *)PyObject_Malloc(
1259 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001260 if (b->b_instr == NULL) {
1261 PyErr_NoMemory();
1262 return -1;
1263 }
1264 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1265 memset((char *)b->b_instr, 0,
1266 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001268 else if (b->b_iused == b->b_ialloc) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001269 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270 size_t oldsize, newsize;
1271 oldsize = b->b_ialloc * sizeof(struct instr);
1272 newsize = oldsize << 1;
1273 if (newsize == 0) {
1274 PyErr_NoMemory();
1275 return -1;
1276 }
1277 b->b_ialloc <<= 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001278 tmp = (struct instr *)PyObject_Realloc(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001279 (void *)b->b_instr, newsize);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001280 if (tmp == NULL) {
1281 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001282 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001283 }
1284 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1286 }
1287 return b->b_iused++;
1288}
1289
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001290/* Set the i_lineno member of the instruction at offse off if the
1291 line number for the current expression/statement (?) has not
1292 already been set. If it has been set, the call has no effect.
1293
1294 Every time a new node is b
1295 */
1296
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001297static void
1298compiler_set_lineno(struct compiler *c, int off)
1299{
1300 basicblock *b;
1301 if (c->u->u_lineno_set)
1302 return;
1303 c->u->u_lineno_set = true;
1304 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001305 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001306}
1307
1308static int
1309opcode_stack_effect(int opcode, int oparg)
1310{
1311 switch (opcode) {
1312 case POP_TOP:
1313 return -1;
1314 case ROT_TWO:
1315 case ROT_THREE:
1316 return 0;
1317 case DUP_TOP:
1318 return 1;
1319 case ROT_FOUR:
1320 return 0;
1321
1322 case UNARY_POSITIVE:
1323 case UNARY_NEGATIVE:
1324 case UNARY_NOT:
1325 case UNARY_CONVERT:
1326 case UNARY_INVERT:
1327 return 0;
1328
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001329 case LIST_APPEND:
1330 return -2;
1331
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001332 case BINARY_POWER:
1333 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334 case BINARY_MODULO:
1335 case BINARY_ADD:
1336 case BINARY_SUBTRACT:
1337 case BINARY_SUBSCR:
1338 case BINARY_FLOOR_DIVIDE:
1339 case BINARY_TRUE_DIVIDE:
1340 return -1;
1341 case INPLACE_FLOOR_DIVIDE:
1342 case INPLACE_TRUE_DIVIDE:
1343 return -1;
1344
1345 case SLICE+0:
1346 return 1;
1347 case SLICE+1:
1348 return 0;
1349 case SLICE+2:
1350 return 0;
1351 case SLICE+3:
1352 return -1;
1353
1354 case STORE_SLICE+0:
1355 return -2;
1356 case STORE_SLICE+1:
1357 return -3;
1358 case STORE_SLICE+2:
1359 return -3;
1360 case STORE_SLICE+3:
1361 return -4;
1362
1363 case DELETE_SLICE+0:
1364 return -1;
1365 case DELETE_SLICE+1:
1366 return -2;
1367 case DELETE_SLICE+2:
1368 return -2;
1369 case DELETE_SLICE+3:
1370 return -3;
1371
1372 case INPLACE_ADD:
1373 case INPLACE_SUBTRACT:
1374 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375 case INPLACE_MODULO:
1376 return -1;
1377 case STORE_SUBSCR:
1378 return -3;
1379 case DELETE_SUBSCR:
1380 return -2;
1381
1382 case BINARY_LSHIFT:
1383 case BINARY_RSHIFT:
1384 case BINARY_AND:
1385 case BINARY_XOR:
1386 case BINARY_OR:
1387 return -1;
1388 case INPLACE_POWER:
1389 return -1;
1390 case GET_ITER:
1391 return 0;
1392
1393 case PRINT_EXPR:
1394 return -1;
1395 case PRINT_ITEM:
1396 return -1;
1397 case PRINT_NEWLINE:
1398 return 0;
1399 case PRINT_ITEM_TO:
1400 return -2;
1401 case PRINT_NEWLINE_TO:
1402 return -1;
1403 case INPLACE_LSHIFT:
1404 case INPLACE_RSHIFT:
1405 case INPLACE_AND:
1406 case INPLACE_XOR:
1407 case INPLACE_OR:
1408 return -1;
1409 case BREAK_LOOP:
1410 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001411 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001412 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001413 case LOAD_LOCALS:
1414 return 1;
1415 case RETURN_VALUE:
1416 return -1;
1417 case IMPORT_STAR:
1418 return -1;
1419 case EXEC_STMT:
1420 return -3;
1421 case YIELD_VALUE:
1422 return 0;
1423
1424 case POP_BLOCK:
1425 return 0;
1426 case END_FINALLY:
1427 return -1; /* or -2 or -3 if exception occurred */
1428 case BUILD_CLASS:
1429 return -2;
1430
1431 case STORE_NAME:
1432 return -1;
1433 case DELETE_NAME:
1434 return 0;
1435 case UNPACK_SEQUENCE:
1436 return oparg-1;
1437 case FOR_ITER:
1438 return 1;
1439
1440 case STORE_ATTR:
1441 return -2;
1442 case DELETE_ATTR:
1443 return -1;
1444 case STORE_GLOBAL:
1445 return -1;
1446 case DELETE_GLOBAL:
1447 return 0;
1448 case DUP_TOPX:
1449 return oparg;
1450 case LOAD_CONST:
1451 return 1;
1452 case LOAD_NAME:
1453 return 1;
1454 case BUILD_TUPLE:
1455 case BUILD_LIST:
1456 return 1-oparg;
1457 case BUILD_MAP:
1458 return 1;
1459 case LOAD_ATTR:
1460 return 0;
1461 case COMPARE_OP:
1462 return -1;
1463 case IMPORT_NAME:
1464 return 0;
1465 case IMPORT_FROM:
1466 return 1;
1467
1468 case JUMP_FORWARD:
1469 case JUMP_IF_FALSE:
1470 case JUMP_IF_TRUE:
1471 case JUMP_ABSOLUTE:
1472 return 0;
1473
1474 case LOAD_GLOBAL:
1475 return 1;
1476
1477 case CONTINUE_LOOP:
1478 return 0;
1479 case SETUP_LOOP:
1480 return 0;
1481 case SETUP_EXCEPT:
1482 case SETUP_FINALLY:
1483 return 3; /* actually pushed by an exception */
1484
1485 case LOAD_FAST:
1486 return 1;
1487 case STORE_FAST:
1488 return -1;
1489 case DELETE_FAST:
1490 return 0;
1491
1492 case RAISE_VARARGS:
1493 return -oparg;
1494#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1495 case CALL_FUNCTION:
1496 return -NARGS(oparg);
1497 case CALL_FUNCTION_VAR:
1498 case CALL_FUNCTION_KW:
1499 return -NARGS(oparg)-1;
1500 case CALL_FUNCTION_VAR_KW:
1501 return -NARGS(oparg)-2;
1502#undef NARGS
1503 case MAKE_FUNCTION:
1504 return -oparg;
1505 case BUILD_SLICE:
1506 if (oparg == 3)
1507 return -2;
1508 else
1509 return -1;
1510
1511 case MAKE_CLOSURE:
1512 return -oparg;
1513 case LOAD_CLOSURE:
1514 return 1;
1515 case LOAD_DEREF:
1516 return 1;
1517 case STORE_DEREF:
1518 return -1;
1519 default:
1520 fprintf(stderr, "opcode = %d\n", opcode);
1521 Py_FatalError("opcode_stack_effect()");
1522
1523 }
1524 return 0; /* not reachable */
1525}
1526
1527/* Add an opcode with no argument.
1528 Returns 0 on failure, 1 on success.
1529*/
1530
1531static int
1532compiler_addop(struct compiler *c, int opcode)
1533{
1534 basicblock *b;
1535 struct instr *i;
1536 int off;
1537 off = compiler_next_instr(c, c->u->u_curblock);
1538 if (off < 0)
1539 return 0;
1540 b = c->u->u_curblock;
1541 i = &b->b_instr[off];
1542 i->i_opcode = opcode;
1543 i->i_hasarg = 0;
1544 if (opcode == RETURN_VALUE)
1545 b->b_return = 1;
1546 compiler_set_lineno(c, off);
1547 return 1;
1548}
1549
1550static int
1551compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1552{
1553 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001556 /* necessary to make sure types aren't coerced (e.g., int and long) */
1557 t = PyTuple_Pack(2, o, o->ob_type);
1558 if (t == NULL)
1559 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001560
1561 v = PyDict_GetItem(dict, t);
1562 if (!v) {
1563 arg = PyDict_Size(dict);
1564 v = PyInt_FromLong(arg);
1565 if (!v) {
1566 Py_DECREF(t);
1567 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001568 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001569 if (PyDict_SetItem(dict, t, v) < 0) {
1570 Py_DECREF(t);
1571 Py_DECREF(v);
1572 return -1;
1573 }
1574 Py_DECREF(v);
1575 }
1576 else
1577 arg = PyInt_AsLong(v);
1578 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001579 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001580}
1581
1582static int
1583compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1584 PyObject *o)
1585{
1586 int arg = compiler_add_o(c, dict, o);
1587 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001588 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589 return compiler_addop_i(c, opcode, arg);
1590}
1591
1592static int
1593compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001594 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595{
1596 int arg;
1597 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1598 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001599 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600 arg = compiler_add_o(c, dict, mangled);
1601 Py_DECREF(mangled);
1602 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001603 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604 return compiler_addop_i(c, opcode, arg);
1605}
1606
1607/* Add an opcode with an integer argument.
1608 Returns 0 on failure, 1 on success.
1609*/
1610
1611static int
1612compiler_addop_i(struct compiler *c, int opcode, int oparg)
1613{
1614 struct instr *i;
1615 int off;
1616 off = compiler_next_instr(c, c->u->u_curblock);
1617 if (off < 0)
1618 return 0;
1619 i = &c->u->u_curblock->b_instr[off];
1620 i->i_opcode = opcode;
1621 i->i_oparg = oparg;
1622 i->i_hasarg = 1;
1623 compiler_set_lineno(c, off);
1624 return 1;
1625}
1626
1627static int
1628compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1629{
1630 struct instr *i;
1631 int off;
1632
1633 assert(b != NULL);
1634 off = compiler_next_instr(c, c->u->u_curblock);
1635 if (off < 0)
1636 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 i = &c->u->u_curblock->b_instr[off];
1638 i->i_opcode = opcode;
1639 i->i_target = b;
1640 i->i_hasarg = 1;
1641 if (absolute)
1642 i->i_jabs = 1;
1643 else
1644 i->i_jrel = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001645 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646 return 1;
1647}
1648
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001649/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1650 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651 it as the current block. NEXT_BLOCK() also creates an implicit jump
1652 from the current block to the new block.
1653*/
1654
1655/* XXX The returns inside these macros make it impossible to decref
1656 objects created in the local function.
1657*/
1658
1659
1660#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001661 if (compiler_use_new_block((C)) == NULL) \
1662 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001663}
1664
1665#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001666 if (compiler_next_block((C)) == NULL) \
1667 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668}
1669
1670#define ADDOP(C, OP) { \
1671 if (!compiler_addop((C), (OP))) \
1672 return 0; \
1673}
1674
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001675#define ADDOP_IN_SCOPE(C, OP) { \
1676 if (!compiler_addop((C), (OP))) { \
1677 compiler_exit_scope(c); \
1678 return 0; \
1679 } \
1680}
1681
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682#define ADDOP_O(C, OP, O, TYPE) { \
1683 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1684 return 0; \
1685}
1686
1687#define ADDOP_NAME(C, OP, O, TYPE) { \
1688 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1689 return 0; \
1690}
1691
1692#define ADDOP_I(C, OP, O) { \
1693 if (!compiler_addop_i((C), (OP), (O))) \
1694 return 0; \
1695}
1696
1697#define ADDOP_JABS(C, OP, O) { \
1698 if (!compiler_addop_j((C), (OP), (O), 1)) \
1699 return 0; \
1700}
1701
1702#define ADDOP_JREL(C, OP, O) { \
1703 if (!compiler_addop_j((C), (OP), (O), 0)) \
1704 return 0; \
1705}
1706
1707/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1708 the ASDL name to synthesize the name of the C type and the visit function.
1709*/
1710
1711#define VISIT(C, TYPE, V) {\
1712 if (!compiler_visit_ ## TYPE((C), (V))) \
1713 return 0; \
1714}
1715
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001716#define VISIT_IN_SCOPE(C, TYPE, V) {\
1717 if (!compiler_visit_ ## TYPE((C), (V))) { \
1718 compiler_exit_scope(c); \
1719 return 0; \
1720 } \
1721}
1722
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723#define VISIT_SLICE(C, V, CTX) {\
1724 if (!compiler_visit_slice((C), (V), (CTX))) \
1725 return 0; \
1726}
1727
1728#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001729 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001731 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001732 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001733 if (!compiler_visit_ ## TYPE((C), elt)) \
1734 return 0; \
1735 } \
1736}
1737
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001738#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001739 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001740 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001741 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001742 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001743 if (!compiler_visit_ ## TYPE((C), elt)) { \
1744 compiler_exit_scope(c); \
1745 return 0; \
1746 } \
1747 } \
1748}
1749
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750static int
1751compiler_isdocstring(stmt_ty s)
1752{
1753 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001754 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001755 return s->v.Expr.value->kind == Str_kind;
1756}
1757
1758/* Compile a sequence of statements, checking for a docstring. */
1759
1760static int
1761compiler_body(struct compiler *c, asdl_seq *stmts)
1762{
1763 int i = 0;
1764 stmt_ty st;
1765
1766 if (!asdl_seq_LEN(stmts))
1767 return 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001768 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769 if (compiler_isdocstring(st)) {
1770 i = 1;
1771 VISIT(c, expr, st->v.Expr.value);
1772 if (!compiler_nameop(c, __doc__, Store))
1773 return 0;
1774 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001775 for (; i < asdl_seq_LEN(stmts); i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001776 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777 return 1;
1778}
1779
1780static PyCodeObject *
1781compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001782{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001783 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001784 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 static PyObject *module;
1786 if (!module) {
1787 module = PyString_FromString("<module>");
1788 if (!module)
1789 return NULL;
1790 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1792 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001793 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 switch (mod->kind) {
1795 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001796 if (!compiler_body(c, mod->v.Module.body)) {
1797 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001799 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 break;
1801 case Interactive_kind:
1802 c->c_interactive = 1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001803 VISIT_SEQ_IN_SCOPE(c, stmt,
1804 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805 break;
1806 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001807 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001808 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 break;
1810 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001811 PyErr_SetString(PyExc_SystemError,
1812 "suite should not be possible");
1813 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001814 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001815 PyErr_Format(PyExc_SystemError,
1816 "module kind %d should not be possible",
1817 mod->kind);
1818 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001819 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820 co = assemble(c, addNone);
1821 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001822 return co;
1823}
1824
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825/* The test for LOCAL must come before the test for FREE in order to
1826 handle classes where name is both local and free. The local var is
1827 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001828*/
1829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830static int
1831get_ref_type(struct compiler *c, PyObject *name)
1832{
1833 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001834 if (scope == 0) {
1835 char buf[350];
1836 PyOS_snprintf(buf, sizeof(buf),
1837 "unknown scope for %.100s in %.100s(%s) in %s\n"
1838 "symbols: %s\nlocals: %s\nglobals: %s\n",
1839 PyString_AS_STRING(name),
1840 PyString_AS_STRING(c->u->u_name),
1841 PyObject_REPR(c->u->u_ste->ste_id),
1842 c->c_filename,
1843 PyObject_REPR(c->u->u_ste->ste_symbols),
1844 PyObject_REPR(c->u->u_varnames),
1845 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001846 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001847 Py_FatalError(buf);
1848 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001849
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001850 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851}
1852
1853static int
1854compiler_lookup_arg(PyObject *dict, PyObject *name)
1855{
1856 PyObject *k, *v;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001857 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001859 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001861 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001863 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 return PyInt_AS_LONG(v);
1865}
1866
1867static int
1868compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1869{
1870 int i, free = PyCode_GetNumFree(co);
1871 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001872 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1873 ADDOP_I(c, MAKE_FUNCTION, args);
1874 return 1;
1875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876 for (i = 0; i < free; ++i) {
1877 /* Bypass com_addop_varname because it will generate
1878 LOAD_DEREF but LOAD_CLOSURE is needed.
1879 */
1880 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1881 int arg, reftype;
1882
1883 /* Special case: If a class contains a method with a
1884 free variable that has the same name as a method,
1885 the name will be considered free *and* local in the
1886 class. It should be handled by the closure, as
1887 well as by the normal name loookup logic.
1888 */
1889 reftype = get_ref_type(c, name);
1890 if (reftype == CELL)
1891 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1892 else /* (reftype == FREE) */
1893 arg = compiler_lookup_arg(c->u->u_freevars, name);
1894 if (arg == -1) {
1895 printf("lookup %s in %s %d %d\n"
1896 "freevars of %s: %s\n",
1897 PyObject_REPR(name),
1898 PyString_AS_STRING(c->u->u_name),
1899 reftype, arg,
1900 PyString_AS_STRING(co->co_name),
1901 PyObject_REPR(co->co_freevars));
1902 Py_FatalError("compiler_make_closure()");
1903 }
1904 ADDOP_I(c, LOAD_CLOSURE, arg);
1905 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001906 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001908 ADDOP_I(c, MAKE_CLOSURE, args);
1909 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910}
1911
1912static int
1913compiler_decorators(struct compiler *c, asdl_seq* decos)
1914{
1915 int i;
1916
1917 if (!decos)
1918 return 1;
1919
1920 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001921 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922 }
1923 return 1;
1924}
1925
1926static int
1927compiler_arguments(struct compiler *c, arguments_ty args)
1928{
1929 int i;
1930 int n = asdl_seq_LEN(args->args);
1931 /* Correctly handle nested argument lists */
1932 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001933 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001934 if (arg->kind == Tuple_kind) {
1935 PyObject *id = PyString_FromFormat(".%d", i);
1936 if (id == NULL) {
1937 return 0;
1938 }
1939 if (!compiler_nameop(c, id, Load)) {
1940 Py_DECREF(id);
1941 return 0;
1942 }
1943 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001944 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945 }
1946 }
1947 return 1;
1948}
1949
1950static int
1951compiler_function(struct compiler *c, stmt_ty s)
1952{
1953 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001954 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 arguments_ty args = s->v.FunctionDef.args;
1956 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001957 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 int i, n, docstring;
1959
1960 assert(s->kind == FunctionDef_kind);
1961
1962 if (!compiler_decorators(c, decos))
1963 return 0;
1964 if (args->defaults)
1965 VISIT_SEQ(c, expr, args->defaults);
1966 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1967 s->lineno))
1968 return 0;
1969
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001970 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001971 docstring = compiler_isdocstring(st);
1972 if (docstring)
1973 first_const = st->v.Expr.value->v.Str.s;
1974 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001975 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001976 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001977 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001979 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980 compiler_arguments(c, args);
1981
1982 c->u->u_argcount = asdl_seq_LEN(args->args);
1983 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001984 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001985 for (i = docstring; i < n; i++) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001986 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
1987 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988 }
1989 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001990 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 if (co == NULL)
1992 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001994 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001995 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996
1997 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1998 ADDOP_I(c, CALL_FUNCTION, 1);
1999 }
2000
2001 return compiler_nameop(c, s->v.FunctionDef.name, Store);
2002}
2003
2004static int
2005compiler_class(struct compiler *c, stmt_ty s)
2006{
2007 int n;
2008 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002009 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010 /* push class name on stack, needed by BUILD_CLASS */
2011 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2012 /* push the tuple of base classes on the stack */
2013 n = asdl_seq_LEN(s->v.ClassDef.bases);
2014 if (n > 0)
2015 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
2016 ADDOP_I(c, BUILD_TUPLE, n);
2017 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2018 s->lineno))
2019 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002020 c->u->u_private = s->v.ClassDef.name;
2021 Py_INCREF(c->u->u_private);
2022 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 if (!str || !compiler_nameop(c, str, Load)) {
2024 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002025 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002027 }
2028
2029 Py_DECREF(str);
2030 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002031 if (!str || !compiler_nameop(c, str, Store)) {
2032 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002033 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002035 }
2036 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002038 if (!compiler_body(c, s->v.ClassDef.body)) {
2039 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002041 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002043 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2044 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002045 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002046 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002047 if (co == NULL)
2048 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002049
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002050 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002051 Py_DECREF(co);
2052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053 ADDOP_I(c, CALL_FUNCTION, 0);
2054 ADDOP(c, BUILD_CLASS);
2055 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2056 return 0;
2057 return 1;
2058}
2059
2060static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002061compiler_ifexp(struct compiler *c, expr_ty e)
2062{
2063 basicblock *end, *next;
2064
2065 assert(e->kind == IfExp_kind);
2066 end = compiler_new_block(c);
2067 if (end == NULL)
2068 return 0;
2069 next = compiler_new_block(c);
2070 if (next == NULL)
2071 return 0;
2072 VISIT(c, expr, e->v.IfExp.test);
2073 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2074 ADDOP(c, POP_TOP);
2075 VISIT(c, expr, e->v.IfExp.body);
2076 ADDOP_JREL(c, JUMP_FORWARD, end);
2077 compiler_use_next_block(c, next);
2078 ADDOP(c, POP_TOP);
2079 VISIT(c, expr, e->v.IfExp.orelse);
2080 compiler_use_next_block(c, end);
2081 return 1;
2082}
2083
2084static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085compiler_lambda(struct compiler *c, expr_ty e)
2086{
2087 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002088 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089 arguments_ty args = e->v.Lambda.args;
2090 assert(e->kind == Lambda_kind);
2091
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002092 if (!name) {
2093 name = PyString_InternFromString("<lambda>");
2094 if (!name)
2095 return 0;
2096 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002097
2098 if (args->defaults)
2099 VISIT_SEQ(c, expr, args->defaults);
2100 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2101 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002102
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002103 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002104 compiler_arguments(c, args);
2105
2106 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002107 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2108 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002110 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002111 if (co == NULL)
2112 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002114 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002115 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116
2117 return 1;
2118}
2119
2120static int
2121compiler_print(struct compiler *c, stmt_ty s)
2122{
2123 int i, n;
2124 bool dest;
2125
2126 assert(s->kind == Print_kind);
2127 n = asdl_seq_LEN(s->v.Print.values);
2128 dest = false;
2129 if (s->v.Print.dest) {
2130 VISIT(c, expr, s->v.Print.dest);
2131 dest = true;
2132 }
2133 for (i = 0; i < n; i++) {
2134 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2135 if (dest) {
2136 ADDOP(c, DUP_TOP);
2137 VISIT(c, expr, e);
2138 ADDOP(c, ROT_TWO);
2139 ADDOP(c, PRINT_ITEM_TO);
2140 }
2141 else {
2142 VISIT(c, expr, e);
2143 ADDOP(c, PRINT_ITEM);
2144 }
2145 }
2146 if (s->v.Print.nl) {
2147 if (dest)
2148 ADDOP(c, PRINT_NEWLINE_TO)
2149 else
2150 ADDOP(c, PRINT_NEWLINE)
2151 }
2152 else if (dest)
2153 ADDOP(c, POP_TOP);
2154 return 1;
2155}
2156
2157static int
2158compiler_if(struct compiler *c, stmt_ty s)
2159{
2160 basicblock *end, *next;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002161 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002162 assert(s->kind == If_kind);
2163 end = compiler_new_block(c);
2164 if (end == NULL)
2165 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002166 next = compiler_new_block(c);
2167 if (next == NULL)
2168 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002169
2170 constant = expr_constant(s->v.If.test);
2171 /* constant = 0: "if 0"
2172 * constant = 1: "if 1", "if 2", ...
2173 * constant = -1: rest */
2174 if (constant == 0) {
2175 if (s->v.If.orelse)
2176 VISIT_SEQ(c, stmt, s->v.If.orelse);
2177 } else if (constant == 1) {
2178 VISIT_SEQ(c, stmt, s->v.If.body);
2179 } else {
2180 VISIT(c, expr, s->v.If.test);
2181 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2182 ADDOP(c, POP_TOP);
2183 VISIT_SEQ(c, stmt, s->v.If.body);
2184 ADDOP_JREL(c, JUMP_FORWARD, end);
2185 compiler_use_next_block(c, next);
2186 ADDOP(c, POP_TOP);
2187 if (s->v.If.orelse)
2188 VISIT_SEQ(c, stmt, s->v.If.orelse);
2189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002190 compiler_use_next_block(c, end);
2191 return 1;
2192}
2193
2194static int
2195compiler_for(struct compiler *c, stmt_ty s)
2196{
2197 basicblock *start, *cleanup, *end;
2198
2199 start = compiler_new_block(c);
2200 cleanup = compiler_new_block(c);
2201 end = compiler_new_block(c);
2202 if (start == NULL || end == NULL || cleanup == NULL)
2203 return 0;
2204 ADDOP_JREL(c, SETUP_LOOP, end);
2205 if (!compiler_push_fblock(c, LOOP, start))
2206 return 0;
2207 VISIT(c, expr, s->v.For.iter);
2208 ADDOP(c, GET_ITER);
2209 compiler_use_next_block(c, start);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002210 /* XXX(nnorwitz): is there a better way to handle this?
2211 for loops are special, we want to be able to trace them
2212 each time around, so we need to set an extra line number. */
2213 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214 ADDOP_JREL(c, FOR_ITER, cleanup);
2215 VISIT(c, expr, s->v.For.target);
2216 VISIT_SEQ(c, stmt, s->v.For.body);
2217 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2218 compiler_use_next_block(c, cleanup);
2219 ADDOP(c, POP_BLOCK);
2220 compiler_pop_fblock(c, LOOP, start);
2221 VISIT_SEQ(c, stmt, s->v.For.orelse);
2222 compiler_use_next_block(c, end);
2223 return 1;
2224}
2225
2226static int
2227compiler_while(struct compiler *c, stmt_ty s)
2228{
2229 basicblock *loop, *orelse, *end, *anchor = NULL;
2230 int constant = expr_constant(s->v.While.test);
2231
2232 if (constant == 0)
2233 return 1;
2234 loop = compiler_new_block(c);
2235 end = compiler_new_block(c);
2236 if (constant == -1) {
2237 anchor = compiler_new_block(c);
2238 if (anchor == NULL)
2239 return 0;
2240 }
2241 if (loop == NULL || end == NULL)
2242 return 0;
2243 if (s->v.While.orelse) {
2244 orelse = compiler_new_block(c);
2245 if (orelse == NULL)
2246 return 0;
2247 }
2248 else
2249 orelse = NULL;
2250
2251 ADDOP_JREL(c, SETUP_LOOP, end);
2252 compiler_use_next_block(c, loop);
2253 if (!compiler_push_fblock(c, LOOP, loop))
2254 return 0;
2255 if (constant == -1) {
2256 VISIT(c, expr, s->v.While.test);
2257 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2258 ADDOP(c, POP_TOP);
2259 }
2260 VISIT_SEQ(c, stmt, s->v.While.body);
2261 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2262
2263 /* XXX should the two POP instructions be in a separate block
2264 if there is no else clause ?
2265 */
2266
2267 if (constant == -1) {
2268 compiler_use_next_block(c, anchor);
2269 ADDOP(c, POP_TOP);
2270 ADDOP(c, POP_BLOCK);
2271 }
2272 compiler_pop_fblock(c, LOOP, loop);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002273 if (orelse != NULL) /* what if orelse is just pass? */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274 VISIT_SEQ(c, stmt, s->v.While.orelse);
2275 compiler_use_next_block(c, end);
2276
2277 return 1;
2278}
2279
2280static int
2281compiler_continue(struct compiler *c)
2282{
2283 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2284 int i;
2285
2286 if (!c->u->u_nfblocks)
2287 return compiler_error(c, LOOP_ERROR_MSG);
2288 i = c->u->u_nfblocks - 1;
2289 switch (c->u->u_fblock[i].fb_type) {
2290 case LOOP:
2291 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2292 break;
2293 case EXCEPT:
2294 case FINALLY_TRY:
2295 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2296 ;
2297 if (i == -1)
2298 return compiler_error(c, LOOP_ERROR_MSG);
2299 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2300 break;
2301 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002302 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303 "'continue' not supported inside 'finally' clause");
2304 }
2305
2306 return 1;
2307}
2308
2309/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2310
2311 SETUP_FINALLY L
2312 <code for body>
2313 POP_BLOCK
2314 LOAD_CONST <None>
2315 L: <code for finalbody>
2316 END_FINALLY
2317
2318 The special instructions use the block stack. Each block
2319 stack entry contains the instruction that created it (here
2320 SETUP_FINALLY), the level of the value stack at the time the
2321 block stack entry was created, and a label (here L).
2322
2323 SETUP_FINALLY:
2324 Pushes the current value stack level and the label
2325 onto the block stack.
2326 POP_BLOCK:
2327 Pops en entry from the block stack, and pops the value
2328 stack until its level is the same as indicated on the
2329 block stack. (The label is ignored.)
2330 END_FINALLY:
2331 Pops a variable number of entries from the *value* stack
2332 and re-raises the exception they specify. The number of
2333 entries popped depends on the (pseudo) exception type.
2334
2335 The block stack is unwound when an exception is raised:
2336 when a SETUP_FINALLY entry is found, the exception is pushed
2337 onto the value stack (and the exception condition is cleared),
2338 and the interpreter jumps to the label gotten from the block
2339 stack.
2340*/
2341
2342static int
2343compiler_try_finally(struct compiler *c, stmt_ty s)
2344{
2345 basicblock *body, *end;
2346 body = compiler_new_block(c);
2347 end = compiler_new_block(c);
2348 if (body == NULL || end == NULL)
2349 return 0;
2350
2351 ADDOP_JREL(c, SETUP_FINALLY, end);
2352 compiler_use_next_block(c, body);
2353 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2354 return 0;
2355 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2356 ADDOP(c, POP_BLOCK);
2357 compiler_pop_fblock(c, FINALLY_TRY, body);
2358
2359 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2360 compiler_use_next_block(c, end);
2361 if (!compiler_push_fblock(c, FINALLY_END, end))
2362 return 0;
2363 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2364 ADDOP(c, END_FINALLY);
2365 compiler_pop_fblock(c, FINALLY_END, end);
2366
2367 return 1;
2368}
2369
2370/*
2371 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2372 (The contents of the value stack is shown in [], with the top
2373 at the right; 'tb' is trace-back info, 'val' the exception's
2374 associated value, and 'exc' the exception.)
2375
2376 Value stack Label Instruction Argument
2377 [] SETUP_EXCEPT L1
2378 [] <code for S>
2379 [] POP_BLOCK
2380 [] JUMP_FORWARD L0
2381
2382 [tb, val, exc] L1: DUP )
2383 [tb, val, exc, exc] <evaluate E1> )
2384 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2385 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2386 [tb, val, exc, 1] POP )
2387 [tb, val, exc] POP
2388 [tb, val] <assign to V1> (or POP if no V1)
2389 [tb] POP
2390 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002391 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392
2393 [tb, val, exc, 0] L2: POP
2394 [tb, val, exc] DUP
2395 .............................etc.......................
2396
2397 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002398 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399
2400 [] L0: <next statement>
2401
2402 Of course, parts are not generated if Vi or Ei is not present.
2403*/
2404static int
2405compiler_try_except(struct compiler *c, stmt_ty s)
2406{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002407 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408 int i, n;
2409
2410 body = compiler_new_block(c);
2411 except = compiler_new_block(c);
2412 orelse = compiler_new_block(c);
2413 end = compiler_new_block(c);
2414 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2415 return 0;
2416 ADDOP_JREL(c, SETUP_EXCEPT, except);
2417 compiler_use_next_block(c, body);
2418 if (!compiler_push_fblock(c, EXCEPT, body))
2419 return 0;
2420 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2421 ADDOP(c, POP_BLOCK);
2422 compiler_pop_fblock(c, EXCEPT, body);
2423 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2424 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2425 compiler_use_next_block(c, except);
2426 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002427 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002428 s->v.TryExcept.handlers, i);
2429 if (!handler->type && i < n-1)
2430 return compiler_error(c, "default 'except:' must be last");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002431 c->u->u_lineno_set = false;
2432 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 except = compiler_new_block(c);
2434 if (except == NULL)
2435 return 0;
2436 if (handler->type) {
2437 ADDOP(c, DUP_TOP);
2438 VISIT(c, expr, handler->type);
2439 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2440 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2441 ADDOP(c, POP_TOP);
2442 }
2443 ADDOP(c, POP_TOP);
2444 if (handler->name) {
2445 VISIT(c, expr, handler->name);
2446 }
2447 else {
2448 ADDOP(c, POP_TOP);
2449 }
2450 ADDOP(c, POP_TOP);
2451 VISIT_SEQ(c, stmt, handler->body);
2452 ADDOP_JREL(c, JUMP_FORWARD, end);
2453 compiler_use_next_block(c, except);
2454 if (handler->type)
2455 ADDOP(c, POP_TOP);
2456 }
2457 ADDOP(c, END_FINALLY);
2458 compiler_use_next_block(c, orelse);
2459 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2460 compiler_use_next_block(c, end);
2461 return 1;
2462}
2463
2464static int
2465compiler_import_as(struct compiler *c, identifier name, identifier asname)
2466{
2467 /* The IMPORT_NAME opcode was already generated. This function
2468 merely needs to bind the result to a name.
2469
2470 If there is a dot in name, we need to split it and emit a
2471 LOAD_ATTR for each name.
2472 */
2473 const char *src = PyString_AS_STRING(name);
2474 const char *dot = strchr(src, '.');
2475 if (dot) {
2476 /* Consume the base module name to get the first attribute */
2477 src = dot + 1;
2478 while (dot) {
2479 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002480 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002481 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002482 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002484 if (!attr)
2485 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002487 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 src = dot + 1;
2489 }
2490 }
2491 return compiler_nameop(c, asname, Store);
2492}
2493
2494static int
2495compiler_import(struct compiler *c, stmt_ty s)
2496{
2497 /* The Import node stores a module name like a.b.c as a single
2498 string. This is convenient for all cases except
2499 import a.b.c as d
2500 where we need to parse that string to extract the individual
2501 module names.
2502 XXX Perhaps change the representation to make this case simpler?
2503 */
2504 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002507 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002509 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510
Guido van Rossum45aecf42006-03-15 04:58:47 +00002511 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002512 if (level == NULL)
2513 return 0;
2514
2515 ADDOP_O(c, LOAD_CONST, level, consts);
2516 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002517 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2518 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2519
2520 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002521 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002522 if (!r)
2523 return r;
2524 }
2525 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 identifier tmp = alias->name;
2527 const char *base = PyString_AS_STRING(alias->name);
2528 char *dot = strchr(base, '.');
2529 if (dot)
2530 tmp = PyString_FromStringAndSize(base,
2531 dot - base);
2532 r = compiler_nameop(c, tmp, Store);
2533 if (dot) {
2534 Py_DECREF(tmp);
2535 }
2536 if (!r)
2537 return r;
2538 }
2539 }
2540 return 1;
2541}
2542
2543static int
2544compiler_from_import(struct compiler *c, stmt_ty s)
2545{
2546 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002547
2548 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002549 PyObject *level;
2550
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002551 if (!names)
2552 return 0;
2553
Guido van Rossum45aecf42006-03-15 04:58:47 +00002554 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002555 if (!level) {
2556 Py_DECREF(names);
2557 return 0;
2558 }
2559
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002560 /* build up the names */
2561 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002562 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002563 Py_INCREF(alias->name);
2564 PyTuple_SET_ITEM(names, i, alias->name);
2565 }
2566
2567 if (s->lineno > c->c_future->ff_lineno) {
2568 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2569 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002570 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 Py_DECREF(names);
2572 return compiler_error(c,
2573 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002574 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002575
2576 }
2577 }
2578
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002579 ADDOP_O(c, LOAD_CONST, level, consts);
2580 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002581 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002582 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002583 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2584 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002585 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 identifier store_name;
2587
2588 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2589 assert(n == 1);
2590 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002591 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002592 }
2593
2594 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2595 store_name = alias->name;
2596 if (alias->asname)
2597 store_name = alias->asname;
2598
2599 if (!compiler_nameop(c, store_name, Store)) {
2600 Py_DECREF(names);
2601 return 0;
2602 }
2603 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002604 /* remove imported module */
2605 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606 return 1;
2607}
2608
2609static int
2610compiler_assert(struct compiler *c, stmt_ty s)
2611{
2612 static PyObject *assertion_error = NULL;
2613 basicblock *end;
2614
2615 if (Py_OptimizeFlag)
2616 return 1;
2617 if (assertion_error == NULL) {
2618 assertion_error = PyString_FromString("AssertionError");
2619 if (assertion_error == NULL)
2620 return 0;
2621 }
2622 VISIT(c, expr, s->v.Assert.test);
2623 end = compiler_new_block(c);
2624 if (end == NULL)
2625 return 0;
2626 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2627 ADDOP(c, POP_TOP);
2628 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2629 if (s->v.Assert.msg) {
2630 VISIT(c, expr, s->v.Assert.msg);
2631 ADDOP_I(c, RAISE_VARARGS, 2);
2632 }
2633 else {
2634 ADDOP_I(c, RAISE_VARARGS, 1);
2635 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002636 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 ADDOP(c, POP_TOP);
2638 return 1;
2639}
2640
2641static int
2642compiler_visit_stmt(struct compiler *c, stmt_ty s)
2643{
2644 int i, n;
2645
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002646 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 c->u->u_lineno = s->lineno;
2648 c->u->u_lineno_set = false;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 if (c->u->u_ste->ste_type != FunctionBlock)
2657 return compiler_error(c, "'return' outside function");
2658 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659 VISIT(c, expr, s->v.Return.value);
2660 }
2661 else
2662 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2663 ADDOP(c, RETURN_VALUE);
2664 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 VISIT_SEQ(c, expr, s->v.Delete.targets)
2667 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002668 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669 n = asdl_seq_LEN(s->v.Assign.targets);
2670 VISIT(c, expr, s->v.Assign.value);
2671 for (i = 0; i < n; i++) {
2672 if (i < n - 1)
2673 ADDOP(c, DUP_TOP);
2674 VISIT(c, expr,
2675 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2676 }
2677 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002682 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002684 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002685 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002686 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002688 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 n = 0;
2690 if (s->v.Raise.type) {
2691 VISIT(c, expr, s->v.Raise.type);
2692 n++;
2693 if (s->v.Raise.inst) {
2694 VISIT(c, expr, s->v.Raise.inst);
2695 n++;
2696 if (s->v.Raise.tback) {
2697 VISIT(c, expr, s->v.Raise.tback);
2698 n++;
2699 }
2700 }
2701 }
2702 ADDOP_I(c, RAISE_VARARGS, n);
2703 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002708 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002709 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002713 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002714 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 VISIT(c, expr, s->v.Exec.body);
2716 if (s->v.Exec.globals) {
2717 VISIT(c, expr, s->v.Exec.globals);
2718 if (s->v.Exec.locals) {
2719 VISIT(c, expr, s->v.Exec.locals);
2720 } else {
2721 ADDOP(c, DUP_TOP);
2722 }
2723 } else {
2724 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2725 ADDOP(c, DUP_TOP);
2726 }
2727 ADDOP(c, EXEC_STMT);
2728 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002729 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002731 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 if (c->c_interactive && c->c_nestlevel <= 1) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002733 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 ADDOP(c, PRINT_EXPR);
2735 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002736 else if (s->v.Expr.value->kind != Str_kind &&
2737 s->v.Expr.value->kind != Num_kind) {
2738 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 ADDOP(c, POP_TOP);
2740 }
2741 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002742 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002743 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002744 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002745 if (!c->u->u_nfblocks)
2746 return compiler_error(c, "'break' outside loop");
2747 ADDOP(c, BREAK_LOOP);
2748 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002749 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002751 case With_kind:
2752 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 }
2754 return 1;
2755}
2756
2757static int
2758unaryop(unaryop_ty op)
2759{
2760 switch (op) {
2761 case Invert:
2762 return UNARY_INVERT;
2763 case Not:
2764 return UNARY_NOT;
2765 case UAdd:
2766 return UNARY_POSITIVE;
2767 case USub:
2768 return UNARY_NEGATIVE;
2769 }
2770 return 0;
2771}
2772
2773static int
2774binop(struct compiler *c, operator_ty op)
2775{
2776 switch (op) {
2777 case Add:
2778 return BINARY_ADD;
2779 case Sub:
2780 return BINARY_SUBTRACT;
2781 case Mult:
2782 return BINARY_MULTIPLY;
2783 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002784 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002785 case Mod:
2786 return BINARY_MODULO;
2787 case Pow:
2788 return BINARY_POWER;
2789 case LShift:
2790 return BINARY_LSHIFT;
2791 case RShift:
2792 return BINARY_RSHIFT;
2793 case BitOr:
2794 return BINARY_OR;
2795 case BitXor:
2796 return BINARY_XOR;
2797 case BitAnd:
2798 return BINARY_AND;
2799 case FloorDiv:
2800 return BINARY_FLOOR_DIVIDE;
2801 }
2802 return 0;
2803}
2804
2805static int
2806cmpop(cmpop_ty op)
2807{
2808 switch (op) {
2809 case Eq:
2810 return PyCmp_EQ;
2811 case NotEq:
2812 return PyCmp_NE;
2813 case Lt:
2814 return PyCmp_LT;
2815 case LtE:
2816 return PyCmp_LE;
2817 case Gt:
2818 return PyCmp_GT;
2819 case GtE:
2820 return PyCmp_GE;
2821 case Is:
2822 return PyCmp_IS;
2823 case IsNot:
2824 return PyCmp_IS_NOT;
2825 case In:
2826 return PyCmp_IN;
2827 case NotIn:
2828 return PyCmp_NOT_IN;
2829 }
2830 return PyCmp_BAD;
2831}
2832
2833static int
2834inplace_binop(struct compiler *c, operator_ty op)
2835{
2836 switch (op) {
2837 case Add:
2838 return INPLACE_ADD;
2839 case Sub:
2840 return INPLACE_SUBTRACT;
2841 case Mult:
2842 return INPLACE_MULTIPLY;
2843 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002844 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002845 case Mod:
2846 return INPLACE_MODULO;
2847 case Pow:
2848 return INPLACE_POWER;
2849 case LShift:
2850 return INPLACE_LSHIFT;
2851 case RShift:
2852 return INPLACE_RSHIFT;
2853 case BitOr:
2854 return INPLACE_OR;
2855 case BitXor:
2856 return INPLACE_XOR;
2857 case BitAnd:
2858 return INPLACE_AND;
2859 case FloorDiv:
2860 return INPLACE_FLOOR_DIVIDE;
2861 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002862 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002863 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 return 0;
2865}
2866
2867static int
2868compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2869{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002870 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002871 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2872
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002873 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002874 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002875 /* XXX AugStore isn't used anywhere! */
2876
2877 /* First check for assignment to __debug__. Param? */
2878 if ((ctx == Store || ctx == AugStore || ctx == Del)
2879 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2880 return compiler_error(c, "can not assign to __debug__");
2881 }
2882
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002883 mangled = _Py_Mangle(c->u->u_private, name);
2884 if (!mangled)
2885 return 0;
2886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887 op = 0;
2888 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002889 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890 switch (scope) {
2891 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002892 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002893 optype = OP_DEREF;
2894 break;
2895 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002896 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002897 optype = OP_DEREF;
2898 break;
2899 case LOCAL:
2900 if (c->u->u_ste->ste_type == FunctionBlock)
2901 optype = OP_FAST;
2902 break;
2903 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002904 if (c->u->u_ste->ste_type == FunctionBlock &&
2905 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 optype = OP_GLOBAL;
2907 break;
2908 case GLOBAL_EXPLICIT:
2909 optype = OP_GLOBAL;
2910 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002911 default:
2912 /* scope can be 0 */
2913 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914 }
2915
2916 /* XXX Leave assert here, but handle __doc__ and the like better */
2917 assert(scope || PyString_AS_STRING(name)[0] == '_');
2918
2919 switch (optype) {
2920 case OP_DEREF:
2921 switch (ctx) {
2922 case Load: op = LOAD_DEREF; break;
2923 case Store: op = STORE_DEREF; break;
2924 case AugLoad:
2925 case AugStore:
2926 break;
2927 case Del:
2928 PyErr_Format(PyExc_SyntaxError,
2929 "can not delete variable '%s' referenced "
2930 "in nested scope",
2931 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002932 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002935 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for deref variable");
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 }
2940 break;
2941 case OP_FAST:
2942 switch (ctx) {
2943 case Load: op = LOAD_FAST; break;
2944 case Store: op = STORE_FAST; break;
2945 case Del: op = DELETE_FAST; break;
2946 case AugLoad:
2947 case AugStore:
2948 break;
2949 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002950 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002951 PyErr_SetString(PyExc_SystemError,
2952 "param invalid for local variable");
2953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002955 ADDOP_O(c, op, mangled, varnames);
2956 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957 return 1;
2958 case OP_GLOBAL:
2959 switch (ctx) {
2960 case Load: op = LOAD_GLOBAL; break;
2961 case Store: op = STORE_GLOBAL; break;
2962 case Del: op = DELETE_GLOBAL; break;
2963 case AugLoad:
2964 case AugStore:
2965 break;
2966 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002967 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002968 PyErr_SetString(PyExc_SystemError,
2969 "param invalid for global variable");
2970 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 }
2972 break;
2973 case OP_NAME:
2974 switch (ctx) {
2975 case Load: op = LOAD_NAME; break;
2976 case Store: op = STORE_NAME; break;
2977 case Del: op = DELETE_NAME; break;
2978 case AugLoad:
2979 case AugStore:
2980 break;
2981 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002982 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002983 PyErr_SetString(PyExc_SystemError,
2984 "param invalid for name variable");
2985 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002986 }
2987 break;
2988 }
2989
2990 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002991 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002992 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002993 if (arg < 0)
2994 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002995 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002996}
2997
2998static int
2999compiler_boolop(struct compiler *c, expr_ty e)
3000{
3001 basicblock *end;
3002 int jumpi, i, n;
3003 asdl_seq *s;
3004
3005 assert(e->kind == BoolOp_kind);
3006 if (e->v.BoolOp.op == And)
3007 jumpi = JUMP_IF_FALSE;
3008 else
3009 jumpi = JUMP_IF_TRUE;
3010 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003011 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 return 0;
3013 s = e->v.BoolOp.values;
3014 n = asdl_seq_LEN(s) - 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003015 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 for (i = 0; i < n; ++i) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003017 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003018 ADDOP_JREL(c, jumpi, end);
3019 ADDOP(c, POP_TOP)
3020 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003021 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003022 compiler_use_next_block(c, end);
3023 return 1;
3024}
3025
3026static int
3027compiler_list(struct compiler *c, expr_ty e)
3028{
3029 int n = asdl_seq_LEN(e->v.List.elts);
3030 if (e->v.List.ctx == Store) {
3031 ADDOP_I(c, UNPACK_SEQUENCE, n);
3032 }
3033 VISIT_SEQ(c, expr, e->v.List.elts);
3034 if (e->v.List.ctx == Load) {
3035 ADDOP_I(c, BUILD_LIST, n);
3036 }
3037 return 1;
3038}
3039
3040static int
3041compiler_tuple(struct compiler *c, expr_ty e)
3042{
3043 int n = asdl_seq_LEN(e->v.Tuple.elts);
3044 if (e->v.Tuple.ctx == Store) {
3045 ADDOP_I(c, UNPACK_SEQUENCE, n);
3046 }
3047 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3048 if (e->v.Tuple.ctx == Load) {
3049 ADDOP_I(c, BUILD_TUPLE, n);
3050 }
3051 return 1;
3052}
3053
3054static int
3055compiler_compare(struct compiler *c, expr_ty e)
3056{
3057 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003058 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003059
3060 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3061 VISIT(c, expr, e->v.Compare.left);
3062 n = asdl_seq_LEN(e->v.Compare.ops);
3063 assert(n > 0);
3064 if (n > 1) {
3065 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003066 if (cleanup == NULL)
3067 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003068 VISIT(c, expr,
3069 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070 }
3071 for (i = 1; i < n; i++) {
3072 ADDOP(c, DUP_TOP);
3073 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003075 cmpop((cmpop_ty)(asdl_seq_GET(
3076 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003077 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3078 NEXT_BLOCK(c);
3079 ADDOP(c, POP_TOP);
3080 if (i < (n - 1))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003081 VISIT(c, expr,
3082 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003084 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085 ADDOP_I(c, COMPARE_OP,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003086 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 if (n > 1) {
3088 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003089 if (end == NULL)
3090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 ADDOP_JREL(c, JUMP_FORWARD, end);
3092 compiler_use_next_block(c, cleanup);
3093 ADDOP(c, ROT_TWO);
3094 ADDOP(c, POP_TOP);
3095 compiler_use_next_block(c, end);
3096 }
3097 return 1;
3098}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003099#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003100
3101static int
3102compiler_call(struct compiler *c, expr_ty e)
3103{
3104 int n, code = 0;
3105
3106 VISIT(c, expr, e->v.Call.func);
3107 n = asdl_seq_LEN(e->v.Call.args);
3108 VISIT_SEQ(c, expr, e->v.Call.args);
3109 if (e->v.Call.keywords) {
3110 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3111 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3112 }
3113 if (e->v.Call.starargs) {
3114 VISIT(c, expr, e->v.Call.starargs);
3115 code |= 1;
3116 }
3117 if (e->v.Call.kwargs) {
3118 VISIT(c, expr, e->v.Call.kwargs);
3119 code |= 2;
3120 }
3121 switch (code) {
3122 case 0:
3123 ADDOP_I(c, CALL_FUNCTION, n);
3124 break;
3125 case 1:
3126 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3127 break;
3128 case 2:
3129 ADDOP_I(c, CALL_FUNCTION_KW, n);
3130 break;
3131 case 3:
3132 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3133 break;
3134 }
3135 return 1;
3136}
3137
3138static int
3139compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 asdl_seq *generators, int gen_index,
3141 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142{
3143 /* generate code for the iterator, then each of the ifs,
3144 and then write to the element */
3145
3146 comprehension_ty l;
3147 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149
3150 start = compiler_new_block(c);
3151 skip = compiler_new_block(c);
3152 if_cleanup = compiler_new_block(c);
3153 anchor = compiler_new_block(c);
3154
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003155 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3156 anchor == NULL)
3157 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003159 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160 VISIT(c, expr, l->iter);
3161 ADDOP(c, GET_ITER);
3162 compiler_use_next_block(c, start);
3163 ADDOP_JREL(c, FOR_ITER, anchor);
3164 NEXT_BLOCK(c);
3165 VISIT(c, expr, l->target);
3166
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 n = asdl_seq_LEN(l->ifs);
3169 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003170 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171 VISIT(c, expr, e);
3172 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3173 NEXT_BLOCK(c);
3174 ADDOP(c, POP_TOP);
3175 }
3176
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 if (++gen_index < asdl_seq_LEN(generators))
3178 if (!compiler_listcomp_generator(c, tmpname,
3179 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 /* only append after the last for generator */
3183 if (gen_index >= asdl_seq_LEN(generators)) {
3184 if (!compiler_nameop(c, tmpname, Load))
3185 return 0;
3186 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003187 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003188
3189 compiler_use_next_block(c, skip);
3190 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191 for (i = 0; i < n; i++) {
3192 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 if (i == 0)
3194 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195 ADDOP(c, POP_TOP);
3196 }
3197 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3198 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003199 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003201 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003202 return 0;
3203
3204 return 1;
3205}
3206
3207static int
3208compiler_listcomp(struct compiler *c, expr_ty e)
3209{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212 static identifier append;
3213 asdl_seq *generators = e->v.ListComp.generators;
3214
3215 assert(e->kind == ListComp_kind);
3216 if (!append) {
3217 append = PyString_InternFromString("append");
3218 if (!append)
3219 return 0;
3220 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003221 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 if (!tmp)
3223 return 0;
3224 ADDOP_I(c, BUILD_LIST, 0);
3225 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003227 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3228 e->v.ListComp.elt);
3229 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 return rc;
3231}
3232
3233static int
3234compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 asdl_seq *generators, int gen_index,
3236 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237{
3238 /* generate code for the iterator, then each of the ifs,
3239 and then write to the element */
3240
3241 comprehension_ty ge;
3242 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003243 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
3245 start = compiler_new_block(c);
3246 skip = compiler_new_block(c);
3247 if_cleanup = compiler_new_block(c);
3248 anchor = compiler_new_block(c);
3249 end = compiler_new_block(c);
3250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 anchor == NULL || end == NULL)
3253 return 0;
3254
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003255 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256 ADDOP_JREL(c, SETUP_LOOP, end);
3257 if (!compiler_push_fblock(c, LOOP, start))
3258 return 0;
3259
3260 if (gen_index == 0) {
3261 /* Receive outermost iter as an implicit argument */
3262 c->u->u_argcount = 1;
3263 ADDOP_I(c, LOAD_FAST, 0);
3264 }
3265 else {
3266 /* Sub-iter - calculate on the fly */
3267 VISIT(c, expr, ge->iter);
3268 ADDOP(c, GET_ITER);
3269 }
3270 compiler_use_next_block(c, start);
3271 ADDOP_JREL(c, FOR_ITER, anchor);
3272 NEXT_BLOCK(c);
3273 VISIT(c, expr, ge->target);
3274
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003275 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276 n = asdl_seq_LEN(ge->ifs);
3277 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003278 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279 VISIT(c, expr, e);
3280 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3281 NEXT_BLOCK(c);
3282 ADDOP(c, POP_TOP);
3283 }
3284
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003285 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3287 return 0;
3288
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003289 /* only append after the last 'for' generator */
3290 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291 VISIT(c, expr, elt);
3292 ADDOP(c, YIELD_VALUE);
3293 ADDOP(c, POP_TOP);
3294
3295 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003296 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297 for (i = 0; i < n; i++) {
3298 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003299 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 compiler_use_next_block(c, if_cleanup);
3301
3302 ADDOP(c, POP_TOP);
3303 }
3304 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3305 compiler_use_next_block(c, anchor);
3306 ADDOP(c, POP_BLOCK);
3307 compiler_pop_fblock(c, LOOP, start);
3308 compiler_use_next_block(c, end);
3309
3310 return 1;
3311}
3312
3313static int
3314compiler_genexp(struct compiler *c, expr_ty e)
3315{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003316 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317 PyCodeObject *co;
3318 expr_ty outermost_iter = ((comprehension_ty)
3319 (asdl_seq_GET(e->v.GeneratorExp.generators,
3320 0)))->iter;
3321
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003322 if (!name) {
3323 name = PyString_FromString("<genexpr>");
3324 if (!name)
3325 return 0;
3326 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327
3328 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3329 return 0;
3330 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3331 e->v.GeneratorExp.elt);
3332 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003333 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334 if (co == NULL)
3335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003337 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003338 Py_DECREF(co);
3339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340 VISIT(c, expr, outermost_iter);
3341 ADDOP(c, GET_ITER);
3342 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343
3344 return 1;
3345}
3346
3347static int
3348compiler_visit_keyword(struct compiler *c, keyword_ty k)
3349{
3350 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3351 VISIT(c, expr, k->value);
3352 return 1;
3353}
3354
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003355/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356 whether they are true or false.
3357
3358 Return values: 1 for true, 0 for false, -1 for non-constant.
3359 */
3360
3361static int
3362expr_constant(expr_ty e)
3363{
3364 switch (e->kind) {
3365 case Num_kind:
3366 return PyObject_IsTrue(e->v.Num.n);
3367 case Str_kind:
3368 return PyObject_IsTrue(e->v.Str.s);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003369 case Name_kind:
3370 /* __debug__ is not assignable, so we can optimize
3371 * it away in if and while statements */
3372 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3373 "__debug__") == 0)
3374 return ! Py_OptimizeFlag;
3375 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003376 default:
3377 return -1;
3378 }
3379}
3380
Guido van Rossumc2e20742006-02-27 22:32:47 +00003381/*
3382 Implements the with statement from PEP 343.
3383
3384 The semantics outlined in that PEP are as follows:
3385
3386 with EXPR as VAR:
3387 BLOCK
3388
3389 It is implemented roughly as:
3390
Thomas Wouters477c8d52006-05-27 19:21:47 +00003391 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003392 exit = context.__exit__ # not calling it
3393 value = context.__enter__()
3394 try:
3395 VAR = value # if VAR present in the syntax
3396 BLOCK
3397 finally:
3398 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003399 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003400 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003401 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003402 exit(*exc)
3403 */
3404static int
3405compiler_with(struct compiler *c, stmt_ty s)
3406{
Thomas Wouters477c8d52006-05-27 19:21:47 +00003407 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003408 basicblock *block, *finally;
3409 identifier tmpexit, tmpvalue = NULL;
3410
3411 assert(s->kind == With_kind);
3412
Guido van Rossumc2e20742006-02-27 22:32:47 +00003413 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003414 enter_attr = PyString_InternFromString("__enter__");
3415 if (!enter_attr)
3416 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003417 }
3418 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003419 exit_attr = PyString_InternFromString("__exit__");
3420 if (!exit_attr)
3421 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003422 }
3423
3424 block = compiler_new_block(c);
3425 finally = compiler_new_block(c);
3426 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003427 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003428
3429 /* Create a temporary variable to hold context.__exit__ */
3430 tmpexit = compiler_new_tmpname(c);
3431 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003432 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003433 PyArena_AddPyObject(c->c_arena, tmpexit);
3434
3435 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003436 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003437 We need to do this rather than preserving it on the stack
3438 because SETUP_FINALLY remembers the stack level.
3439 We need to do the assignment *inside* the try/finally
3440 so that context.__exit__() is called when the assignment
3441 fails. But we need to call context.__enter__() *before*
3442 the try/finally so that if it fails we won't call
3443 context.__exit__().
3444 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003445 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003446 if (tmpvalue == NULL)
3447 return 0;
3448 PyArena_AddPyObject(c->c_arena, tmpvalue);
3449 }
3450
Thomas Wouters477c8d52006-05-27 19:21:47 +00003451 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003452 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003453
3454 /* Squirrel away context.__exit__ */
3455 ADDOP(c, DUP_TOP);
3456 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3457 if (!compiler_nameop(c, tmpexit, Store))
3458 return 0;
3459
3460 /* Call context.__enter__() */
3461 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3462 ADDOP_I(c, CALL_FUNCTION, 0);
3463
3464 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003465 /* Store it in tmpvalue */
3466 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003467 return 0;
3468 }
3469 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 /* Discard result from context.__enter__() */
3471 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003472 }
3473
3474 /* Start the try block */
3475 ADDOP_JREL(c, SETUP_FINALLY, finally);
3476
3477 compiler_use_next_block(c, block);
3478 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003479 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003480 }
3481
3482 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003483 /* Bind saved result of context.__enter__() to VAR */
3484 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003485 !compiler_nameop(c, tmpvalue, Del))
3486 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003488 }
3489
3490 /* BLOCK code */
3491 VISIT_SEQ(c, stmt, s->v.With.body);
3492
3493 /* End of try block; start the finally block */
3494 ADDOP(c, POP_BLOCK);
3495 compiler_pop_fblock(c, FINALLY_TRY, block);
3496
3497 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3498 compiler_use_next_block(c, finally);
3499 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003500 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003501
3502 /* Finally block starts; push tmpexit and issue our magic opcode. */
3503 if (!compiler_nameop(c, tmpexit, Load) ||
3504 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003506 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003507
3508 /* Finally block ends. */
3509 ADDOP(c, END_FINALLY);
3510 compiler_pop_fblock(c, FINALLY_END, finally);
3511 return 1;
3512}
3513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514static int
3515compiler_visit_expr(struct compiler *c, expr_ty e)
3516{
3517 int i, n;
3518
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003519 /* If expr e has a different line number than the last expr/stmt,
3520 set a new line number for the next instruction.
3521 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522 if (e->lineno > c->u->u_lineno) {
3523 c->u->u_lineno = e->lineno;
3524 c->u->u_lineno_set = false;
3525 }
3526 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003527 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003529 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 VISIT(c, expr, e->v.BinOp.left);
3531 VISIT(c, expr, e->v.BinOp.right);
3532 ADDOP(c, binop(c, e->v.BinOp.op));
3533 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003534 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 VISIT(c, expr, e->v.UnaryOp.operand);
3536 ADDOP(c, unaryop(e->v.UnaryOp.op));
3537 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003538 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003540 case IfExp_kind:
3541 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003542 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 /* XXX get rid of arg? */
3544 ADDOP_I(c, BUILD_MAP, 0);
3545 n = asdl_seq_LEN(e->v.Dict.values);
3546 /* We must arrange things just right for STORE_SUBSCR.
3547 It wants the stack to look like (value) (dict) (key) */
3548 for (i = 0; i < n; i++) {
3549 ADDOP(c, DUP_TOP);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003550 VISIT(c, expr,
3551 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552 ADDOP(c, ROT_TWO);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003553 VISIT(c, expr,
3554 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 ADDOP(c, STORE_SUBSCR);
3556 }
3557 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003558 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003559 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003560 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 return compiler_genexp(c, e);
3562 case Yield_kind:
3563 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003564 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 /*
3566 for (i = 0; i < c->u->u_nfblocks; i++) {
3567 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3568 return compiler_error(
3569 c, "'yield' not allowed in a 'try' "
3570 "block with a 'finally' clause");
3571 }
3572 */
3573 if (e->v.Yield.value) {
3574 VISIT(c, expr, e->v.Yield.value);
3575 }
3576 else {
3577 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3578 }
3579 ADDOP(c, YIELD_VALUE);
3580 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003581 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003583 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003585 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 VISIT(c, expr, e->v.Repr.value);
3587 ADDOP(c, UNARY_CONVERT);
3588 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003589 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3591 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003592 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3594 break;
3595 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003596 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 if (e->v.Attribute.ctx != AugStore)
3598 VISIT(c, expr, e->v.Attribute.value);
3599 switch (e->v.Attribute.ctx) {
3600 case AugLoad:
3601 ADDOP(c, DUP_TOP);
3602 /* Fall through to load */
3603 case Load:
3604 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3605 break;
3606 case AugStore:
3607 ADDOP(c, ROT_TWO);
3608 /* Fall through to save */
3609 case Store:
3610 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3611 break;
3612 case Del:
3613 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3614 break;
3615 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003616 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003617 PyErr_SetString(PyExc_SystemError,
3618 "param invalid in attribute expression");
3619 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 }
3621 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003622 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 switch (e->v.Subscript.ctx) {
3624 case AugLoad:
3625 VISIT(c, expr, e->v.Subscript.value);
3626 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3627 break;
3628 case Load:
3629 VISIT(c, expr, e->v.Subscript.value);
3630 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3631 break;
3632 case AugStore:
3633 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3634 break;
3635 case Store:
3636 VISIT(c, expr, e->v.Subscript.value);
3637 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3638 break;
3639 case Del:
3640 VISIT(c, expr, e->v.Subscript.value);
3641 VISIT_SLICE(c, e->v.Subscript.slice, Del);
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,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003646 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003647 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 }
3649 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003650 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3652 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003653 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 return compiler_tuple(c, e);
3657 }
3658 return 1;
3659}
3660
3661static int
3662compiler_augassign(struct compiler *c, stmt_ty s)
3663{
3664 expr_ty e = s->v.AugAssign.target;
3665 expr_ty auge;
3666
3667 assert(s->kind == AugAssign_kind);
3668
3669 switch (e->kind) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003670 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003671 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003672 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003673 if (auge == NULL)
3674 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675 VISIT(c, expr, auge);
3676 VISIT(c, expr, s->v.AugAssign.value);
3677 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3678 auge->v.Attribute.ctx = AugStore;
3679 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003680 break;
3681 case Subscript_kind:
3682 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003683 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003684 if (auge == NULL)
3685 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003686 VISIT(c, expr, auge);
3687 VISIT(c, expr, s->v.AugAssign.value);
3688 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003689 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003690 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003691 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003692 case Name_kind:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003693 if (!compiler_nameop(c, e->v.Name.id, Load))
3694 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003695 VISIT(c, expr, s->v.AugAssign.value);
3696 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3697 return compiler_nameop(c, e->v.Name.id, Store);
3698 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003699 PyErr_Format(PyExc_SystemError,
3700 "invalid node type (%d) for augmented assignment",
3701 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003702 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703 }
3704 return 1;
3705}
3706
3707static int
3708compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3709{
3710 struct fblockinfo *f;
3711 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3712 return 0;
3713 f = &c->u->u_fblock[c->u->u_nfblocks++];
3714 f->fb_type = t;
3715 f->fb_block = b;
3716 return 1;
3717}
3718
3719static void
3720compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3721{
3722 struct compiler_unit *u = c->u;
3723 assert(u->u_nfblocks > 0);
3724 u->u_nfblocks--;
3725 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3726 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3727}
3728
3729/* Raises a SyntaxError and returns 0.
3730 If something goes wrong, a different exception may be raised.
3731*/
3732
3733static int
3734compiler_error(struct compiler *c, const char *errstr)
3735{
3736 PyObject *loc;
3737 PyObject *u = NULL, *v = NULL;
3738
3739 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3740 if (!loc) {
3741 Py_INCREF(Py_None);
3742 loc = Py_None;
3743 }
3744 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3745 Py_None, loc);
3746 if (!u)
3747 goto exit;
3748 v = Py_BuildValue("(zO)", errstr, u);
3749 if (!v)
3750 goto exit;
3751 PyErr_SetObject(PyExc_SyntaxError, v);
3752 exit:
3753 Py_DECREF(loc);
3754 Py_XDECREF(u);
3755 Py_XDECREF(v);
3756 return 0;
3757}
3758
3759static int
3760compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003763 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765 /* XXX this code is duplicated */
3766 switch (ctx) {
3767 case AugLoad: /* fall through to Load */
3768 case Load: op = BINARY_SUBSCR; break;
3769 case AugStore:/* fall through to Store */
3770 case Store: op = STORE_SUBSCR; break;
3771 case Del: op = DELETE_SUBSCR; break;
3772 case Param:
3773 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003774 "invalid %s kind %d in subscript\n",
3775 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003776 return 0;
3777 }
3778 if (ctx == AugLoad) {
3779 ADDOP_I(c, DUP_TOPX, 2);
3780 }
3781 else if (ctx == AugStore) {
3782 ADDOP(c, ROT_THREE);
3783 }
3784 ADDOP(c, op);
3785 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003786}
3787
3788static int
3789compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3790{
3791 int n = 2;
3792 assert(s->kind == Slice_kind);
3793
3794 /* only handles the cases where BUILD_SLICE is emitted */
3795 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003796 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003797 }
3798 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003799 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003801
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003803 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804 }
3805 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003806 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807 }
3808
3809 if (s->v.Slice.step) {
3810 n++;
3811 VISIT(c, expr, s->v.Slice.step);
3812 }
3813 ADDOP_I(c, BUILD_SLICE, n);
3814 return 1;
3815}
3816
3817static int
3818compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3819{
3820 int op = 0, slice_offset = 0, stack_count = 0;
3821
3822 assert(s->v.Slice.step == NULL);
3823 if (s->v.Slice.lower) {
3824 slice_offset++;
3825 stack_count++;
3826 if (ctx != AugStore)
3827 VISIT(c, expr, s->v.Slice.lower);
3828 }
3829 if (s->v.Slice.upper) {
3830 slice_offset += 2;
3831 stack_count++;
3832 if (ctx != AugStore)
3833 VISIT(c, expr, s->v.Slice.upper);
3834 }
3835
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003836 if (ctx == AugLoad) {
3837 switch (stack_count) {
3838 case 0: ADDOP(c, DUP_TOP); break;
3839 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3840 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3841 }
3842 }
3843 else if (ctx == AugStore) {
3844 switch (stack_count) {
3845 case 0: ADDOP(c, ROT_TWO); break;
3846 case 1: ADDOP(c, ROT_THREE); break;
3847 case 2: ADDOP(c, ROT_FOUR); break;
3848 }
3849 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850
3851 switch (ctx) {
3852 case AugLoad: /* fall through to Load */
3853 case Load: op = SLICE; break;
3854 case AugStore:/* fall through to Store */
3855 case Store: op = STORE_SLICE; break;
3856 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003857 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003858 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003859 PyErr_SetString(PyExc_SystemError,
3860 "param invalid in simple slice");
3861 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003862 }
3863
3864 ADDOP(c, op + slice_offset);
3865 return 1;
3866}
3867
3868static int
3869compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3870 expr_context_ty ctx)
3871{
3872 switch (s->kind) {
3873 case Ellipsis_kind:
3874 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3875 break;
3876 case Slice_kind:
3877 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 case Index_kind:
3879 VISIT(c, expr, s->v.Index.value);
3880 break;
3881 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003882 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003883 PyErr_SetString(PyExc_SystemError,
3884 "extended slice invalid in nested slice");
3885 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 }
3887 return 1;
3888}
3889
3890
3891static int
3892compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3893{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003894 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003895 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003896 case Index_kind:
3897 kindname = "index";
3898 if (ctx != AugStore) {
3899 VISIT(c, expr, s->v.Index.value);
3900 }
3901 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003902 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003903 kindname = "ellipsis";
3904 if (ctx != AugStore) {
3905 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3906 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003907 break;
3908 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003909 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 if (!s->v.Slice.step)
3911 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003912 if (ctx != AugStore) {
3913 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914 return 0;
3915 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003916 break;
3917 case ExtSlice_kind:
3918 kindname = "extended slice";
3919 if (ctx != AugStore) {
3920 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3921 for (i = 0; i < n; i++) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003922 slice_ty sub = (slice_ty)asdl_seq_GET(
3923 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003924 if (!compiler_visit_nested_slice(c, sub, ctx))
3925 return 0;
3926 }
3927 ADDOP_I(c, BUILD_TUPLE, n);
3928 }
3929 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003930 default:
3931 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003932 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003933 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003935 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936}
3937
3938/* do depth-first search of basic block graph, starting with block.
3939 post records the block indices in post-order.
3940
3941 XXX must handle implicit jumps from one block to next
3942*/
3943
3944static void
3945dfs(struct compiler *c, basicblock *b, struct assembler *a)
3946{
3947 int i;
3948 struct instr *instr = NULL;
3949
3950 if (b->b_seen)
3951 return;
3952 b->b_seen = 1;
3953 if (b->b_next != NULL)
3954 dfs(c, b->b_next, a);
3955 for (i = 0; i < b->b_iused; i++) {
3956 instr = &b->b_instr[i];
3957 if (instr->i_jrel || instr->i_jabs)
3958 dfs(c, instr->i_target, a);
3959 }
3960 a->a_postorder[a->a_nblocks++] = b;
3961}
3962
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003963static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3965{
3966 int i;
3967 struct instr *instr;
3968 if (b->b_seen || b->b_startdepth >= depth)
3969 return maxdepth;
3970 b->b_seen = 1;
3971 b->b_startdepth = depth;
3972 for (i = 0; i < b->b_iused; i++) {
3973 instr = &b->b_instr[i];
3974 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3975 if (depth > maxdepth)
3976 maxdepth = depth;
3977 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3978 if (instr->i_jrel || instr->i_jabs) {
3979 maxdepth = stackdepth_walk(c, instr->i_target,
3980 depth, maxdepth);
3981 if (instr->i_opcode == JUMP_ABSOLUTE ||
3982 instr->i_opcode == JUMP_FORWARD) {
3983 goto out; /* remaining code is dead */
3984 }
3985 }
3986 }
3987 if (b->b_next)
3988 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3989out:
3990 b->b_seen = 0;
3991 return maxdepth;
3992}
3993
3994/* Find the flow path that needs the largest stack. We assume that
3995 * cycles in the flow graph have no net effect on the stack depth.
3996 */
3997static int
3998stackdepth(struct compiler *c)
3999{
4000 basicblock *b, *entryblock;
4001 entryblock = NULL;
4002 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4003 b->b_seen = 0;
4004 b->b_startdepth = INT_MIN;
4005 entryblock = b;
4006 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004007 if (!entryblock)
4008 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004009 return stackdepth_walk(c, entryblock, 0, 0);
4010}
4011
4012static int
4013assemble_init(struct assembler *a, int nblocks, int firstlineno)
4014{
4015 memset(a, 0, sizeof(struct assembler));
4016 a->a_lineno = firstlineno;
4017 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4018 if (!a->a_bytecode)
4019 return 0;
4020 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4021 if (!a->a_lnotab)
4022 return 0;
4023 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004024 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004025 if (!a->a_postorder) {
4026 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004027 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004028 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004029 return 1;
4030}
4031
4032static void
4033assemble_free(struct assembler *a)
4034{
4035 Py_XDECREF(a->a_bytecode);
4036 Py_XDECREF(a->a_lnotab);
4037 if (a->a_postorder)
4038 PyObject_Free(a->a_postorder);
4039}
4040
4041/* Return the size of a basic block in bytes. */
4042
4043static int
4044instrsize(struct instr *instr)
4045{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004046 if (!instr->i_hasarg)
4047 return 1;
4048 if (instr->i_oparg > 0xffff)
4049 return 6;
4050 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004051}
4052
4053static int
4054blocksize(basicblock *b)
4055{
4056 int i;
4057 int size = 0;
4058
4059 for (i = 0; i < b->b_iused; i++)
4060 size += instrsize(&b->b_instr[i]);
4061 return size;
4062}
4063
4064/* All about a_lnotab.
4065
4066c_lnotab is an array of unsigned bytes disguised as a Python string.
4067It is used to map bytecode offsets to source code line #s (when needed
4068for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004069
Tim Peters2a7f3842001-06-09 09:26:21 +00004070The array is conceptually a list of
4071 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004072pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004073
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004074 byte code offset source code line number
4075 0 1
4076 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004077 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004078 350 307
4079 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004080
4081The first trick is that these numbers aren't stored, only the increments
4082from one row to the next (this doesn't really work, but it's a start):
4083
4084 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4085
4086The second trick is that an unsigned byte can't hold negative values, or
4087values larger than 255, so (a) there's a deep assumption that byte code
4088offsets and their corresponding line #s both increase monotonically, and (b)
4089if at least one column jumps by more than 255 from one row to the next, more
4090than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004091from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004092part. A user of c_lnotab desiring to find the source line number
4093corresponding to a bytecode address A should do something like this
4094
4095 lineno = addr = 0
4096 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004097 addr += addr_incr
4098 if addr > A:
4099 return lineno
4100 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004101
4102In order for this to work, when the addr field increments by more than 255,
4103the line # increment in each pair generated must be 0 until the remaining addr
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004104increment is < 256. So, in the example above, assemble_lnotab (it used
4105to be called com_set_lineno) should not (as was actually done until 2.2)
4106expand 300, 300 to 255, 255, 45, 45,
4107 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004108*/
4109
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004110static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004112{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113 int d_bytecode, d_lineno;
4114 int len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004115 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004116
4117 d_bytecode = a->a_offset - a->a_lineno_off;
4118 d_lineno = i->i_lineno - a->a_lineno;
4119
4120 assert(d_bytecode >= 0);
4121 assert(d_lineno >= 0);
4122
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004123 /* XXX(nnorwitz): is there a better way to handle this?
4124 for loops are special, we want to be able to trace them
4125 each time around, so we need to set an extra line number. */
4126 if (d_lineno == 0 && i->i_opcode != FOR_ITER)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004127 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004128
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004130 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131 nbytes = a->a_lnotab_off + 2 * ncodes;
4132 len = PyString_GET_SIZE(a->a_lnotab);
4133 if (nbytes >= len) {
4134 if (len * 2 < nbytes)
4135 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004136 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 len *= 2;
4138 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4139 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004140 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004141 lnotab = (unsigned char *)
4142 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004143 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144 *lnotab++ = 255;
4145 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004146 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 d_bytecode -= ncodes * 255;
4148 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004149 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150 assert(d_bytecode <= 255);
4151 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004152 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 nbytes = a->a_lnotab_off + 2 * ncodes;
4154 len = PyString_GET_SIZE(a->a_lnotab);
4155 if (nbytes >= len) {
4156 if (len * 2 < nbytes)
4157 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004158 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 len *= 2;
4160 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4161 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004162 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004163 lnotab = (unsigned char *)
4164 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 *lnotab++ = d_bytecode;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004166 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004168 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 *lnotab++ = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004170 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004171 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172 d_lineno -= ncodes * 255;
4173 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004174 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 len = PyString_GET_SIZE(a->a_lnotab);
4177 if (a->a_lnotab_off + 2 >= len) {
4178 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004179 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004180 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004181 lnotab = (unsigned char *)
4182 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004183
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 a->a_lnotab_off += 2;
4185 if (d_bytecode) {
4186 *lnotab++ = d_bytecode;
4187 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004188 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004189 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 *lnotab++ = 0;
4191 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004192 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193 a->a_lineno = i->i_lineno;
4194 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004195 return 1;
4196}
4197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198/* assemble_emit()
4199 Extend the bytecode with a new instruction.
4200 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004201*/
4202
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004203static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004205{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004206 int size, arg = 0, ext = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004207 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004208 char *code;
4209
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004210 size = instrsize(i);
4211 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004213 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004216 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004217 if (a->a_offset + size >= len) {
4218 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004219 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4222 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004223 if (size == 6) {
4224 assert(i->i_hasarg);
4225 *code++ = (char)EXTENDED_ARG;
4226 *code++ = ext & 0xff;
4227 *code++ = ext >> 8;
4228 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004229 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004230 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004231 if (i->i_hasarg) {
4232 assert(size == 3 || size == 6);
4233 *code++ = arg & 0xff;
4234 *code++ = arg >> 8;
4235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004237}
4238
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004239static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004241{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004242 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004243 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004244 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004245
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246 /* Compute the size of each block and fixup jump args.
4247 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004248start:
4249 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004250 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004251 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252 bsize = blocksize(b);
4253 b->b_offset = totsize;
4254 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004255 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004256 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004257 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4258 bsize = b->b_offset;
4259 for (i = 0; i < b->b_iused; i++) {
4260 struct instr *instr = &b->b_instr[i];
4261 /* Relative jumps are computed relative to
4262 the instruction pointer after fetching
4263 the jump instruction.
4264 */
4265 bsize += instrsize(instr);
4266 if (instr->i_jabs)
4267 instr->i_oparg = instr->i_target->b_offset;
4268 else if (instr->i_jrel) {
4269 int delta = instr->i_target->b_offset - bsize;
4270 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004271 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004272 else
4273 continue;
4274 if (instr->i_oparg > 0xffff)
4275 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004276 }
4277 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004278
4279 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004280 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004281 with a better solution.
4282
4283 In the meantime, should the goto be dropped in favor
4284 of a loop?
4285
4286 The issue is that in the first loop blocksize() is called
4287 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004288 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004289 i_oparg is calculated in the second loop above.
4290
4291 So we loop until we stop seeing new EXTENDED_ARGs.
4292 The only EXTENDED_ARGs that could be popping up are
4293 ones in jump instructions. So this should converge
4294 fairly quickly.
4295 */
4296 if (last_extended_arg_count != extended_arg_count) {
4297 last_extended_arg_count = extended_arg_count;
4298 goto start;
4299 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004300}
4301
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004302static PyObject *
4303dict_keys_inorder(PyObject *dict, int offset)
4304{
4305 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004306 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004307
4308 tuple = PyTuple_New(size);
4309 if (tuple == NULL)
4310 return NULL;
4311 while (PyDict_Next(dict, &pos, &k, &v)) {
4312 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004313 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004314 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004315 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004316 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004317 PyTuple_SET_ITEM(tuple, i - offset, k);
4318 }
4319 return tuple;
4320}
4321
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004322static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004324{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 PySTEntryObject *ste = c->u->u_ste;
4326 int flags = 0, n;
4327 if (ste->ste_type != ModuleBlock)
4328 flags |= CO_NEWLOCALS;
4329 if (ste->ste_type == FunctionBlock) {
4330 if (!ste->ste_unoptimized)
4331 flags |= CO_OPTIMIZED;
4332 if (ste->ste_nested)
4333 flags |= CO_NESTED;
4334 if (ste->ste_generator)
4335 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004337 if (ste->ste_varargs)
4338 flags |= CO_VARARGS;
4339 if (ste->ste_varkeywords)
4340 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004341 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004343
4344 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004345 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004346
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347 n = PyDict_Size(c->u->u_freevars);
4348 if (n < 0)
4349 return -1;
4350 if (n == 0) {
4351 n = PyDict_Size(c->u->u_cellvars);
4352 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004353 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004354 if (n == 0) {
4355 flags |= CO_NOFREE;
4356 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004357 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004358
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004359 return flags;
4360}
4361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004362static PyCodeObject *
4363makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004364{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365 PyObject *tmp;
4366 PyCodeObject *co = NULL;
4367 PyObject *consts = NULL;
4368 PyObject *names = NULL;
4369 PyObject *varnames = NULL;
4370 PyObject *filename = NULL;
4371 PyObject *name = NULL;
4372 PyObject *freevars = NULL;
4373 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004374 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004375 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004376
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004377 tmp = dict_keys_inorder(c->u->u_consts, 0);
4378 if (!tmp)
4379 goto error;
4380 consts = PySequence_List(tmp); /* optimize_code requires a list */
4381 Py_DECREF(tmp);
4382
4383 names = dict_keys_inorder(c->u->u_names, 0);
4384 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4385 if (!consts || !names || !varnames)
4386 goto error;
4387
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004388 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4389 if (!cellvars)
4390 goto error;
4391 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4392 if (!freevars)
4393 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394 filename = PyString_FromString(c->c_filename);
4395 if (!filename)
4396 goto error;
4397
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004398 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004399 flags = compute_code_flags(c);
4400 if (flags < 0)
4401 goto error;
4402
4403 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4404 if (!bytecode)
4405 goto error;
4406
4407 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4408 if (!tmp)
4409 goto error;
4410 Py_DECREF(consts);
4411 consts = tmp;
4412
4413 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4414 bytecode, consts, names, varnames,
4415 freevars, cellvars,
4416 filename, c->u->u_name,
4417 c->u->u_firstlineno,
4418 a->a_lnotab);
4419 error:
4420 Py_XDECREF(consts);
4421 Py_XDECREF(names);
4422 Py_XDECREF(varnames);
4423 Py_XDECREF(filename);
4424 Py_XDECREF(name);
4425 Py_XDECREF(freevars);
4426 Py_XDECREF(cellvars);
4427 Py_XDECREF(bytecode);
4428 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004429}
4430
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004431
4432/* For debugging purposes only */
4433#if 0
4434static void
4435dump_instr(const struct instr *i)
4436{
4437 const char *jrel = i->i_jrel ? "jrel " : "";
4438 const char *jabs = i->i_jabs ? "jabs " : "";
4439 char arg[128];
4440
4441 *arg = '\0';
4442 if (i->i_hasarg)
4443 sprintf(arg, "arg: %d ", i->i_oparg);
4444
4445 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4446 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4447}
4448
4449static void
4450dump_basicblock(const basicblock *b)
4451{
4452 const char *seen = b->b_seen ? "seen " : "";
4453 const char *b_return = b->b_return ? "return " : "";
4454 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4455 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4456 if (b->b_instr) {
4457 int i;
4458 for (i = 0; i < b->b_iused; i++) {
4459 fprintf(stderr, " [%02d] ", i);
4460 dump_instr(b->b_instr + i);
4461 }
4462 }
4463}
4464#endif
4465
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004466static PyCodeObject *
4467assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004468{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004469 basicblock *b, *entryblock;
4470 struct assembler a;
4471 int i, j, nblocks;
4472 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004474 /* Make sure every block that falls off the end returns None.
4475 XXX NEXT_BLOCK() isn't quite right, because if the last
4476 block ends with a jump or return b_next shouldn't set.
4477 */
4478 if (!c->u->u_curblock->b_return) {
4479 NEXT_BLOCK(c);
4480 if (addNone)
4481 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4482 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004483 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004484
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004485 nblocks = 0;
4486 entryblock = NULL;
4487 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4488 nblocks++;
4489 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004490 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004491
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004492 /* Set firstlineno if it wasn't explicitly set. */
4493 if (!c->u->u_firstlineno) {
4494 if (entryblock && entryblock->b_instr)
4495 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4496 else
4497 c->u->u_firstlineno = 1;
4498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004499 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4500 goto error;
4501 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004502
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004503 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004504 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004506 /* Emit code in reverse postorder from dfs. */
4507 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004508 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004509 for (j = 0; j < b->b_iused; j++)
4510 if (!assemble_emit(&a, &b->b_instr[j]))
4511 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004512 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4515 goto error;
4516 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4517 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004519 co = makecode(c, &a);
4520 error:
4521 assemble_free(&a);
4522 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004523}