blob: 3ee5cbbd6e93e21be45e910d3040522772697c70 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
146 int c_interactive;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
190
191static int inplace_binop(struct compiler *, operator_ty);
192static int expr_constant(expr_ty e);
193
Guido van Rossumc2e20742006-02-27 22:32:47 +0000194static int compiler_with(struct compiler *, stmt_ty);
195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196static PyCodeObject *assemble(struct compiler *, int addNone);
197static PyObject *__doc__;
198
199PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000200_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000201{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202 /* Name mangling: __private becomes _classname__private.
203 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 const char *p, *name = PyString_AsString(ident);
205 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206 size_t nlen, plen;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000207 if (privateobj == NULL || name == NULL || name[0] != '_' ||
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 name[1] != '_') {
209 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000212 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 nlen = strlen(name);
214 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000215 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 /* Strip leading underscores from class name */
219 while (*p == '_')
220 p++;
221 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000222 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
227 if (!ident)
228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000230 buffer = PyString_AS_STRING(ident);
231 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232 strncpy(buffer+1, p, plen);
233 strcpy(buffer+1+plen, name);
234 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000235}
236
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237static int
238compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000239{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000240 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 c->c_stack = PyList_New(0);
243 if (!c->c_stack)
244 return 0;
245
246 return 1;
247}
248
249PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000250PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000251 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252{
253 struct compiler c;
254 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 PyCompilerFlags local_flags;
256 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000257
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000258 if (!__doc__) {
259 __doc__ = PyString_InternFromString("__doc__");
260 if (!__doc__)
261 return NULL;
262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
264 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000265 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000267 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_future = PyFuture_FromAST(mod, filename);
269 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000270 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000272 local_flags.cf_flags = 0;
273 flags = &local_flags;
274 }
275 merged = c.c_future->ff_features | flags->cf_flags;
276 c.c_future->ff_features = merged;
277 flags->cf_flags = merged;
278 c.c_flags = flags;
279 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000280
281 c.c_st = PySymtable_Build(mod, filename, c.c_future);
282 if (c.c_st == NULL) {
283 if (!PyErr_Occurred())
284 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000285 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286 }
287
288 /* XXX initialize to NULL for now, need to handle */
289 c.c_encoding = NULL;
290
291 co = compiler_mod(&c, mod);
292
Thomas Wouters1175c432006-02-27 22:49:54 +0000293 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000295 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 return co;
297}
298
299PyCodeObject *
300PyNode_Compile(struct _node *n, const char *filename)
301{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000302 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000303 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 mod_ty mod = PyAST_FromNode(n, NULL, filename, arena);
305 if (mod)
306 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000307 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000308 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000309}
310
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000311static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000313{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000314 if (c->c_st)
315 PySymtable_Free(c->c_st);
316 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000317 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000318 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000319}
320
Guido van Rossum79f25d91997-04-29 20:08:16 +0000321static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000323{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000325 PyObject *v, *k;
326 PyObject *dict = PyDict_New();
327 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000328
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329 n = PyList_Size(list);
330 for (i = 0; i < n; i++) {
331 v = PyInt_FromLong(i);
332 if (!v) {
333 Py_DECREF(dict);
334 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000335 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000336 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000337 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
339 Py_XDECREF(k);
340 Py_DECREF(v);
341 Py_DECREF(dict);
342 return NULL;
343 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000344 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000346 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 return dict;
348}
349
350/* Return new dict containing names from src that match scope(s).
351
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000352src is a symbol table dictionary. If the scope of a name matches
353either scope_type or flag is set, insert it into the new dict. The
354values are integers, starting at offset and increasing by one for
355each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356*/
357
358static PyObject *
359dictbytype(PyObject *src, int scope_type, int flag, int offset)
360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362 PyObject *k, *v, *dest = PyDict_New();
363
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 assert(offset >= 0);
365 if (dest == NULL)
366 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
368 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 /* XXX this should probably be a macro in symtable.h */
370 assert(PyInt_Check(v));
371 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
374 PyObject *tuple, *item = PyInt_FromLong(i);
375 if (item == NULL) {
376 Py_DECREF(dest);
377 return NULL;
378 }
379 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000380 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000381 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
382 Py_DECREF(item);
383 Py_DECREF(dest);
384 Py_XDECREF(tuple);
385 return NULL;
386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000388 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390 }
391 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000392}
393
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000394/* Begin: Peephole optimizations ----------------------------------------- */
395
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000396#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000398#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
399#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000400#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define ISBASICBLOCK(blocks, start, bytes) \
403 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000404
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000405/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000407 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000408 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000409 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000410 Bails out with no change if one or more of the LOAD_CONSTs is missing.
411 Also works for BUILD_LIST when followed by an "in" or "not in" test.
412*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413static int
414tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
415{
416 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418
419 /* Pre-conditions */
420 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000421 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000424 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000425
426 /* Buildup new tuple of constants */
427 newconst = PyTuple_New(n);
428 if (newconst == NULL)
429 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 for (i=0 ; i<n ; i++) {
432 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000433 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434 constant = PyList_GET_ITEM(consts, arg);
435 Py_INCREF(constant);
436 PyTuple_SET_ITEM(newconst, i, constant);
437 }
438
439 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 if (PyList_Append(consts, newconst)) {
441 Py_DECREF(newconst);
442 return 0;
443 }
444 Py_DECREF(newconst);
445
446 /* Write NOPs over old LOAD_CONSTS and
447 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
448 memset(codestr, NOP, n*3);
449 codestr[n*3] = LOAD_CONST;
450 SETARG(codestr, (n*3), len_consts);
451 return 1;
452}
453
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000454/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000456 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000458 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000459 Abandons the transformation if the folding fails (i.e. 1+'a').
460 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000461 is below a threshold value. That keeps pyc files from
462 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000463*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000464static int
465fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
466{
467 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468 Py_ssize_t len_consts, size;
469 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000470
471 /* Pre-conditions */
472 assert(PyList_CheckExact(consts));
473 assert(codestr[0] == LOAD_CONST);
474 assert(codestr[3] == LOAD_CONST);
475
476 /* Create new constant */
477 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
478 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
479 opcode = codestr[6];
480 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000481 case BINARY_POWER:
482 newconst = PyNumber_Power(v, w, Py_None);
483 break;
484 case BINARY_MULTIPLY:
485 newconst = PyNumber_Multiply(v, w);
486 break;
487 case BINARY_DIVIDE:
488 /* Cannot fold this operation statically since
489 the result can depend on the run-time presence
490 of the -Qnew flag */
491 return 0;
492 case BINARY_TRUE_DIVIDE:
493 newconst = PyNumber_TrueDivide(v, w);
494 break;
495 case BINARY_FLOOR_DIVIDE:
496 newconst = PyNumber_FloorDivide(v, w);
497 break;
498 case BINARY_MODULO:
499 newconst = PyNumber_Remainder(v, w);
500 break;
501 case BINARY_ADD:
502 newconst = PyNumber_Add(v, w);
503 break;
504 case BINARY_SUBTRACT:
505 newconst = PyNumber_Subtract(v, w);
506 break;
507 case BINARY_SUBSCR:
508 newconst = PyObject_GetItem(v, w);
509 break;
510 case BINARY_LSHIFT:
511 newconst = PyNumber_Lshift(v, w);
512 break;
513 case BINARY_RSHIFT:
514 newconst = PyNumber_Rshift(v, w);
515 break;
516 case BINARY_AND:
517 newconst = PyNumber_And(v, w);
518 break;
519 case BINARY_XOR:
520 newconst = PyNumber_Xor(v, w);
521 break;
522 case BINARY_OR:
523 newconst = PyNumber_Or(v, w);
524 break;
525 default:
526 /* Called with an unknown opcode */
527 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000528 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000529 opcode);
530 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000531 }
532 if (newconst == NULL) {
533 PyErr_Clear();
534 return 0;
535 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000536 size = PyObject_Size(newconst);
537 if (size == -1)
538 PyErr_Clear();
539 else if (size > 20) {
540 Py_DECREF(newconst);
541 return 0;
542 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000543
544 /* Append folded constant into consts table */
545 len_consts = PyList_GET_SIZE(consts);
546 if (PyList_Append(consts, newconst)) {
547 Py_DECREF(newconst);
548 return 0;
549 }
550 Py_DECREF(newconst);
551
552 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
553 memset(codestr, NOP, 4);
554 codestr[4] = LOAD_CONST;
555 SETARG(codestr, 4, len_consts);
556 return 1;
557}
558
Raymond Hettinger80121492005-02-20 12:41:32 +0000559static int
560fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
561{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000562 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563 Py_ssize_t len_consts;
564 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000565
566 /* Pre-conditions */
567 assert(PyList_CheckExact(consts));
568 assert(codestr[0] == LOAD_CONST);
569
570 /* Create new constant */
571 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
572 opcode = codestr[3];
573 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000574 case UNARY_NEGATIVE:
575 /* Preserve the sign of -0.0 */
576 if (PyObject_IsTrue(v) == 1)
577 newconst = PyNumber_Negative(v);
578 break;
579 case UNARY_CONVERT:
580 newconst = PyObject_Repr(v);
581 break;
582 case UNARY_INVERT:
583 newconst = PyNumber_Invert(v);
584 break;
585 default:
586 /* Called with an unknown opcode */
587 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000588 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000589 opcode);
590 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000591 }
592 if (newconst == NULL) {
593 PyErr_Clear();
594 return 0;
595 }
596
597 /* Append folded constant into consts table */
598 len_consts = PyList_GET_SIZE(consts);
599 if (PyList_Append(consts, newconst)) {
600 Py_DECREF(newconst);
601 return 0;
602 }
603 Py_DECREF(newconst);
604
605 /* Write NOP LOAD_CONST newconst */
606 codestr[0] = NOP;
607 codestr[1] = LOAD_CONST;
608 SETARG(codestr, 1, len_consts);
609 return 1;
610}
611
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612static unsigned int *
613markblocks(unsigned char *code, int len)
614{
Anthony Baxter7b782b62006-04-11 12:01:56 +0000615 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000617
618 if (blocks == NULL)
619 return NULL;
620 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000621
622 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000623 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
624 opcode = code[i];
625 switch (opcode) {
626 case FOR_ITER:
627 case JUMP_FORWARD:
628 case JUMP_IF_FALSE:
629 case JUMP_IF_TRUE:
630 case JUMP_ABSOLUTE:
631 case CONTINUE_LOOP:
632 case SETUP_LOOP:
633 case SETUP_EXCEPT:
634 case SETUP_FINALLY:
635 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000636 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000638 }
639 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000640 /* Build block numbers in the second pass */
641 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000642 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000643 blocks[i] = blockcnt;
644 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000645 return blocks;
646}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000647
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000648/* Perform basic peephole optimizations to components of a code object.
649 The consts object should still be in list form to allow new constants
650 to be appended.
651
652 To keep the optimizer simple, it bails out (does nothing) for code
653 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000654 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000655 the lineno table has complex encoding for gaps >= 255.
656
657 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000658 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000659 smaller. For those that reduce size, the gaps are initially filled with
660 NOPs. Later those NOPs are removed and the jump addresses retargeted in
661 a single pass. Line numbering is adjusted accordingly. */
662
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000664optimize_code(PyObject *code, PyObject* consts, PyObject *names,
665 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000666{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000667 Py_ssize_t i, j, codelen;
668 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000669 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000670 unsigned char *codestr = NULL;
671 unsigned char *lineno;
672 int *addrmap = NULL;
673 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000674 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000675 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000676 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000677
Raymond Hettingereffb3932004-10-30 08:55:08 +0000678 /* Bail out if an exception is set */
679 if (PyErr_Occurred())
680 goto exitUnchanged;
681
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000682 /* Bypass optimization when the lineno table is too complex */
683 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000684 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000685 tabsiz = PyString_GET_SIZE(lineno_obj);
686 if (memchr(lineno, 255, tabsiz) != NULL)
687 goto exitUnchanged;
688
Raymond Hettingera12fa142004-08-24 04:34:16 +0000689 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000690 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000692 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000693 goto exitUnchanged;
694
695 /* Make a modifiable copy of the code string */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000696 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000697 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000698 goto exitUnchanged;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000699 codestr = (unsigned char *)memcpy(codestr,
700 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000701
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000702 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000703 the various transformation patterns to look ahead several
704 instructions without additional checks to make sure they are not
705 looking beyond the end of the code string.
706 */
707 if (codestr[codelen-1] != RETURN_VALUE)
708 goto exitUnchanged;
709
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000710 /* Mapping to new jump targets after NOPs are removed */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000711 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000712 if (addrmap == NULL)
713 goto exitUnchanged;
714
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000715 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000716 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000717 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000718 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000719
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000720 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000721 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000722
723 lastlc = cumlc;
724 cumlc = 0;
725
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000726 switch (opcode) {
727
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000728 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
729 with JUMP_IF_TRUE POP_TOP */
730 case UNARY_NOT:
731 if (codestr[i+1] != JUMP_IF_FALSE ||
732 codestr[i+4] != POP_TOP ||
733 !ISBASICBLOCK(blocks,i,5))
734 continue;
735 tgt = GETJUMPTGT(codestr, (i+1));
736 if (codestr[tgt] != POP_TOP)
737 continue;
738 j = GETARG(codestr, i+1) + 1;
739 codestr[i] = JUMP_IF_TRUE;
740 SETARG(codestr, i, j);
741 codestr[i+3] = POP_TOP;
742 codestr[i+4] = NOP;
743 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000744
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000745 /* not a is b --> a is not b
746 not a in b --> a not in b
747 not a is not b --> a is b
748 not a not in b --> a in b
749 */
750 case COMPARE_OP:
751 j = GETARG(codestr, i);
752 if (j < 6 || j > 9 ||
753 codestr[i+3] != UNARY_NOT ||
754 !ISBASICBLOCK(blocks,i,4))
755 continue;
756 SETARG(codestr, i, (j^1));
757 codestr[i+3] = NOP;
758 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000759
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000760 /* Replace LOAD_GLOBAL/LOAD_NAME None
761 with LOAD_CONST None */
762 case LOAD_NAME:
763 case LOAD_GLOBAL:
764 j = GETARG(codestr, i);
765 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
766 if (name == NULL || strcmp(name, "None") != 0)
767 continue;
768 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
769 if (PyList_GET_ITEM(consts, j) == Py_None) {
770 codestr[i] = LOAD_CONST;
771 SETARG(codestr, i, j);
772 cumlc = lastlc + 1;
773 break;
774 }
775 }
776 break;
777
778 /* Skip over LOAD_CONST trueconst
779 JUMP_IF_FALSE xx POP_TOP */
780 case LOAD_CONST:
781 cumlc = lastlc + 1;
782 j = GETARG(codestr, i);
783 if (codestr[i+3] != JUMP_IF_FALSE ||
784 codestr[i+6] != POP_TOP ||
785 !ISBASICBLOCK(blocks,i,7) ||
786 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
787 continue;
788 memset(codestr+i, NOP, 7);
789 cumlc = 0;
790 break;
791
792 /* Try to fold tuples of constants (includes a case for lists
793 which are only used for "in" and "not in" tests).
794 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
795 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
796 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
797 case BUILD_TUPLE:
798 case BUILD_LIST:
799 j = GETARG(codestr, i);
800 h = i - 3 * j;
801 if (h >= 0 &&
802 j <= lastlc &&
803 ((opcode == BUILD_TUPLE &&
804 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
805 (opcode == BUILD_LIST &&
806 codestr[i+3]==COMPARE_OP &&
807 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
808 (GETARG(codestr,i+3)==6 ||
809 GETARG(codestr,i+3)==7))) &&
810 tuple_of_constants(&codestr[h], j, consts)) {
811 assert(codestr[i] == LOAD_CONST);
812 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000813 break;
814 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000815 if (codestr[i+3] != UNPACK_SEQUENCE ||
816 !ISBASICBLOCK(blocks,i,6) ||
817 j != GETARG(codestr, i+3))
818 continue;
819 if (j == 1) {
820 memset(codestr+i, NOP, 6);
821 } else if (j == 2) {
822 codestr[i] = ROT_TWO;
823 memset(codestr+i+1, NOP, 5);
824 } else if (j == 3) {
825 codestr[i] = ROT_THREE;
826 codestr[i+1] = ROT_TWO;
827 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000828 }
829 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000830
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000831 /* Fold binary ops on constants.
832 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
833 case BINARY_POWER:
834 case BINARY_MULTIPLY:
835 case BINARY_TRUE_DIVIDE:
836 case BINARY_FLOOR_DIVIDE:
837 case BINARY_MODULO:
838 case BINARY_ADD:
839 case BINARY_SUBTRACT:
840 case BINARY_SUBSCR:
841 case BINARY_LSHIFT:
842 case BINARY_RSHIFT:
843 case BINARY_AND:
844 case BINARY_XOR:
845 case BINARY_OR:
846 if (lastlc >= 2 &&
847 ISBASICBLOCK(blocks, i-6, 7) &&
848 fold_binops_on_constants(&codestr[i-6], consts)) {
849 i -= 2;
850 assert(codestr[i] == LOAD_CONST);
851 cumlc = 1;
852 }
853 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000854
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000855 /* Fold unary ops on constants.
856 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
857 case UNARY_NEGATIVE:
858 case UNARY_CONVERT:
859 case UNARY_INVERT:
860 if (lastlc >= 1 &&
861 ISBASICBLOCK(blocks, i-3, 4) &&
862 fold_unaryops_on_constants(&codestr[i-3], consts)) {
863 i -= 2;
864 assert(codestr[i] == LOAD_CONST);
865 cumlc = 1;
866 }
867 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000868
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000869 /* Simplify conditional jump to conditional jump where the
870 result of the first test implies the success of a similar
871 test or the failure of the opposite test.
872 Arises in code like:
873 "if a and b:"
874 "if a or b:"
875 "a and b or c"
876 "(a and b) and c"
877 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
878 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
879 where y+3 is the instruction following the second test.
880 */
881 case JUMP_IF_FALSE:
882 case JUMP_IF_TRUE:
883 tgt = GETJUMPTGT(codestr, i);
884 j = codestr[tgt];
885 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
886 if (j == opcode) {
887 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
888 SETARG(codestr, i, tgttgt);
889 } else {
890 tgt -= i;
891 SETARG(codestr, i, tgt);
892 }
893 break;
894 }
895 /* Intentional fallthrough */
896
897 /* Replace jumps to unconditional jumps */
898 case FOR_ITER:
899 case JUMP_FORWARD:
900 case JUMP_ABSOLUTE:
901 case CONTINUE_LOOP:
902 case SETUP_LOOP:
903 case SETUP_EXCEPT:
904 case SETUP_FINALLY:
905 tgt = GETJUMPTGT(codestr, i);
906 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
907 continue;
908 tgttgt = GETJUMPTGT(codestr, tgt);
909 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
910 opcode = JUMP_ABSOLUTE;
911 if (!ABSOLUTE_JUMP(opcode))
912 tgttgt -= i + 3; /* Calc relative jump addr */
913 if (tgttgt < 0) /* No backward relative jumps */
914 continue;
915 codestr[i] = opcode;
916 SETARG(codestr, i, tgttgt);
917 break;
918
919 case EXTENDED_ARG:
920 goto exitUnchanged;
921
922 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
923 case RETURN_VALUE:
924 if (i+4 >= codelen ||
925 codestr[i+4] != RETURN_VALUE ||
926 !ISBASICBLOCK(blocks,i,5))
927 continue;
928 memset(codestr+i+1, NOP, 4);
929 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000930 }
931 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000932
933 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000934 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
935 addrmap[i] = i - nops;
936 if (codestr[i] == NOP)
937 nops++;
938 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000939 cum_orig_line = 0;
940 last_line = 0;
941 for (i=0 ; i < tabsiz ; i+=2) {
942 cum_orig_line += lineno[i];
943 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000944 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000945 lineno[i] =((unsigned char)(new_line - last_line));
946 last_line = new_line;
947 }
948
949 /* Remove NOPs and fixup jump targets */
950 for (i=0, h=0 ; i<codelen ; ) {
951 opcode = codestr[i];
952 switch (opcode) {
953 case NOP:
954 i++;
955 continue;
956
957 case JUMP_ABSOLUTE:
958 case CONTINUE_LOOP:
959 j = addrmap[GETARG(codestr, i)];
960 SETARG(codestr, i, j);
961 break;
962
963 case FOR_ITER:
964 case JUMP_FORWARD:
965 case JUMP_IF_FALSE:
966 case JUMP_IF_TRUE:
967 case SETUP_LOOP:
968 case SETUP_EXCEPT:
969 case SETUP_FINALLY:
970 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
971 SETARG(codestr, i, j);
972 break;
973 }
974 adj = CODESIZE(opcode);
975 while (adj--)
976 codestr[h++] = codestr[i++];
977 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000978 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000979
980 code = PyString_FromStringAndSize((char *)codestr, h);
981 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000982 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000983 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000984 return code;
985
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000986 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000987 if (blocks != NULL)
988 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000989 if (addrmap != NULL)
990 PyMem_Free(addrmap);
991 if (codestr != NULL)
992 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000993 Py_INCREF(code);
994 return code;
995}
996
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000997/* End: Peephole optimizations ----------------------------------------- */
998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000999/*
1000
1001Leave this debugging code for just a little longer.
1002
1003static void
1004compiler_display_symbols(PyObject *name, PyObject *symbols)
1005{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006PyObject *key, *value;
1007int flags;
1008Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001010fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1011while (PyDict_Next(symbols, &pos, &key, &value)) {
1012flags = PyInt_AsLong(value);
1013fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1014if (flags & DEF_GLOBAL)
1015fprintf(stderr, " declared_global");
1016if (flags & DEF_LOCAL)
1017fprintf(stderr, " local");
1018if (flags & DEF_PARAM)
1019fprintf(stderr, " param");
1020if (flags & DEF_STAR)
1021fprintf(stderr, " stararg");
1022if (flags & DEF_DOUBLESTAR)
1023fprintf(stderr, " starstar");
1024if (flags & DEF_INTUPLE)
1025fprintf(stderr, " tuple");
1026if (flags & DEF_FREE)
1027fprintf(stderr, " free");
1028if (flags & DEF_FREE_GLOBAL)
1029fprintf(stderr, " global");
1030if (flags & DEF_FREE_CLASS)
1031fprintf(stderr, " free/class");
1032if (flags & DEF_IMPORT)
1033fprintf(stderr, " import");
1034fprintf(stderr, "\n");
1035}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 fprintf(stderr, "\n");
1037}
1038*/
1039
1040static void
1041compiler_unit_check(struct compiler_unit *u)
1042{
1043 basicblock *block;
1044 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1045 assert(block != (void *)0xcbcbcbcb);
1046 assert(block != (void *)0xfbfbfbfb);
1047 assert(block != (void *)0xdbdbdbdb);
1048 if (block->b_instr != NULL) {
1049 assert(block->b_ialloc > 0);
1050 assert(block->b_iused > 0);
1051 assert(block->b_ialloc >= block->b_iused);
1052 }
1053 else {
1054 assert (block->b_iused == 0);
1055 assert (block->b_ialloc == 0);
1056 }
1057 }
1058}
1059
1060static void
1061compiler_unit_free(struct compiler_unit *u)
1062{
1063 basicblock *b, *next;
1064
1065 compiler_unit_check(u);
1066 b = u->u_blocks;
1067 while (b != NULL) {
1068 if (b->b_instr)
1069 PyObject_Free((void *)b->b_instr);
1070 next = b->b_list;
1071 PyObject_Free((void *)b);
1072 b = next;
1073 }
1074 Py_XDECREF(u->u_ste);
1075 Py_XDECREF(u->u_name);
1076 Py_XDECREF(u->u_consts);
1077 Py_XDECREF(u->u_names);
1078 Py_XDECREF(u->u_varnames);
1079 Py_XDECREF(u->u_freevars);
1080 Py_XDECREF(u->u_cellvars);
1081 Py_XDECREF(u->u_private);
1082 PyObject_Free(u);
1083}
1084
1085static int
1086compiler_enter_scope(struct compiler *c, identifier name, void *key,
1087 int lineno)
1088{
1089 struct compiler_unit *u;
1090
Anthony Baxter7b782b62006-04-11 12:01:56 +00001091 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1092 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001093 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001094 PyErr_NoMemory();
1095 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001096 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 u->u_argcount = 0;
1099 u->u_ste = PySymtable_Lookup(c->c_st, key);
1100 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001101 compiler_unit_free(u);
1102 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103 }
1104 Py_INCREF(name);
1105 u->u_name = name;
1106 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1107 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +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));
Neal Norwitzd12bd012006-07-21 07:59:47 +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);
1142 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001143 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144 return 0;
1145 }
1146 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001147 u->u_private = c->u->u_private;
1148 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149 }
1150 c->u = u;
1151
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001152 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001153 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 return 0;
1155
1156 return 1;
1157}
1158
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001159static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001160compiler_exit_scope(struct compiler *c)
1161{
1162 int n;
1163 PyObject *wrapper;
1164
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001165 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166 compiler_unit_free(c->u);
1167 /* Restore c->u to the parent unit. */
1168 n = PyList_GET_SIZE(c->c_stack) - 1;
1169 if (n >= 0) {
1170 wrapper = PyList_GET_ITEM(c->c_stack, n);
1171 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001172 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001174 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001175 compiler_unit_check(c->u);
1176 }
1177 else
1178 c->u = NULL;
1179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180}
1181
Guido van Rossumc2e20742006-02-27 22:32:47 +00001182/* Allocate a new "anonymous" local variable.
1183 Used by list comprehensions and with statements.
1184*/
1185
1186static PyObject *
1187compiler_new_tmpname(struct compiler *c)
1188{
1189 char tmpname[256];
1190 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1191 return PyString_FromString(tmpname);
1192}
1193
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194/* Allocate a new block and return a pointer to it.
1195 Returns NULL on error.
1196*/
1197
1198static basicblock *
1199compiler_new_block(struct compiler *c)
1200{
1201 basicblock *b;
1202 struct compiler_unit *u;
1203
1204 u = c->u;
1205 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001206 if (b == NULL) {
1207 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001208 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001209 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001211 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212 b->b_list = u->u_blocks;
1213 u->u_blocks = b;
1214 return b;
1215}
1216
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217static basicblock *
1218compiler_use_new_block(struct compiler *c)
1219{
1220 basicblock *block = compiler_new_block(c);
1221 if (block == NULL)
1222 return NULL;
1223 c->u->u_curblock = block;
1224 return block;
1225}
1226
1227static basicblock *
1228compiler_next_block(struct compiler *c)
1229{
1230 basicblock *block = compiler_new_block(c);
1231 if (block == NULL)
1232 return NULL;
1233 c->u->u_curblock->b_next = block;
1234 c->u->u_curblock = block;
1235 return block;
1236}
1237
1238static basicblock *
1239compiler_use_next_block(struct compiler *c, basicblock *block)
1240{
1241 assert(block != NULL);
1242 c->u->u_curblock->b_next = block;
1243 c->u->u_curblock = block;
1244 return block;
1245}
1246
1247/* Returns the offset of the next instruction in the current block's
1248 b_instr array. Resizes the b_instr as necessary.
1249 Returns -1 on failure.
1250 */
1251
1252static int
1253compiler_next_instr(struct compiler *c, basicblock *b)
1254{
1255 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001256 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001257 b->b_instr = (struct instr *)PyObject_Malloc(
1258 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001259 if (b->b_instr == NULL) {
1260 PyErr_NoMemory();
1261 return -1;
1262 }
1263 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1264 memset((char *)b->b_instr, 0,
1265 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001267 else if (b->b_iused == b->b_ialloc) {
1268 size_t oldsize, newsize;
1269 oldsize = b->b_ialloc * sizeof(struct instr);
1270 newsize = oldsize << 1;
1271 if (newsize == 0) {
1272 PyErr_NoMemory();
1273 return -1;
1274 }
1275 b->b_ialloc <<= 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001276 b->b_instr = (struct instr *)PyObject_Realloc(
1277 (void *)b->b_instr, newsize);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278 if (b->b_instr == NULL)
1279 return -1;
1280 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1281 }
1282 return b->b_iused++;
1283}
1284
Jeremy Hylton12603c42006-04-01 16:18:02 +00001285/* Set the i_lineno member of the instruction at offse off if the
1286 line number for the current expression/statement (?) has not
1287 already been set. If it has been set, the call has no effect.
1288
1289 Every time a new node is b
1290 */
1291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001292static void
1293compiler_set_lineno(struct compiler *c, int off)
1294{
1295 basicblock *b;
1296 if (c->u->u_lineno_set)
1297 return;
1298 c->u->u_lineno_set = true;
1299 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001300 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001301}
1302
1303static int
1304opcode_stack_effect(int opcode, int oparg)
1305{
1306 switch (opcode) {
1307 case POP_TOP:
1308 return -1;
1309 case ROT_TWO:
1310 case ROT_THREE:
1311 return 0;
1312 case DUP_TOP:
1313 return 1;
1314 case ROT_FOUR:
1315 return 0;
1316
1317 case UNARY_POSITIVE:
1318 case UNARY_NEGATIVE:
1319 case UNARY_NOT:
1320 case UNARY_CONVERT:
1321 case UNARY_INVERT:
1322 return 0;
1323
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001324 case LIST_APPEND:
1325 return -2;
1326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001327 case BINARY_POWER:
1328 case BINARY_MULTIPLY:
1329 case BINARY_DIVIDE:
1330 case BINARY_MODULO:
1331 case BINARY_ADD:
1332 case BINARY_SUBTRACT:
1333 case BINARY_SUBSCR:
1334 case BINARY_FLOOR_DIVIDE:
1335 case BINARY_TRUE_DIVIDE:
1336 return -1;
1337 case INPLACE_FLOOR_DIVIDE:
1338 case INPLACE_TRUE_DIVIDE:
1339 return -1;
1340
1341 case SLICE+0:
1342 return 1;
1343 case SLICE+1:
1344 return 0;
1345 case SLICE+2:
1346 return 0;
1347 case SLICE+3:
1348 return -1;
1349
1350 case STORE_SLICE+0:
1351 return -2;
1352 case STORE_SLICE+1:
1353 return -3;
1354 case STORE_SLICE+2:
1355 return -3;
1356 case STORE_SLICE+3:
1357 return -4;
1358
1359 case DELETE_SLICE+0:
1360 return -1;
1361 case DELETE_SLICE+1:
1362 return -2;
1363 case DELETE_SLICE+2:
1364 return -2;
1365 case DELETE_SLICE+3:
1366 return -3;
1367
1368 case INPLACE_ADD:
1369 case INPLACE_SUBTRACT:
1370 case INPLACE_MULTIPLY:
1371 case INPLACE_DIVIDE:
1372 case INPLACE_MODULO:
1373 return -1;
1374 case STORE_SUBSCR:
1375 return -3;
1376 case DELETE_SUBSCR:
1377 return -2;
1378
1379 case BINARY_LSHIFT:
1380 case BINARY_RSHIFT:
1381 case BINARY_AND:
1382 case BINARY_XOR:
1383 case BINARY_OR:
1384 return -1;
1385 case INPLACE_POWER:
1386 return -1;
1387 case GET_ITER:
1388 return 0;
1389
1390 case PRINT_EXPR:
1391 return -1;
1392 case PRINT_ITEM:
1393 return -1;
1394 case PRINT_NEWLINE:
1395 return 0;
1396 case PRINT_ITEM_TO:
1397 return -2;
1398 case PRINT_NEWLINE_TO:
1399 return -1;
1400 case INPLACE_LSHIFT:
1401 case INPLACE_RSHIFT:
1402 case INPLACE_AND:
1403 case INPLACE_XOR:
1404 case INPLACE_OR:
1405 return -1;
1406 case BREAK_LOOP:
1407 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001408 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001409 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001410 case LOAD_LOCALS:
1411 return 1;
1412 case RETURN_VALUE:
1413 return -1;
1414 case IMPORT_STAR:
1415 return -1;
1416 case EXEC_STMT:
1417 return -3;
1418 case YIELD_VALUE:
1419 return 0;
1420
1421 case POP_BLOCK:
1422 return 0;
1423 case END_FINALLY:
1424 return -1; /* or -2 or -3 if exception occurred */
1425 case BUILD_CLASS:
1426 return -2;
1427
1428 case STORE_NAME:
1429 return -1;
1430 case DELETE_NAME:
1431 return 0;
1432 case UNPACK_SEQUENCE:
1433 return oparg-1;
1434 case FOR_ITER:
1435 return 1;
1436
1437 case STORE_ATTR:
1438 return -2;
1439 case DELETE_ATTR:
1440 return -1;
1441 case STORE_GLOBAL:
1442 return -1;
1443 case DELETE_GLOBAL:
1444 return 0;
1445 case DUP_TOPX:
1446 return oparg;
1447 case LOAD_CONST:
1448 return 1;
1449 case LOAD_NAME:
1450 return 1;
1451 case BUILD_TUPLE:
1452 case BUILD_LIST:
1453 return 1-oparg;
1454 case BUILD_MAP:
1455 return 1;
1456 case LOAD_ATTR:
1457 return 0;
1458 case COMPARE_OP:
1459 return -1;
1460 case IMPORT_NAME:
1461 return 0;
1462 case IMPORT_FROM:
1463 return 1;
1464
1465 case JUMP_FORWARD:
1466 case JUMP_IF_FALSE:
1467 case JUMP_IF_TRUE:
1468 case JUMP_ABSOLUTE:
1469 return 0;
1470
1471 case LOAD_GLOBAL:
1472 return 1;
1473
1474 case CONTINUE_LOOP:
1475 return 0;
1476 case SETUP_LOOP:
1477 return 0;
1478 case SETUP_EXCEPT:
1479 case SETUP_FINALLY:
1480 return 3; /* actually pushed by an exception */
1481
1482 case LOAD_FAST:
1483 return 1;
1484 case STORE_FAST:
1485 return -1;
1486 case DELETE_FAST:
1487 return 0;
1488
1489 case RAISE_VARARGS:
1490 return -oparg;
1491#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1492 case CALL_FUNCTION:
1493 return -NARGS(oparg);
1494 case CALL_FUNCTION_VAR:
1495 case CALL_FUNCTION_KW:
1496 return -NARGS(oparg)-1;
1497 case CALL_FUNCTION_VAR_KW:
1498 return -NARGS(oparg)-2;
1499#undef NARGS
1500 case MAKE_FUNCTION:
1501 return -oparg;
1502 case BUILD_SLICE:
1503 if (oparg == 3)
1504 return -2;
1505 else
1506 return -1;
1507
1508 case MAKE_CLOSURE:
1509 return -oparg;
1510 case LOAD_CLOSURE:
1511 return 1;
1512 case LOAD_DEREF:
1513 return 1;
1514 case STORE_DEREF:
1515 return -1;
1516 default:
1517 fprintf(stderr, "opcode = %d\n", opcode);
1518 Py_FatalError("opcode_stack_effect()");
1519
1520 }
1521 return 0; /* not reachable */
1522}
1523
1524/* Add an opcode with no argument.
1525 Returns 0 on failure, 1 on success.
1526*/
1527
1528static int
1529compiler_addop(struct compiler *c, int opcode)
1530{
1531 basicblock *b;
1532 struct instr *i;
1533 int off;
1534 off = compiler_next_instr(c, c->u->u_curblock);
1535 if (off < 0)
1536 return 0;
1537 b = c->u->u_curblock;
1538 i = &b->b_instr[off];
1539 i->i_opcode = opcode;
1540 i->i_hasarg = 0;
1541 if (opcode == RETURN_VALUE)
1542 b->b_return = 1;
1543 compiler_set_lineno(c, off);
1544 return 1;
1545}
1546
1547static int
1548compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1549{
1550 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001551 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001553 /* necessary to make sure types aren't coerced (e.g., int and long) */
1554 t = PyTuple_Pack(2, o, o->ob_type);
1555 if (t == NULL)
1556 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557
1558 v = PyDict_GetItem(dict, t);
1559 if (!v) {
1560 arg = PyDict_Size(dict);
1561 v = PyInt_FromLong(arg);
1562 if (!v) {
1563 Py_DECREF(t);
1564 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001565 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566 if (PyDict_SetItem(dict, t, v) < 0) {
1567 Py_DECREF(t);
1568 Py_DECREF(v);
1569 return -1;
1570 }
1571 Py_DECREF(v);
1572 }
1573 else
1574 arg = PyInt_AsLong(v);
1575 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001576 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577}
1578
1579static int
1580compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1581 PyObject *o)
1582{
1583 int arg = compiler_add_o(c, dict, o);
1584 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001585 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001586 return compiler_addop_i(c, opcode, arg);
1587}
1588
1589static int
1590compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001591 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001592{
1593 int arg;
1594 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1595 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001596 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001597 arg = compiler_add_o(c, dict, mangled);
1598 Py_DECREF(mangled);
1599 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001600 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601 return compiler_addop_i(c, opcode, arg);
1602}
1603
1604/* Add an opcode with an integer argument.
1605 Returns 0 on failure, 1 on success.
1606*/
1607
1608static int
1609compiler_addop_i(struct compiler *c, int opcode, int oparg)
1610{
1611 struct instr *i;
1612 int off;
1613 off = compiler_next_instr(c, c->u->u_curblock);
1614 if (off < 0)
1615 return 0;
1616 i = &c->u->u_curblock->b_instr[off];
1617 i->i_opcode = opcode;
1618 i->i_oparg = oparg;
1619 i->i_hasarg = 1;
1620 compiler_set_lineno(c, off);
1621 return 1;
1622}
1623
1624static int
1625compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1626{
1627 struct instr *i;
1628 int off;
1629
1630 assert(b != NULL);
1631 off = compiler_next_instr(c, c->u->u_curblock);
1632 if (off < 0)
1633 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634 i = &c->u->u_curblock->b_instr[off];
1635 i->i_opcode = opcode;
1636 i->i_target = b;
1637 i->i_hasarg = 1;
1638 if (absolute)
1639 i->i_jabs = 1;
1640 else
1641 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001642 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643 return 1;
1644}
1645
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001646/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1647 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648 it as the current block. NEXT_BLOCK() also creates an implicit jump
1649 from the current block to the new block.
1650*/
1651
1652/* XXX The returns inside these macros make it impossible to decref
1653 objects created in the local function.
1654*/
1655
1656
1657#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001658 if (compiler_use_new_block((C)) == NULL) \
1659 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660}
1661
1662#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001663 if (compiler_next_block((C)) == NULL) \
1664 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001665}
1666
1667#define ADDOP(C, OP) { \
1668 if (!compiler_addop((C), (OP))) \
1669 return 0; \
1670}
1671
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001672#define ADDOP_IN_SCOPE(C, OP) { \
1673 if (!compiler_addop((C), (OP))) { \
1674 compiler_exit_scope(c); \
1675 return 0; \
1676 } \
1677}
1678
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001679#define ADDOP_O(C, OP, O, TYPE) { \
1680 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1681 return 0; \
1682}
1683
1684#define ADDOP_NAME(C, OP, O, TYPE) { \
1685 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1686 return 0; \
1687}
1688
1689#define ADDOP_I(C, OP, O) { \
1690 if (!compiler_addop_i((C), (OP), (O))) \
1691 return 0; \
1692}
1693
1694#define ADDOP_JABS(C, OP, O) { \
1695 if (!compiler_addop_j((C), (OP), (O), 1)) \
1696 return 0; \
1697}
1698
1699#define ADDOP_JREL(C, OP, O) { \
1700 if (!compiler_addop_j((C), (OP), (O), 0)) \
1701 return 0; \
1702}
1703
1704/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1705 the ASDL name to synthesize the name of the C type and the visit function.
1706*/
1707
1708#define VISIT(C, TYPE, V) {\
1709 if (!compiler_visit_ ## TYPE((C), (V))) \
1710 return 0; \
1711}
1712
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001713#define VISIT_IN_SCOPE(C, TYPE, V) {\
1714 if (!compiler_visit_ ## TYPE((C), (V))) { \
1715 compiler_exit_scope(c); \
1716 return 0; \
1717 } \
1718}
1719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720#define VISIT_SLICE(C, V, CTX) {\
1721 if (!compiler_visit_slice((C), (V), (CTX))) \
1722 return 0; \
1723}
1724
1725#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001726 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001727 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001728 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001729 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001730 if (!compiler_visit_ ## TYPE((C), elt)) \
1731 return 0; \
1732 } \
1733}
1734
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001735#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001736 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001737 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001738 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001739 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001740 if (!compiler_visit_ ## TYPE((C), elt)) { \
1741 compiler_exit_scope(c); \
1742 return 0; \
1743 } \
1744 } \
1745}
1746
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747static int
1748compiler_isdocstring(stmt_ty s)
1749{
1750 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001751 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752 return s->v.Expr.value->kind == Str_kind;
1753}
1754
1755/* Compile a sequence of statements, checking for a docstring. */
1756
1757static int
1758compiler_body(struct compiler *c, asdl_seq *stmts)
1759{
1760 int i = 0;
1761 stmt_ty st;
1762
1763 if (!asdl_seq_LEN(stmts))
1764 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001765 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 if (compiler_isdocstring(st)) {
1767 i = 1;
1768 VISIT(c, expr, st->v.Expr.value);
1769 if (!compiler_nameop(c, __doc__, Store))
1770 return 0;
1771 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001772 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001773 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 return 1;
1775}
1776
1777static PyCodeObject *
1778compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001779{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001780 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001781 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 static PyObject *module;
1783 if (!module) {
1784 module = PyString_FromString("<module>");
1785 if (!module)
1786 return NULL;
1787 }
Neal Norwitzed657552006-07-10 00:04:44 +00001788 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1789 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001790 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 switch (mod->kind) {
1792 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001793 if (!compiler_body(c, mod->v.Module.body)) {
1794 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001796 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 break;
1798 case Interactive_kind:
1799 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001800 VISIT_SEQ_IN_SCOPE(c, stmt,
1801 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 break;
1803 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001804 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001805 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806 break;
1807 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001808 PyErr_SetString(PyExc_SystemError,
1809 "suite should not be possible");
1810 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001811 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001812 PyErr_Format(PyExc_SystemError,
1813 "module kind %d should not be possible",
1814 mod->kind);
1815 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001816 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 co = assemble(c, addNone);
1818 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001819 return co;
1820}
1821
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822/* The test for LOCAL must come before the test for FREE in order to
1823 handle classes where name is both local and free. The local var is
1824 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001825*/
1826
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827static int
1828get_ref_type(struct compiler *c, PyObject *name)
1829{
1830 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001831 if (scope == 0) {
1832 char buf[350];
1833 PyOS_snprintf(buf, sizeof(buf),
1834 "unknown scope for %.100s in %.100s(%s) in %s\n"
1835 "symbols: %s\nlocals: %s\nglobals: %s\n",
1836 PyString_AS_STRING(name),
1837 PyString_AS_STRING(c->u->u_name),
1838 PyObject_REPR(c->u->u_ste->ste_id),
1839 c->c_filename,
1840 PyObject_REPR(c->u->u_ste->ste_symbols),
1841 PyObject_REPR(c->u->u_varnames),
1842 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001843 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001844 Py_FatalError(buf);
1845 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001846
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001847 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848}
1849
1850static int
1851compiler_lookup_arg(PyObject *dict, PyObject *name)
1852{
1853 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001854 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001856 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001858 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001860 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861 return PyInt_AS_LONG(v);
1862}
1863
1864static int
1865compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1866{
1867 int i, free = PyCode_GetNumFree(co);
1868 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001869 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1870 ADDOP_I(c, MAKE_FUNCTION, args);
1871 return 1;
1872 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873 for (i = 0; i < free; ++i) {
1874 /* Bypass com_addop_varname because it will generate
1875 LOAD_DEREF but LOAD_CLOSURE is needed.
1876 */
1877 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1878 int arg, reftype;
1879
1880 /* Special case: If a class contains a method with a
1881 free variable that has the same name as a method,
1882 the name will be considered free *and* local in the
1883 class. It should be handled by the closure, as
1884 well as by the normal name loookup logic.
1885 */
1886 reftype = get_ref_type(c, name);
1887 if (reftype == CELL)
1888 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1889 else /* (reftype == FREE) */
1890 arg = compiler_lookup_arg(c->u->u_freevars, name);
1891 if (arg == -1) {
1892 printf("lookup %s in %s %d %d\n"
1893 "freevars of %s: %s\n",
1894 PyObject_REPR(name),
1895 PyString_AS_STRING(c->u->u_name),
1896 reftype, arg,
1897 PyString_AS_STRING(co->co_name),
1898 PyObject_REPR(co->co_freevars));
1899 Py_FatalError("compiler_make_closure()");
1900 }
1901 ADDOP_I(c, LOAD_CLOSURE, arg);
1902 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001903 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001905 ADDOP_I(c, MAKE_CLOSURE, args);
1906 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001907}
1908
1909static int
1910compiler_decorators(struct compiler *c, asdl_seq* decos)
1911{
1912 int i;
1913
1914 if (!decos)
1915 return 1;
1916
1917 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001918 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919 }
1920 return 1;
1921}
1922
1923static int
1924compiler_arguments(struct compiler *c, arguments_ty args)
1925{
1926 int i;
1927 int n = asdl_seq_LEN(args->args);
1928 /* Correctly handle nested argument lists */
1929 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001930 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 if (arg->kind == Tuple_kind) {
1932 PyObject *id = PyString_FromFormat(".%d", i);
1933 if (id == NULL) {
1934 return 0;
1935 }
1936 if (!compiler_nameop(c, id, Load)) {
1937 Py_DECREF(id);
1938 return 0;
1939 }
1940 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001941 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942 }
1943 }
1944 return 1;
1945}
1946
1947static int
1948compiler_function(struct compiler *c, stmt_ty s)
1949{
1950 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001951 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952 arguments_ty args = s->v.FunctionDef.args;
1953 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001954 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 int i, n, docstring;
1956
1957 assert(s->kind == FunctionDef_kind);
1958
1959 if (!compiler_decorators(c, decos))
1960 return 0;
1961 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001962 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1964 s->lineno))
1965 return 0;
1966
Anthony Baxter7b782b62006-04-11 12:01:56 +00001967 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001968 docstring = compiler_isdocstring(st);
1969 if (docstring)
1970 first_const = st->v.Expr.value->v.Str.s;
1971 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001972 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001973 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001974 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001976 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 compiler_arguments(c, args);
1978
1979 c->u->u_argcount = asdl_seq_LEN(args->args);
1980 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001981 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982 for (i = docstring; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001983 stmt_ty s2 = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 if (i == 0 && s2->kind == Expr_kind &&
1985 s2->v.Expr.value->kind == Str_kind)
1986 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001987 VISIT_IN_SCOPE(c, stmt, s2);
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)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002015 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 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)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002099 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002100 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;
Georg Brandlddbaa662006-06-04 21:56:52 +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;
Georg Brandlddbaa662006-06-04 21:56:52 +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);
2210 ADDOP_JREL(c, FOR_ITER, cleanup);
2211 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002212 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2214 compiler_use_next_block(c, cleanup);
2215 ADDOP(c, POP_BLOCK);
2216 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002217 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002218 compiler_use_next_block(c, end);
2219 return 1;
2220}
2221
2222static int
2223compiler_while(struct compiler *c, stmt_ty s)
2224{
2225 basicblock *loop, *orelse, *end, *anchor = NULL;
2226 int constant = expr_constant(s->v.While.test);
2227
2228 if (constant == 0)
2229 return 1;
2230 loop = compiler_new_block(c);
2231 end = compiler_new_block(c);
2232 if (constant == -1) {
2233 anchor = compiler_new_block(c);
2234 if (anchor == NULL)
2235 return 0;
2236 }
2237 if (loop == NULL || end == NULL)
2238 return 0;
2239 if (s->v.While.orelse) {
2240 orelse = compiler_new_block(c);
2241 if (orelse == NULL)
2242 return 0;
2243 }
2244 else
2245 orelse = NULL;
2246
2247 ADDOP_JREL(c, SETUP_LOOP, end);
2248 compiler_use_next_block(c, loop);
2249 if (!compiler_push_fblock(c, LOOP, loop))
2250 return 0;
2251 if (constant == -1) {
2252 VISIT(c, expr, s->v.While.test);
2253 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2254 ADDOP(c, POP_TOP);
2255 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002256 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002257 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2258
2259 /* XXX should the two POP instructions be in a separate block
2260 if there is no else clause ?
2261 */
2262
2263 if (constant == -1) {
2264 compiler_use_next_block(c, anchor);
2265 ADDOP(c, POP_TOP);
2266 ADDOP(c, POP_BLOCK);
2267 }
2268 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002269 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002270 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271 compiler_use_next_block(c, end);
2272
2273 return 1;
2274}
2275
2276static int
2277compiler_continue(struct compiler *c)
2278{
2279 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2280 int i;
2281
2282 if (!c->u->u_nfblocks)
2283 return compiler_error(c, LOOP_ERROR_MSG);
2284 i = c->u->u_nfblocks - 1;
2285 switch (c->u->u_fblock[i].fb_type) {
2286 case LOOP:
2287 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2288 break;
2289 case EXCEPT:
2290 case FINALLY_TRY:
2291 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2292 ;
2293 if (i == -1)
2294 return compiler_error(c, LOOP_ERROR_MSG);
2295 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2296 break;
2297 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002298 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299 "'continue' not supported inside 'finally' clause");
2300 }
2301
2302 return 1;
2303}
2304
2305/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2306
2307 SETUP_FINALLY L
2308 <code for body>
2309 POP_BLOCK
2310 LOAD_CONST <None>
2311 L: <code for finalbody>
2312 END_FINALLY
2313
2314 The special instructions use the block stack. Each block
2315 stack entry contains the instruction that created it (here
2316 SETUP_FINALLY), the level of the value stack at the time the
2317 block stack entry was created, and a label (here L).
2318
2319 SETUP_FINALLY:
2320 Pushes the current value stack level and the label
2321 onto the block stack.
2322 POP_BLOCK:
2323 Pops en entry from the block stack, and pops the value
2324 stack until its level is the same as indicated on the
2325 block stack. (The label is ignored.)
2326 END_FINALLY:
2327 Pops a variable number of entries from the *value* stack
2328 and re-raises the exception they specify. The number of
2329 entries popped depends on the (pseudo) exception type.
2330
2331 The block stack is unwound when an exception is raised:
2332 when a SETUP_FINALLY entry is found, the exception is pushed
2333 onto the value stack (and the exception condition is cleared),
2334 and the interpreter jumps to the label gotten from the block
2335 stack.
2336*/
2337
2338static int
2339compiler_try_finally(struct compiler *c, stmt_ty s)
2340{
2341 basicblock *body, *end;
2342 body = compiler_new_block(c);
2343 end = compiler_new_block(c);
2344 if (body == NULL || end == NULL)
2345 return 0;
2346
2347 ADDOP_JREL(c, SETUP_FINALLY, end);
2348 compiler_use_next_block(c, body);
2349 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2350 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002351 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352 ADDOP(c, POP_BLOCK);
2353 compiler_pop_fblock(c, FINALLY_TRY, body);
2354
2355 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2356 compiler_use_next_block(c, end);
2357 if (!compiler_push_fblock(c, FINALLY_END, end))
2358 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002359 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 ADDOP(c, END_FINALLY);
2361 compiler_pop_fblock(c, FINALLY_END, end);
2362
2363 return 1;
2364}
2365
2366/*
2367 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2368 (The contents of the value stack is shown in [], with the top
2369 at the right; 'tb' is trace-back info, 'val' the exception's
2370 associated value, and 'exc' the exception.)
2371
2372 Value stack Label Instruction Argument
2373 [] SETUP_EXCEPT L1
2374 [] <code for S>
2375 [] POP_BLOCK
2376 [] JUMP_FORWARD L0
2377
2378 [tb, val, exc] L1: DUP )
2379 [tb, val, exc, exc] <evaluate E1> )
2380 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2381 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2382 [tb, val, exc, 1] POP )
2383 [tb, val, exc] POP
2384 [tb, val] <assign to V1> (or POP if no V1)
2385 [tb] POP
2386 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002387 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002388
2389 [tb, val, exc, 0] L2: POP
2390 [tb, val, exc] DUP
2391 .............................etc.......................
2392
2393 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002394 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002395
2396 [] L0: <next statement>
2397
2398 Of course, parts are not generated if Vi or Ei is not present.
2399*/
2400static int
2401compiler_try_except(struct compiler *c, stmt_ty s)
2402{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002403 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404 int i, n;
2405
2406 body = compiler_new_block(c);
2407 except = compiler_new_block(c);
2408 orelse = compiler_new_block(c);
2409 end = compiler_new_block(c);
2410 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2411 return 0;
2412 ADDOP_JREL(c, SETUP_EXCEPT, except);
2413 compiler_use_next_block(c, body);
2414 if (!compiler_push_fblock(c, EXCEPT, body))
2415 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002416 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417 ADDOP(c, POP_BLOCK);
2418 compiler_pop_fblock(c, EXCEPT, body);
2419 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2420 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2421 compiler_use_next_block(c, except);
2422 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002423 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002424 s->v.TryExcept.handlers, i);
2425 if (!handler->type && i < n-1)
2426 return compiler_error(c, "default 'except:' must be last");
Jeremy Hyltoned40ea12006-04-04 14:26:39 +00002427 c->u->u_lineno_set = false;
2428 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429 except = compiler_new_block(c);
2430 if (except == NULL)
2431 return 0;
2432 if (handler->type) {
2433 ADDOP(c, DUP_TOP);
2434 VISIT(c, expr, handler->type);
2435 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2436 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2437 ADDOP(c, POP_TOP);
2438 }
2439 ADDOP(c, POP_TOP);
2440 if (handler->name) {
2441 VISIT(c, expr, handler->name);
2442 }
2443 else {
2444 ADDOP(c, POP_TOP);
2445 }
2446 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002447 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448 ADDOP_JREL(c, JUMP_FORWARD, end);
2449 compiler_use_next_block(c, except);
2450 if (handler->type)
2451 ADDOP(c, POP_TOP);
2452 }
2453 ADDOP(c, END_FINALLY);
2454 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002455 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 compiler_use_next_block(c, end);
2457 return 1;
2458}
2459
2460static int
2461compiler_import_as(struct compiler *c, identifier name, identifier asname)
2462{
2463 /* The IMPORT_NAME opcode was already generated. This function
2464 merely needs to bind the result to a name.
2465
2466 If there is a dot in name, we need to split it and emit a
2467 LOAD_ATTR for each name.
2468 */
2469 const char *src = PyString_AS_STRING(name);
2470 const char *dot = strchr(src, '.');
2471 if (dot) {
2472 /* Consume the base module name to get the first attribute */
2473 src = dot + 1;
2474 while (dot) {
2475 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002476 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002478 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002480 if (!attr)
2481 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002483 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 src = dot + 1;
2485 }
2486 }
2487 return compiler_nameop(c, asname, Store);
2488}
2489
2490static int
2491compiler_import(struct compiler *c, stmt_ty s)
2492{
2493 /* The Import node stores a module name like a.b.c as a single
2494 string. This is convenient for all cases except
2495 import a.b.c as d
2496 where we need to parse that string to extract the individual
2497 module names.
2498 XXX Perhaps change the representation to make this case simpler?
2499 */
2500 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002501
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002502 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002503 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002505 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002506
Neal Norwitzcbce2802006-04-03 06:26:32 +00002507 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002508 level = PyInt_FromLong(0);
2509 else
2510 level = PyInt_FromLong(-1);
2511
2512 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
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002554 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002555 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002556 level = PyInt_FromLong(-1);
2557 else
2558 level = PyInt_FromLong(s->v.ImportFrom.level);
2559
2560 if (!level) {
2561 Py_DECREF(names);
2562 return 0;
2563 }
2564
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002565 /* build up the names */
2566 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002567 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 Py_INCREF(alias->name);
2569 PyTuple_SET_ITEM(names, i, alias->name);
2570 }
2571
2572 if (s->lineno > c->c_future->ff_lineno) {
2573 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2574 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002575 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002576 Py_DECREF(names);
2577 return compiler_error(c,
2578 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002579 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002580
2581 }
2582 }
2583
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002584 ADDOP_O(c, LOAD_CONST, level, consts);
2585 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002587 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002588 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2589 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002590 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002591 identifier store_name;
2592
2593 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2594 assert(n == 1);
2595 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002596 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002597 }
2598
2599 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2600 store_name = alias->name;
2601 if (alias->asname)
2602 store_name = alias->asname;
2603
2604 if (!compiler_nameop(c, store_name, Store)) {
2605 Py_DECREF(names);
2606 return 0;
2607 }
2608 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002609 /* remove imported module */
2610 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 return 1;
2612}
2613
2614static int
2615compiler_assert(struct compiler *c, stmt_ty s)
2616{
2617 static PyObject *assertion_error = NULL;
2618 basicblock *end;
2619
2620 if (Py_OptimizeFlag)
2621 return 1;
2622 if (assertion_error == NULL) {
2623 assertion_error = PyString_FromString("AssertionError");
2624 if (assertion_error == NULL)
2625 return 0;
2626 }
2627 VISIT(c, expr, s->v.Assert.test);
2628 end = compiler_new_block(c);
2629 if (end == NULL)
2630 return 0;
2631 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2632 ADDOP(c, POP_TOP);
2633 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2634 if (s->v.Assert.msg) {
2635 VISIT(c, expr, s->v.Assert.msg);
2636 ADDOP_I(c, RAISE_VARARGS, 2);
2637 }
2638 else {
2639 ADDOP_I(c, RAISE_VARARGS, 1);
2640 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002641 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 ADDOP(c, POP_TOP);
2643 return 1;
2644}
2645
2646static int
2647compiler_visit_stmt(struct compiler *c, stmt_ty s)
2648{
2649 int i, n;
2650
Jeremy Hylton12603c42006-04-01 16:18:02 +00002651 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 c->u->u_lineno = s->lineno;
2653 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002658 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002660 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661 if (c->u->u_ste->ste_type != FunctionBlock)
2662 return compiler_error(c, "'return' outside function");
2663 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 VISIT(c, expr, s->v.Return.value);
2665 }
2666 else
2667 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2668 ADDOP(c, RETURN_VALUE);
2669 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002670 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002671 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 n = asdl_seq_LEN(s->v.Assign.targets);
2675 VISIT(c, expr, s->v.Assign.value);
2676 for (i = 0; i < n; i++) {
2677 if (i < n - 1)
2678 ADDOP(c, DUP_TOP);
2679 VISIT(c, expr,
2680 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2681 }
2682 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002685 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002686 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002687 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002688 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002689 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 n = 0;
2695 if (s->v.Raise.type) {
2696 VISIT(c, expr, s->v.Raise.type);
2697 n++;
2698 if (s->v.Raise.inst) {
2699 VISIT(c, expr, s->v.Raise.inst);
2700 n++;
2701 if (s->v.Raise.tback) {
2702 VISIT(c, expr, s->v.Raise.tback);
2703 n++;
2704 }
2705 }
2706 }
2707 ADDOP_I(c, RAISE_VARARGS, n);
2708 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002709 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002715 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002719 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 VISIT(c, expr, s->v.Exec.body);
2721 if (s->v.Exec.globals) {
2722 VISIT(c, expr, s->v.Exec.globals);
2723 if (s->v.Exec.locals) {
2724 VISIT(c, expr, s->v.Exec.locals);
2725 } else {
2726 ADDOP(c, DUP_TOP);
2727 }
2728 } else {
2729 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2730 ADDOP(c, DUP_TOP);
2731 }
2732 ADDOP(c, EXEC_STMT);
2733 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002734 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002736 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 VISIT(c, expr, s->v.Expr.value);
2738 if (c->c_interactive && c->c_nestlevel <= 1) {
2739 ADDOP(c, PRINT_EXPR);
2740 }
2741 else {
2742 ADDOP(c, POP_TOP);
2743 }
2744 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002745 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002747 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748 if (!c->u->u_nfblocks)
2749 return compiler_error(c, "'break' outside loop");
2750 ADDOP(c, BREAK_LOOP);
2751 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002752 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002753 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002754 case With_kind:
2755 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002756 }
2757 return 1;
2758}
2759
2760static int
2761unaryop(unaryop_ty op)
2762{
2763 switch (op) {
2764 case Invert:
2765 return UNARY_INVERT;
2766 case Not:
2767 return UNARY_NOT;
2768 case UAdd:
2769 return UNARY_POSITIVE;
2770 case USub:
2771 return UNARY_NEGATIVE;
2772 }
2773 return 0;
2774}
2775
2776static int
2777binop(struct compiler *c, operator_ty op)
2778{
2779 switch (op) {
2780 case Add:
2781 return BINARY_ADD;
2782 case Sub:
2783 return BINARY_SUBTRACT;
2784 case Mult:
2785 return BINARY_MULTIPLY;
2786 case Div:
2787 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2788 return BINARY_TRUE_DIVIDE;
2789 else
2790 return BINARY_DIVIDE;
2791 case Mod:
2792 return BINARY_MODULO;
2793 case Pow:
2794 return BINARY_POWER;
2795 case LShift:
2796 return BINARY_LSHIFT;
2797 case RShift:
2798 return BINARY_RSHIFT;
2799 case BitOr:
2800 return BINARY_OR;
2801 case BitXor:
2802 return BINARY_XOR;
2803 case BitAnd:
2804 return BINARY_AND;
2805 case FloorDiv:
2806 return BINARY_FLOOR_DIVIDE;
2807 }
2808 return 0;
2809}
2810
2811static int
2812cmpop(cmpop_ty op)
2813{
2814 switch (op) {
2815 case Eq:
2816 return PyCmp_EQ;
2817 case NotEq:
2818 return PyCmp_NE;
2819 case Lt:
2820 return PyCmp_LT;
2821 case LtE:
2822 return PyCmp_LE;
2823 case Gt:
2824 return PyCmp_GT;
2825 case GtE:
2826 return PyCmp_GE;
2827 case Is:
2828 return PyCmp_IS;
2829 case IsNot:
2830 return PyCmp_IS_NOT;
2831 case In:
2832 return PyCmp_IN;
2833 case NotIn:
2834 return PyCmp_NOT_IN;
2835 }
2836 return PyCmp_BAD;
2837}
2838
2839static int
2840inplace_binop(struct compiler *c, operator_ty op)
2841{
2842 switch (op) {
2843 case Add:
2844 return INPLACE_ADD;
2845 case Sub:
2846 return INPLACE_SUBTRACT;
2847 case Mult:
2848 return INPLACE_MULTIPLY;
2849 case Div:
2850 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2851 return INPLACE_TRUE_DIVIDE;
2852 else
2853 return INPLACE_DIVIDE;
2854 case Mod:
2855 return INPLACE_MODULO;
2856 case Pow:
2857 return INPLACE_POWER;
2858 case LShift:
2859 return INPLACE_LSHIFT;
2860 case RShift:
2861 return INPLACE_RSHIFT;
2862 case BitOr:
2863 return INPLACE_OR;
2864 case BitXor:
2865 return INPLACE_XOR;
2866 case BitAnd:
2867 return INPLACE_AND;
2868 case FloorDiv:
2869 return INPLACE_FLOOR_DIVIDE;
2870 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002871 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002872 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873 return 0;
2874}
2875
2876static int
2877compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2878{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002879 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2881
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002882 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002883 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 /* XXX AugStore isn't used anywhere! */
2885
2886 /* First check for assignment to __debug__. Param? */
2887 if ((ctx == Store || ctx == AugStore || ctx == Del)
2888 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2889 return compiler_error(c, "can not assign to __debug__");
2890 }
2891
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002892 mangled = _Py_Mangle(c->u->u_private, name);
2893 if (!mangled)
2894 return 0;
2895
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896 op = 0;
2897 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002898 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002899 switch (scope) {
2900 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002901 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902 optype = OP_DEREF;
2903 break;
2904 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002905 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 optype = OP_DEREF;
2907 break;
2908 case LOCAL:
2909 if (c->u->u_ste->ste_type == FunctionBlock)
2910 optype = OP_FAST;
2911 break;
2912 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002913 if (c->u->u_ste->ste_type == FunctionBlock &&
2914 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002915 optype = OP_GLOBAL;
2916 break;
2917 case GLOBAL_EXPLICIT:
2918 optype = OP_GLOBAL;
2919 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002920 default:
2921 /* scope can be 0 */
2922 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002923 }
2924
2925 /* XXX Leave assert here, but handle __doc__ and the like better */
2926 assert(scope || PyString_AS_STRING(name)[0] == '_');
2927
2928 switch (optype) {
2929 case OP_DEREF:
2930 switch (ctx) {
2931 case Load: op = LOAD_DEREF; break;
2932 case Store: op = STORE_DEREF; break;
2933 case AugLoad:
2934 case AugStore:
2935 break;
2936 case Del:
2937 PyErr_Format(PyExc_SyntaxError,
2938 "can not delete variable '%s' referenced "
2939 "in nested scope",
2940 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002941 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002944 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002945 PyErr_SetString(PyExc_SystemError,
2946 "param invalid for deref variable");
2947 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 }
2949 break;
2950 case OP_FAST:
2951 switch (ctx) {
2952 case Load: op = LOAD_FAST; break;
2953 case Store: op = STORE_FAST; break;
2954 case Del: op = DELETE_FAST; break;
2955 case AugLoad:
2956 case AugStore:
2957 break;
2958 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002959 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002960 PyErr_SetString(PyExc_SystemError,
2961 "param invalid for local variable");
2962 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002964 ADDOP_O(c, op, mangled, varnames);
2965 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 return 1;
2967 case OP_GLOBAL:
2968 switch (ctx) {
2969 case Load: op = LOAD_GLOBAL; break;
2970 case Store: op = STORE_GLOBAL; break;
2971 case Del: op = DELETE_GLOBAL; break;
2972 case AugLoad:
2973 case AugStore:
2974 break;
2975 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002976 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002977 PyErr_SetString(PyExc_SystemError,
2978 "param invalid for global variable");
2979 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 }
2981 break;
2982 case OP_NAME:
2983 switch (ctx) {
2984 case Load: op = LOAD_NAME; break;
2985 case Store: op = STORE_NAME; break;
2986 case Del: op = DELETE_NAME; break;
2987 case AugLoad:
2988 case AugStore:
2989 break;
2990 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002991 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002992 PyErr_SetString(PyExc_SystemError,
2993 "param invalid for name variable");
2994 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995 }
2996 break;
2997 }
2998
2999 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003000 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00003001 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003002 if (arg < 0)
3003 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00003004 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005}
3006
3007static int
3008compiler_boolop(struct compiler *c, expr_ty e)
3009{
3010 basicblock *end;
3011 int jumpi, i, n;
3012 asdl_seq *s;
3013
3014 assert(e->kind == BoolOp_kind);
3015 if (e->v.BoolOp.op == And)
3016 jumpi = JUMP_IF_FALSE;
3017 else
3018 jumpi = JUMP_IF_TRUE;
3019 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003020 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 return 0;
3022 s = e->v.BoolOp.values;
3023 n = asdl_seq_LEN(s) - 1;
3024 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003025 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026 ADDOP_JREL(c, jumpi, end);
3027 ADDOP(c, POP_TOP)
3028 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003029 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003030 compiler_use_next_block(c, end);
3031 return 1;
3032}
3033
3034static int
3035compiler_list(struct compiler *c, expr_ty e)
3036{
3037 int n = asdl_seq_LEN(e->v.List.elts);
3038 if (e->v.List.ctx == Store) {
3039 ADDOP_I(c, UNPACK_SEQUENCE, n);
3040 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003041 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042 if (e->v.List.ctx == Load) {
3043 ADDOP_I(c, BUILD_LIST, n);
3044 }
3045 return 1;
3046}
3047
3048static int
3049compiler_tuple(struct compiler *c, expr_ty e)
3050{
3051 int n = asdl_seq_LEN(e->v.Tuple.elts);
3052 if (e->v.Tuple.ctx == Store) {
3053 ADDOP_I(c, UNPACK_SEQUENCE, n);
3054 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003055 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 if (e->v.Tuple.ctx == Load) {
3057 ADDOP_I(c, BUILD_TUPLE, n);
3058 }
3059 return 1;
3060}
3061
3062static int
3063compiler_compare(struct compiler *c, expr_ty e)
3064{
3065 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003066 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067
3068 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3069 VISIT(c, expr, e->v.Compare.left);
3070 n = asdl_seq_LEN(e->v.Compare.ops);
3071 assert(n > 0);
3072 if (n > 1) {
3073 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003074 if (cleanup == NULL)
3075 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003076 VISIT(c, expr,
3077 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003078 }
3079 for (i = 1; i < n; i++) {
3080 ADDOP(c, DUP_TOP);
3081 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003082 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003083 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003084 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003085 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3086 NEXT_BLOCK(c);
3087 ADDOP(c, POP_TOP);
3088 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003089 VISIT(c, expr,
3090 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003091 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003092 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003094 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095 if (n > 1) {
3096 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003097 if (end == NULL)
3098 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003099 ADDOP_JREL(c, JUMP_FORWARD, end);
3100 compiler_use_next_block(c, cleanup);
3101 ADDOP(c, ROT_TWO);
3102 ADDOP(c, POP_TOP);
3103 compiler_use_next_block(c, end);
3104 }
3105 return 1;
3106}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003107#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003108
3109static int
3110compiler_call(struct compiler *c, expr_ty e)
3111{
3112 int n, code = 0;
3113
3114 VISIT(c, expr, e->v.Call.func);
3115 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003116 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003118 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3120 }
3121 if (e->v.Call.starargs) {
3122 VISIT(c, expr, e->v.Call.starargs);
3123 code |= 1;
3124 }
3125 if (e->v.Call.kwargs) {
3126 VISIT(c, expr, e->v.Call.kwargs);
3127 code |= 2;
3128 }
3129 switch (code) {
3130 case 0:
3131 ADDOP_I(c, CALL_FUNCTION, n);
3132 break;
3133 case 1:
3134 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3135 break;
3136 case 2:
3137 ADDOP_I(c, CALL_FUNCTION_KW, n);
3138 break;
3139 case 3:
3140 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3141 break;
3142 }
3143 return 1;
3144}
3145
3146static int
3147compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 asdl_seq *generators, int gen_index,
3149 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150{
3151 /* generate code for the iterator, then each of the ifs,
3152 and then write to the element */
3153
3154 comprehension_ty l;
3155 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157
3158 start = compiler_new_block(c);
3159 skip = compiler_new_block(c);
3160 if_cleanup = compiler_new_block(c);
3161 anchor = compiler_new_block(c);
3162
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3164 anchor == NULL)
3165 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166
Anthony Baxter7b782b62006-04-11 12:01:56 +00003167 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 VISIT(c, expr, l->iter);
3169 ADDOP(c, GET_ITER);
3170 compiler_use_next_block(c, start);
3171 ADDOP_JREL(c, FOR_ITER, anchor);
3172 NEXT_BLOCK(c);
3173 VISIT(c, expr, l->target);
3174
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003175 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 n = asdl_seq_LEN(l->ifs);
3177 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003178 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179 VISIT(c, expr, e);
3180 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3181 NEXT_BLOCK(c);
3182 ADDOP(c, POP_TOP);
3183 }
3184
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003185 if (++gen_index < asdl_seq_LEN(generators))
3186 if (!compiler_listcomp_generator(c, tmpname,
3187 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190 /* only append after the last for generator */
3191 if (gen_index >= asdl_seq_LEN(generators)) {
3192 if (!compiler_nameop(c, tmpname, Load))
3193 return 0;
3194 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003195 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003196
3197 compiler_use_next_block(c, skip);
3198 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 for (i = 0; i < n; i++) {
3200 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003201 if (i == 0)
3202 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203 ADDOP(c, POP_TOP);
3204 }
3205 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3206 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003207 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003208 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210 return 0;
3211
3212 return 1;
3213}
3214
3215static int
3216compiler_listcomp(struct compiler *c, expr_ty e)
3217{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 static identifier append;
3221 asdl_seq *generators = e->v.ListComp.generators;
3222
3223 assert(e->kind == ListComp_kind);
3224 if (!append) {
3225 append = PyString_InternFromString("append");
3226 if (!append)
3227 return 0;
3228 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003229 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230 if (!tmp)
3231 return 0;
3232 ADDOP_I(c, BUILD_LIST, 0);
3233 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3236 e->v.ListComp.elt);
3237 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 return rc;
3239}
3240
3241static int
3242compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003243 asdl_seq *generators, int gen_index,
3244 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003245{
3246 /* generate code for the iterator, then each of the ifs,
3247 and then write to the element */
3248
3249 comprehension_ty ge;
3250 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
3253 start = compiler_new_block(c);
3254 skip = compiler_new_block(c);
3255 if_cleanup = compiler_new_block(c);
3256 anchor = compiler_new_block(c);
3257 end = compiler_new_block(c);
3258
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 anchor == NULL || end == NULL)
3261 return 0;
3262
Anthony Baxter7b782b62006-04-11 12:01:56 +00003263 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 ADDOP_JREL(c, SETUP_LOOP, end);
3265 if (!compiler_push_fblock(c, LOOP, start))
3266 return 0;
3267
3268 if (gen_index == 0) {
3269 /* Receive outermost iter as an implicit argument */
3270 c->u->u_argcount = 1;
3271 ADDOP_I(c, LOAD_FAST, 0);
3272 }
3273 else {
3274 /* Sub-iter - calculate on the fly */
3275 VISIT(c, expr, ge->iter);
3276 ADDOP(c, GET_ITER);
3277 }
3278 compiler_use_next_block(c, start);
3279 ADDOP_JREL(c, FOR_ITER, anchor);
3280 NEXT_BLOCK(c);
3281 VISIT(c, expr, ge->target);
3282
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 n = asdl_seq_LEN(ge->ifs);
3285 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003286 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 VISIT(c, expr, e);
3288 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3289 NEXT_BLOCK(c);
3290 ADDOP(c, POP_TOP);
3291 }
3292
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003293 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3295 return 0;
3296
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003297 /* only append after the last 'for' generator */
3298 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299 VISIT(c, expr, elt);
3300 ADDOP(c, YIELD_VALUE);
3301 ADDOP(c, POP_TOP);
3302
3303 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305 for (i = 0; i < n; i++) {
3306 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003307 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 compiler_use_next_block(c, if_cleanup);
3309
3310 ADDOP(c, POP_TOP);
3311 }
3312 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3313 compiler_use_next_block(c, anchor);
3314 ADDOP(c, POP_BLOCK);
3315 compiler_pop_fblock(c, LOOP, start);
3316 compiler_use_next_block(c, end);
3317
3318 return 1;
3319}
3320
3321static int
3322compiler_genexp(struct compiler *c, expr_ty e)
3323{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003324 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003325 PyCodeObject *co;
3326 expr_ty outermost_iter = ((comprehension_ty)
3327 (asdl_seq_GET(e->v.GeneratorExp.generators,
3328 0)))->iter;
3329
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003330 if (!name) {
3331 name = PyString_FromString("<genexpr>");
3332 if (!name)
3333 return 0;
3334 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335
3336 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3337 return 0;
3338 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3339 e->v.GeneratorExp.elt);
3340 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003341 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003342 if (co == NULL)
3343 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003345 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003346 Py_DECREF(co);
3347
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003348 VISIT(c, expr, outermost_iter);
3349 ADDOP(c, GET_ITER);
3350 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003351
3352 return 1;
3353}
3354
3355static int
3356compiler_visit_keyword(struct compiler *c, keyword_ty k)
3357{
3358 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3359 VISIT(c, expr, k->value);
3360 return 1;
3361}
3362
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003363/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003364 whether they are true or false.
3365
3366 Return values: 1 for true, 0 for false, -1 for non-constant.
3367 */
3368
3369static int
3370expr_constant(expr_ty e)
3371{
3372 switch (e->kind) {
3373 case Num_kind:
3374 return PyObject_IsTrue(e->v.Num.n);
3375 case Str_kind:
3376 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003377 case Name_kind:
3378 /* __debug__ is not assignable, so we can optimize
3379 * it away in if and while statements */
3380 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3381 "__debug__") == 0)
3382 return ! Py_OptimizeFlag;
3383 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003384 default:
3385 return -1;
3386 }
3387}
3388
Guido van Rossumc2e20742006-02-27 22:32:47 +00003389/*
3390 Implements the with statement from PEP 343.
3391
3392 The semantics outlined in that PEP are as follows:
3393
3394 with EXPR as VAR:
3395 BLOCK
3396
3397 It is implemented roughly as:
3398
Guido van Rossumda5b7012006-05-02 19:47:52 +00003399 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003400 exit = context.__exit__ # not calling it
3401 value = context.__enter__()
3402 try:
3403 VAR = value # if VAR present in the syntax
3404 BLOCK
3405 finally:
3406 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003407 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003408 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003409 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003410 exit(*exc)
3411 */
3412static int
3413compiler_with(struct compiler *c, stmt_ty s)
3414{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003415 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003416 basicblock *block, *finally;
3417 identifier tmpexit, tmpvalue = NULL;
3418
3419 assert(s->kind == With_kind);
3420
Guido van Rossumc2e20742006-02-27 22:32:47 +00003421 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003422 enter_attr = PyString_InternFromString("__enter__");
3423 if (!enter_attr)
3424 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003425 }
3426 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003427 exit_attr = PyString_InternFromString("__exit__");
3428 if (!exit_attr)
3429 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003430 }
3431
3432 block = compiler_new_block(c);
3433 finally = compiler_new_block(c);
3434 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003435 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003436
3437 /* Create a temporary variable to hold context.__exit__ */
3438 tmpexit = compiler_new_tmpname(c);
3439 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003440 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003441 PyArena_AddPyObject(c->c_arena, tmpexit);
3442
3443 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003444 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003445 We need to do this rather than preserving it on the stack
3446 because SETUP_FINALLY remembers the stack level.
3447 We need to do the assignment *inside* the try/finally
3448 so that context.__exit__() is called when the assignment
3449 fails. But we need to call context.__enter__() *before*
3450 the try/finally so that if it fails we won't call
3451 context.__exit__().
3452 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003454 if (tmpvalue == NULL)
3455 return 0;
3456 PyArena_AddPyObject(c->c_arena, tmpvalue);
3457 }
3458
Guido van Rossumda5b7012006-05-02 19:47:52 +00003459 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003460 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003461
3462 /* Squirrel away context.__exit__ */
3463 ADDOP(c, DUP_TOP);
3464 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3465 if (!compiler_nameop(c, tmpexit, Store))
3466 return 0;
3467
3468 /* Call context.__enter__() */
3469 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3470 ADDOP_I(c, CALL_FUNCTION, 0);
3471
3472 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 /* Store it in tmpvalue */
3474 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003475 return 0;
3476 }
3477 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 /* Discard result from context.__enter__() */
3479 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003480 }
3481
3482 /* Start the try block */
3483 ADDOP_JREL(c, SETUP_FINALLY, finally);
3484
3485 compiler_use_next_block(c, block);
3486 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003487 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003488 }
3489
3490 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003491 /* Bind saved result of context.__enter__() to VAR */
3492 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003493 !compiler_nameop(c, tmpvalue, Del))
3494 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003496 }
3497
3498 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003499 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003500
3501 /* End of try block; start the finally block */
3502 ADDOP(c, POP_BLOCK);
3503 compiler_pop_fblock(c, FINALLY_TRY, block);
3504
3505 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3506 compiler_use_next_block(c, finally);
3507 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003508 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003509
3510 /* Finally block starts; push tmpexit and issue our magic opcode. */
3511 if (!compiler_nameop(c, tmpexit, Load) ||
3512 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003513 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003514 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003515
3516 /* Finally block ends. */
3517 ADDOP(c, END_FINALLY);
3518 compiler_pop_fblock(c, FINALLY_END, finally);
3519 return 1;
3520}
3521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522static int
3523compiler_visit_expr(struct compiler *c, expr_ty e)
3524{
3525 int i, n;
3526
Jeremy Hylton12603c42006-04-01 16:18:02 +00003527 /* If expr e has a different line number than the last expr/stmt,
3528 set a new line number for the next instruction.
3529 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 if (e->lineno > c->u->u_lineno) {
3531 c->u->u_lineno = e->lineno;
3532 c->u->u_lineno_set = false;
3533 }
3534 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003535 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003537 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 VISIT(c, expr, e->v.BinOp.left);
3539 VISIT(c, expr, e->v.BinOp.right);
3540 ADDOP(c, binop(c, e->v.BinOp.op));
3541 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003542 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543 VISIT(c, expr, e->v.UnaryOp.operand);
3544 ADDOP(c, unaryop(e->v.UnaryOp.op));
3545 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003546 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003548 case IfExp_kind:
3549 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003550 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 /* XXX get rid of arg? */
3552 ADDOP_I(c, BUILD_MAP, 0);
3553 n = asdl_seq_LEN(e->v.Dict.values);
3554 /* We must arrange things just right for STORE_SUBSCR.
3555 It wants the stack to look like (value) (dict) (key) */
3556 for (i = 0; i < n; i++) {
3557 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003558 VISIT(c, expr,
3559 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003561 VISIT(c, expr,
3562 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563 ADDOP(c, STORE_SUBSCR);
3564 }
3565 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003566 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003568 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003569 return compiler_genexp(c, e);
3570 case Yield_kind:
3571 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003572 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003573 /*
3574 for (i = 0; i < c->u->u_nfblocks; i++) {
3575 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3576 return compiler_error(
3577 c, "'yield' not allowed in a 'try' "
3578 "block with a 'finally' clause");
3579 }
3580 */
3581 if (e->v.Yield.value) {
3582 VISIT(c, expr, e->v.Yield.value);
3583 }
3584 else {
3585 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3586 }
3587 ADDOP(c, YIELD_VALUE);
3588 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003589 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003591 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003593 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003594 VISIT(c, expr, e->v.Repr.value);
3595 ADDOP(c, UNARY_CONVERT);
3596 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003597 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3599 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003600 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3602 break;
3603 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003604 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605 if (e->v.Attribute.ctx != AugStore)
3606 VISIT(c, expr, e->v.Attribute.value);
3607 switch (e->v.Attribute.ctx) {
3608 case AugLoad:
3609 ADDOP(c, DUP_TOP);
3610 /* Fall through to load */
3611 case Load:
3612 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3613 break;
3614 case AugStore:
3615 ADDOP(c, ROT_TWO);
3616 /* Fall through to save */
3617 case Store:
3618 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3619 break;
3620 case Del:
3621 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3622 break;
3623 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003624 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003625 PyErr_SetString(PyExc_SystemError,
3626 "param invalid in attribute expression");
3627 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628 }
3629 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003630 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 switch (e->v.Subscript.ctx) {
3632 case AugLoad:
3633 VISIT(c, expr, e->v.Subscript.value);
3634 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3635 break;
3636 case Load:
3637 VISIT(c, expr, e->v.Subscript.value);
3638 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3639 break;
3640 case AugStore:
3641 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3642 break;
3643 case Store:
3644 VISIT(c, expr, e->v.Subscript.value);
3645 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3646 break;
3647 case Del:
3648 VISIT(c, expr, e->v.Subscript.value);
3649 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3650 break;
3651 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003652 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003653 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 }
3657 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003658 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3660 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003661 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003662 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003663 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664 return compiler_tuple(c, e);
3665 }
3666 return 1;
3667}
3668
3669static int
3670compiler_augassign(struct compiler *c, stmt_ty s)
3671{
3672 expr_ty e = s->v.AugAssign.target;
3673 expr_ty auge;
3674
3675 assert(s->kind == AugAssign_kind);
3676
3677 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003678 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003680 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003681 if (auge == NULL)
3682 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003683 VISIT(c, expr, auge);
3684 VISIT(c, expr, s->v.AugAssign.value);
3685 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3686 auge->v.Attribute.ctx = AugStore;
3687 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003688 break;
3689 case Subscript_kind:
3690 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003691 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003692 if (auge == NULL)
3693 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 VISIT(c, expr, auge);
3695 VISIT(c, expr, s->v.AugAssign.value);
3696 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003697 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003698 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003699 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003700 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003701 if (!compiler_nameop(c, e->v.Name.id, Load))
3702 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703 VISIT(c, expr, s->v.AugAssign.value);
3704 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3705 return compiler_nameop(c, e->v.Name.id, Store);
3706 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003707 PyErr_Format(PyExc_SystemError,
3708 "invalid node type (%d) for augmented assignment",
3709 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003710 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003711 }
3712 return 1;
3713}
3714
3715static int
3716compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3717{
3718 struct fblockinfo *f;
3719 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3720 return 0;
3721 f = &c->u->u_fblock[c->u->u_nfblocks++];
3722 f->fb_type = t;
3723 f->fb_block = b;
3724 return 1;
3725}
3726
3727static void
3728compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3729{
3730 struct compiler_unit *u = c->u;
3731 assert(u->u_nfblocks > 0);
3732 u->u_nfblocks--;
3733 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3734 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3735}
3736
3737/* Raises a SyntaxError and returns 0.
3738 If something goes wrong, a different exception may be raised.
3739*/
3740
3741static int
3742compiler_error(struct compiler *c, const char *errstr)
3743{
3744 PyObject *loc;
3745 PyObject *u = NULL, *v = NULL;
3746
3747 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3748 if (!loc) {
3749 Py_INCREF(Py_None);
3750 loc = Py_None;
3751 }
3752 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3753 Py_None, loc);
3754 if (!u)
3755 goto exit;
3756 v = Py_BuildValue("(zO)", errstr, u);
3757 if (!v)
3758 goto exit;
3759 PyErr_SetObject(PyExc_SyntaxError, v);
3760 exit:
3761 Py_DECREF(loc);
3762 Py_XDECREF(u);
3763 Py_XDECREF(v);
3764 return 0;
3765}
3766
3767static int
3768compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003769 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003771 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 /* XXX this code is duplicated */
3774 switch (ctx) {
3775 case AugLoad: /* fall through to Load */
3776 case Load: op = BINARY_SUBSCR; break;
3777 case AugStore:/* fall through to Store */
3778 case Store: op = STORE_SUBSCR; break;
3779 case Del: op = DELETE_SUBSCR; break;
3780 case Param:
3781 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003782 "invalid %s kind %d in subscript\n",
3783 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003784 return 0;
3785 }
3786 if (ctx == AugLoad) {
3787 ADDOP_I(c, DUP_TOPX, 2);
3788 }
3789 else if (ctx == AugStore) {
3790 ADDOP(c, ROT_THREE);
3791 }
3792 ADDOP(c, op);
3793 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794}
3795
3796static int
3797compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3798{
3799 int n = 2;
3800 assert(s->kind == Slice_kind);
3801
3802 /* only handles the cases where BUILD_SLICE is emitted */
3803 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003804 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003805 }
3806 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003807 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003808 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003809
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003810 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003811 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812 }
3813 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003814 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003815 }
3816
3817 if (s->v.Slice.step) {
3818 n++;
3819 VISIT(c, expr, s->v.Slice.step);
3820 }
3821 ADDOP_I(c, BUILD_SLICE, n);
3822 return 1;
3823}
3824
3825static int
3826compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3827{
3828 int op = 0, slice_offset = 0, stack_count = 0;
3829
3830 assert(s->v.Slice.step == NULL);
3831 if (s->v.Slice.lower) {
3832 slice_offset++;
3833 stack_count++;
3834 if (ctx != AugStore)
3835 VISIT(c, expr, s->v.Slice.lower);
3836 }
3837 if (s->v.Slice.upper) {
3838 slice_offset += 2;
3839 stack_count++;
3840 if (ctx != AugStore)
3841 VISIT(c, expr, s->v.Slice.upper);
3842 }
3843
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003844 if (ctx == AugLoad) {
3845 switch (stack_count) {
3846 case 0: ADDOP(c, DUP_TOP); break;
3847 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3848 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3849 }
3850 }
3851 else if (ctx == AugStore) {
3852 switch (stack_count) {
3853 case 0: ADDOP(c, ROT_TWO); break;
3854 case 1: ADDOP(c, ROT_THREE); break;
3855 case 2: ADDOP(c, ROT_FOUR); break;
3856 }
3857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003858
3859 switch (ctx) {
3860 case AugLoad: /* fall through to Load */
3861 case Load: op = SLICE; break;
3862 case AugStore:/* fall through to Store */
3863 case Store: op = STORE_SLICE; break;
3864 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003865 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003866 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003867 PyErr_SetString(PyExc_SystemError,
3868 "param invalid in simple slice");
3869 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870 }
3871
3872 ADDOP(c, op + slice_offset);
3873 return 1;
3874}
3875
3876static int
3877compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3878 expr_context_ty ctx)
3879{
3880 switch (s->kind) {
3881 case Ellipsis_kind:
3882 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3883 break;
3884 case Slice_kind:
3885 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 case Index_kind:
3887 VISIT(c, expr, s->v.Index.value);
3888 break;
3889 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003890 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003891 PyErr_SetString(PyExc_SystemError,
3892 "extended slice invalid in nested slice");
3893 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003894 }
3895 return 1;
3896}
3897
3898
3899static int
3900compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3901{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003902 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003904 case Index_kind:
3905 kindname = "index";
3906 if (ctx != AugStore) {
3907 VISIT(c, expr, s->v.Index.value);
3908 }
3909 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003911 kindname = "ellipsis";
3912 if (ctx != AugStore) {
3913 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3914 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003915 break;
3916 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003917 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003918 if (!s->v.Slice.step)
3919 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003920 if (ctx != AugStore) {
3921 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922 return 0;
3923 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003924 break;
3925 case ExtSlice_kind:
3926 kindname = "extended slice";
3927 if (ctx != AugStore) {
3928 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3929 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003930 slice_ty sub = (slice_ty)asdl_seq_GET(
3931 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003932 if (!compiler_visit_nested_slice(c, sub, ctx))
3933 return 0;
3934 }
3935 ADDOP_I(c, BUILD_TUPLE, n);
3936 }
3937 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003938 default:
3939 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003940 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003942 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003943 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944}
3945
3946/* do depth-first search of basic block graph, starting with block.
3947 post records the block indices in post-order.
3948
3949 XXX must handle implicit jumps from one block to next
3950*/
3951
3952static void
3953dfs(struct compiler *c, basicblock *b, struct assembler *a)
3954{
3955 int i;
3956 struct instr *instr = NULL;
3957
3958 if (b->b_seen)
3959 return;
3960 b->b_seen = 1;
3961 if (b->b_next != NULL)
3962 dfs(c, b->b_next, a);
3963 for (i = 0; i < b->b_iused; i++) {
3964 instr = &b->b_instr[i];
3965 if (instr->i_jrel || instr->i_jabs)
3966 dfs(c, instr->i_target, a);
3967 }
3968 a->a_postorder[a->a_nblocks++] = b;
3969}
3970
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003971static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3973{
3974 int i;
3975 struct instr *instr;
3976 if (b->b_seen || b->b_startdepth >= depth)
3977 return maxdepth;
3978 b->b_seen = 1;
3979 b->b_startdepth = depth;
3980 for (i = 0; i < b->b_iused; i++) {
3981 instr = &b->b_instr[i];
3982 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3983 if (depth > maxdepth)
3984 maxdepth = depth;
3985 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3986 if (instr->i_jrel || instr->i_jabs) {
3987 maxdepth = stackdepth_walk(c, instr->i_target,
3988 depth, maxdepth);
3989 if (instr->i_opcode == JUMP_ABSOLUTE ||
3990 instr->i_opcode == JUMP_FORWARD) {
3991 goto out; /* remaining code is dead */
3992 }
3993 }
3994 }
3995 if (b->b_next)
3996 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3997out:
3998 b->b_seen = 0;
3999 return maxdepth;
4000}
4001
4002/* Find the flow path that needs the largest stack. We assume that
4003 * cycles in the flow graph have no net effect on the stack depth.
4004 */
4005static int
4006stackdepth(struct compiler *c)
4007{
4008 basicblock *b, *entryblock;
4009 entryblock = NULL;
4010 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4011 b->b_seen = 0;
4012 b->b_startdepth = INT_MIN;
4013 entryblock = b;
4014 }
4015 return stackdepth_walk(c, entryblock, 0, 0);
4016}
4017
4018static int
4019assemble_init(struct assembler *a, int nblocks, int firstlineno)
4020{
4021 memset(a, 0, sizeof(struct assembler));
4022 a->a_lineno = firstlineno;
4023 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4024 if (!a->a_bytecode)
4025 return 0;
4026 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4027 if (!a->a_lnotab)
4028 return 0;
4029 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004030 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004031 if (!a->a_postorder) {
4032 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004033 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004034 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004035 return 1;
4036}
4037
4038static void
4039assemble_free(struct assembler *a)
4040{
4041 Py_XDECREF(a->a_bytecode);
4042 Py_XDECREF(a->a_lnotab);
4043 if (a->a_postorder)
4044 PyObject_Free(a->a_postorder);
4045}
4046
4047/* Return the size of a basic block in bytes. */
4048
4049static int
4050instrsize(struct instr *instr)
4051{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004052 if (!instr->i_hasarg)
4053 return 1;
4054 if (instr->i_oparg > 0xffff)
4055 return 6;
4056 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004057}
4058
4059static int
4060blocksize(basicblock *b)
4061{
4062 int i;
4063 int size = 0;
4064
4065 for (i = 0; i < b->b_iused; i++)
4066 size += instrsize(&b->b_instr[i]);
4067 return size;
4068}
4069
4070/* All about a_lnotab.
4071
4072c_lnotab is an array of unsigned bytes disguised as a Python string.
4073It is used to map bytecode offsets to source code line #s (when needed
4074for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004075
Tim Peters2a7f3842001-06-09 09:26:21 +00004076The array is conceptually a list of
4077 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004078pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004079
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004080 byte code offset source code line number
4081 0 1
4082 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004083 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004084 350 307
4085 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004086
4087The first trick is that these numbers aren't stored, only the increments
4088from one row to the next (this doesn't really work, but it's a start):
4089
4090 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4091
4092The second trick is that an unsigned byte can't hold negative values, or
4093values larger than 255, so (a) there's a deep assumption that byte code
4094offsets and their corresponding line #s both increase monotonically, and (b)
4095if at least one column jumps by more than 255 from one row to the next, more
4096than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004097from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004098part. A user of c_lnotab desiring to find the source line number
4099corresponding to a bytecode address A should do something like this
4100
4101 lineno = addr = 0
4102 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004103 addr += addr_incr
4104 if addr > A:
4105 return lineno
4106 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004107
4108In order for this to work, when the addr field increments by more than 255,
4109the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004110increment is < 256. So, in the example above, assemble_lnotab (it used
4111to be called com_set_lineno) should not (as was actually done until 2.2)
4112expand 300, 300 to 255, 255, 45, 45,
4113 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004114*/
4115
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004118{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119 int d_bytecode, d_lineno;
4120 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004121 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122
4123 d_bytecode = a->a_offset - a->a_lineno_off;
4124 d_lineno = i->i_lineno - a->a_lineno;
4125
4126 assert(d_bytecode >= 0);
4127 assert(d_lineno >= 0);
4128
4129 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004130 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004133 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134 nbytes = a->a_lnotab_off + 2 * ncodes;
4135 len = PyString_GET_SIZE(a->a_lnotab);
4136 if (nbytes >= len) {
4137 if (len * 2 < nbytes)
4138 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004139 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004140 len *= 2;
4141 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4142 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004143 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004144 lnotab = (unsigned char *)
4145 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004146 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 *lnotab++ = 255;
4148 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004149 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150 d_bytecode -= ncodes * 255;
4151 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004152 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153 assert(d_bytecode <= 255);
4154 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004155 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156 nbytes = a->a_lnotab_off + 2 * ncodes;
4157 len = PyString_GET_SIZE(a->a_lnotab);
4158 if (nbytes >= len) {
4159 if (len * 2 < nbytes)
4160 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004161 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 len *= 2;
4163 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4164 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004165 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004166 lnotab = (unsigned char *)
4167 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004169 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004171 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004173 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175 d_lineno -= ncodes * 255;
4176 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004177 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179 len = PyString_GET_SIZE(a->a_lnotab);
4180 if (a->a_lnotab_off + 2 >= len) {
4181 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004182 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004183 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004184 lnotab = (unsigned char *)
4185 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004186
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187 a->a_lnotab_off += 2;
4188 if (d_bytecode) {
4189 *lnotab++ = d_bytecode;
4190 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004191 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004192 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193 *lnotab++ = 0;
4194 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196 a->a_lineno = i->i_lineno;
4197 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004198 return 1;
4199}
4200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201/* assemble_emit()
4202 Extend the bytecode with a new instruction.
4203 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004204*/
4205
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004206static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004207assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004208{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004209 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004210 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 char *code;
4212
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004213 size = instrsize(i);
4214 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004216 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004219 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220 if (a->a_offset + size >= len) {
4221 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004222 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004223 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004224 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4225 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004226 if (size == 6) {
4227 assert(i->i_hasarg);
4228 *code++ = (char)EXTENDED_ARG;
4229 *code++ = ext & 0xff;
4230 *code++ = ext >> 8;
4231 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004232 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004234 if (i->i_hasarg) {
4235 assert(size == 3 || size == 6);
4236 *code++ = arg & 0xff;
4237 *code++ = arg >> 8;
4238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004239 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004240}
4241
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004242static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004243assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004244{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004245 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004246 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004247 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004249 /* Compute the size of each block and fixup jump args.
4250 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004251start:
4252 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004253 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004254 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004255 bsize = blocksize(b);
4256 b->b_offset = totsize;
4257 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004258 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004259 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4261 bsize = b->b_offset;
4262 for (i = 0; i < b->b_iused; i++) {
4263 struct instr *instr = &b->b_instr[i];
4264 /* Relative jumps are computed relative to
4265 the instruction pointer after fetching
4266 the jump instruction.
4267 */
4268 bsize += instrsize(instr);
4269 if (instr->i_jabs)
4270 instr->i_oparg = instr->i_target->b_offset;
4271 else if (instr->i_jrel) {
4272 int delta = instr->i_target->b_offset - bsize;
4273 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004274 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004275 else
4276 continue;
4277 if (instr->i_oparg > 0xffff)
4278 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004279 }
4280 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004281
4282 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004283 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004284 with a better solution.
4285
4286 In the meantime, should the goto be dropped in favor
4287 of a loop?
4288
4289 The issue is that in the first loop blocksize() is called
4290 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004291 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004292 i_oparg is calculated in the second loop above.
4293
4294 So we loop until we stop seeing new EXTENDED_ARGs.
4295 The only EXTENDED_ARGs that could be popping up are
4296 ones in jump instructions. So this should converge
4297 fairly quickly.
4298 */
4299 if (last_extended_arg_count != extended_arg_count) {
4300 last_extended_arg_count = extended_arg_count;
4301 goto start;
4302 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004303}
4304
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004305static PyObject *
4306dict_keys_inorder(PyObject *dict, int offset)
4307{
4308 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004309 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004310
4311 tuple = PyTuple_New(size);
4312 if (tuple == NULL)
4313 return NULL;
4314 while (PyDict_Next(dict, &pos, &k, &v)) {
4315 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004316 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004317 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004318 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004319 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004320 PyTuple_SET_ITEM(tuple, i - offset, k);
4321 }
4322 return tuple;
4323}
4324
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004325static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004327{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004328 PySTEntryObject *ste = c->u->u_ste;
4329 int flags = 0, n;
4330 if (ste->ste_type != ModuleBlock)
4331 flags |= CO_NEWLOCALS;
4332 if (ste->ste_type == FunctionBlock) {
4333 if (!ste->ste_unoptimized)
4334 flags |= CO_OPTIMIZED;
4335 if (ste->ste_nested)
4336 flags |= CO_NESTED;
4337 if (ste->ste_generator)
4338 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004339 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004340 if (ste->ste_varargs)
4341 flags |= CO_VARARGS;
4342 if (ste->ste_varkeywords)
4343 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004344 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004346
4347 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004348 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004349
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004350 n = PyDict_Size(c->u->u_freevars);
4351 if (n < 0)
4352 return -1;
4353 if (n == 0) {
4354 n = PyDict_Size(c->u->u_cellvars);
4355 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004356 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004357 if (n == 0) {
4358 flags |= CO_NOFREE;
4359 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004360 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004361
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004362 return flags;
4363}
4364
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365static PyCodeObject *
4366makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004367{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368 PyObject *tmp;
4369 PyCodeObject *co = NULL;
4370 PyObject *consts = NULL;
4371 PyObject *names = NULL;
4372 PyObject *varnames = NULL;
4373 PyObject *filename = NULL;
4374 PyObject *name = NULL;
4375 PyObject *freevars = NULL;
4376 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004377 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380 tmp = dict_keys_inorder(c->u->u_consts, 0);
4381 if (!tmp)
4382 goto error;
4383 consts = PySequence_List(tmp); /* optimize_code requires a list */
4384 Py_DECREF(tmp);
4385
4386 names = dict_keys_inorder(c->u->u_names, 0);
4387 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4388 if (!consts || !names || !varnames)
4389 goto error;
4390
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004391 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4392 if (!cellvars)
4393 goto error;
4394 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4395 if (!freevars)
4396 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004397 filename = PyString_FromString(c->c_filename);
4398 if (!filename)
4399 goto error;
4400
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004401 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004402 flags = compute_code_flags(c);
4403 if (flags < 0)
4404 goto error;
4405
4406 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4407 if (!bytecode)
4408 goto error;
4409
4410 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4411 if (!tmp)
4412 goto error;
4413 Py_DECREF(consts);
4414 consts = tmp;
4415
4416 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4417 bytecode, consts, names, varnames,
4418 freevars, cellvars,
4419 filename, c->u->u_name,
4420 c->u->u_firstlineno,
4421 a->a_lnotab);
4422 error:
4423 Py_XDECREF(consts);
4424 Py_XDECREF(names);
4425 Py_XDECREF(varnames);
4426 Py_XDECREF(filename);
4427 Py_XDECREF(name);
4428 Py_XDECREF(freevars);
4429 Py_XDECREF(cellvars);
4430 Py_XDECREF(bytecode);
4431 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004432}
4433
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434static PyCodeObject *
4435assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004436{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004437 basicblock *b, *entryblock;
4438 struct assembler a;
4439 int i, j, nblocks;
4440 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442 /* Make sure every block that falls off the end returns None.
4443 XXX NEXT_BLOCK() isn't quite right, because if the last
4444 block ends with a jump or return b_next shouldn't set.
4445 */
4446 if (!c->u->u_curblock->b_return) {
4447 NEXT_BLOCK(c);
4448 if (addNone)
4449 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4450 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004451 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004452
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004453 nblocks = 0;
4454 entryblock = NULL;
4455 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4456 nblocks++;
4457 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004458 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004459
Neal Norwitzed657552006-07-10 00:04:44 +00004460 /* Set firstlineno if it wasn't explicitly set. */
4461 if (!c->u->u_firstlineno) {
4462 if (entryblock && entryblock->b_instr)
4463 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4464 else
4465 c->u->u_firstlineno = 1;
4466 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4468 goto error;
4469 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004470
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004471 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004472 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004473
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004474 /* Emit code in reverse postorder from dfs. */
4475 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004476 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004477 for (j = 0; j < b->b_iused; j++)
4478 if (!assemble_emit(&a, &b->b_instr[j]))
4479 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004480 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004482 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4483 goto error;
4484 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4485 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004486
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004487 co = makecode(c, &a);
4488 error:
4489 assemble_free(&a);
4490 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004491}