blob: 4dfc42d92893147daa3cd3e2200548c994130494 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
Georg Brandla5fe3ef2006-10-08 07:12:23 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
194static int expr_constant(expr_ty e);
195
Guido van Rossumc2e20742006-02-27 22:32:47 +0000196static int compiler_with(struct compiler *, stmt_ty);
197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198static PyCodeObject *assemble(struct compiler *, int addNone);
199static PyObject *__doc__;
200
201PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000202_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000203{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 /* Name mangling: __private becomes _classname__private.
205 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 const char *p, *name = PyString_AsString(ident);
207 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000209 if (privateobj == NULL || !PyString_Check(privateobj) ||
210 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000213 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000214 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 nlen = strlen(name);
216 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 /* Strip leading underscores from class name */
221 while (*p == '_')
222 p++;
223 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000228 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
229 if (!ident)
230 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000231 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000232 buffer = PyString_AS_STRING(ident);
233 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234 strncpy(buffer+1, p, plen);
235 strcpy(buffer+1+plen, name);
236 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000237}
238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239static int
240compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000241{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000242 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000244 c->c_stack = PyList_New(0);
245 if (!c->c_stack)
246 return 0;
247
248 return 1;
249}
250
251PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000252PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000253 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254{
255 struct compiler c;
256 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 PyCompilerFlags local_flags;
258 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000260 if (!__doc__) {
261 __doc__ = PyString_InternFromString("__doc__");
262 if (!__doc__)
263 return NULL;
264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265
266 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000267 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000270 c.c_future = PyFuture_FromAST(mod, filename);
271 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000272 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000273 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000274 local_flags.cf_flags = 0;
275 flags = &local_flags;
276 }
277 merged = c.c_future->ff_features | flags->cf_flags;
278 c.c_future->ff_features = merged;
279 flags->cf_flags = merged;
280 c.c_flags = flags;
281 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000282
283 c.c_st = PySymtable_Build(mod, filename, c.c_future);
284 if (c.c_st == NULL) {
285 if (!PyErr_Occurred())
286 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000287 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288 }
289
290 /* XXX initialize to NULL for now, need to handle */
291 c.c_encoding = NULL;
292
293 co = compiler_mod(&c, mod);
294
Thomas Wouters1175c432006-02-27 22:49:54 +0000295 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000297 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000298 return co;
299}
300
301PyCodeObject *
302PyNode_Compile(struct _node *n, const char *filename)
303{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000304 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000305 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000306 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000307 if (!arena)
308 return NULL;
309 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000310 if (mod)
311 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000312 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000313 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000314}
315
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000317compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000318{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319 if (c->c_st)
320 PySymtable_Free(c->c_st);
321 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000322 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000324}
325
Guido van Rossum79f25d91997-04-29 20:08:16 +0000326static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000328{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000330 PyObject *v, *k;
331 PyObject *dict = PyDict_New();
332 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000333
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334 n = PyList_Size(list);
335 for (i = 0; i < n; i++) {
336 v = PyInt_FromLong(i);
337 if (!v) {
338 Py_DECREF(dict);
339 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000340 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000341 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000342 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000343 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
344 Py_XDECREF(k);
345 Py_DECREF(v);
346 Py_DECREF(dict);
347 return NULL;
348 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000349 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000351 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352 return dict;
353}
354
355/* Return new dict containing names from src that match scope(s).
356
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000357src is a symbol table dictionary. If the scope of a name matches
358either scope_type or flag is set, insert it into the new dict. The
359values are integers, starting at offset and increasing by one for
360each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361*/
362
363static PyObject *
364dictbytype(PyObject *src, int scope_type, int flag, int offset)
365{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367 PyObject *k, *v, *dest = PyDict_New();
368
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000369 assert(offset >= 0);
370 if (dest == NULL)
371 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000372
373 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000374 /* XXX this should probably be a macro in symtable.h */
375 assert(PyInt_Check(v));
376 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000378 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
379 PyObject *tuple, *item = PyInt_FromLong(i);
380 if (item == NULL) {
381 Py_DECREF(dest);
382 return NULL;
383 }
384 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000385 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000386 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
387 Py_DECREF(item);
388 Py_DECREF(dest);
389 Py_XDECREF(tuple);
390 return NULL;
391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000393 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395 }
396 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000397}
398
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000399/* Begin: Peephole optimizations ----------------------------------------- */
400
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000401#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000402#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000403#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
404#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000405#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000406#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000407#define ISBASICBLOCK(blocks, start, bytes) \
408 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000409
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000410/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000412 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000413 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000414 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000415 Bails out with no change if one or more of the LOAD_CONSTs is missing.
416 Also works for BUILD_LIST when followed by an "in" or "not in" test.
417*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418static int
419tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
420{
421 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000422 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000423
424 /* Pre-conditions */
425 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000426 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000427 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000428 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000429 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000430
431 /* Buildup new tuple of constants */
432 newconst = PyTuple_New(n);
433 if (newconst == NULL)
434 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000435 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000436 for (i=0 ; i<n ; i++) {
437 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000438 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000439 constant = PyList_GET_ITEM(consts, arg);
440 Py_INCREF(constant);
441 PyTuple_SET_ITEM(newconst, i, constant);
442 }
443
444 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000445 if (PyList_Append(consts, newconst)) {
446 Py_DECREF(newconst);
447 return 0;
448 }
449 Py_DECREF(newconst);
450
451 /* Write NOPs over old LOAD_CONSTS and
452 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
453 memset(codestr, NOP, n*3);
454 codestr[n*3] = LOAD_CONST;
455 SETARG(codestr, (n*3), len_consts);
456 return 1;
457}
458
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000459/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000460 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000461 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000463 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000464 Abandons the transformation if the folding fails (i.e. 1+'a').
465 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000466 is below a threshold value. That keeps pyc files from
467 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000468*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000469static int
470fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
471{
472 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000473 Py_ssize_t len_consts, size;
474 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000475
476 /* Pre-conditions */
477 assert(PyList_CheckExact(consts));
478 assert(codestr[0] == LOAD_CONST);
479 assert(codestr[3] == LOAD_CONST);
480
481 /* Create new constant */
482 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
483 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
484 opcode = codestr[6];
485 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000486 case BINARY_POWER:
487 newconst = PyNumber_Power(v, w, Py_None);
488 break;
489 case BINARY_MULTIPLY:
490 newconst = PyNumber_Multiply(v, w);
491 break;
492 case BINARY_DIVIDE:
493 /* Cannot fold this operation statically since
494 the result can depend on the run-time presence
495 of the -Qnew flag */
496 return 0;
497 case BINARY_TRUE_DIVIDE:
498 newconst = PyNumber_TrueDivide(v, w);
499 break;
500 case BINARY_FLOOR_DIVIDE:
501 newconst = PyNumber_FloorDivide(v, w);
502 break;
503 case BINARY_MODULO:
504 newconst = PyNumber_Remainder(v, w);
505 break;
506 case BINARY_ADD:
507 newconst = PyNumber_Add(v, w);
508 break;
509 case BINARY_SUBTRACT:
510 newconst = PyNumber_Subtract(v, w);
511 break;
512 case BINARY_SUBSCR:
513 newconst = PyObject_GetItem(v, w);
514 break;
515 case BINARY_LSHIFT:
516 newconst = PyNumber_Lshift(v, w);
517 break;
518 case BINARY_RSHIFT:
519 newconst = PyNumber_Rshift(v, w);
520 break;
521 case BINARY_AND:
522 newconst = PyNumber_And(v, w);
523 break;
524 case BINARY_XOR:
525 newconst = PyNumber_Xor(v, w);
526 break;
527 case BINARY_OR:
528 newconst = PyNumber_Or(v, w);
529 break;
530 default:
531 /* Called with an unknown opcode */
532 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000533 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000534 opcode);
535 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000536 }
537 if (newconst == NULL) {
538 PyErr_Clear();
539 return 0;
540 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000541 size = PyObject_Size(newconst);
542 if (size == -1)
543 PyErr_Clear();
544 else if (size > 20) {
545 Py_DECREF(newconst);
546 return 0;
547 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000548
549 /* Append folded constant into consts table */
550 len_consts = PyList_GET_SIZE(consts);
551 if (PyList_Append(consts, newconst)) {
552 Py_DECREF(newconst);
553 return 0;
554 }
555 Py_DECREF(newconst);
556
557 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
558 memset(codestr, NOP, 4);
559 codestr[4] = LOAD_CONST;
560 SETARG(codestr, 4, len_consts);
561 return 1;
562}
563
Raymond Hettinger80121492005-02-20 12:41:32 +0000564static int
565fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
566{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000567 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000568 Py_ssize_t len_consts;
569 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000570
571 /* Pre-conditions */
572 assert(PyList_CheckExact(consts));
573 assert(codestr[0] == LOAD_CONST);
574
575 /* Create new constant */
576 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
577 opcode = codestr[3];
578 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000579 case UNARY_NEGATIVE:
580 /* Preserve the sign of -0.0 */
581 if (PyObject_IsTrue(v) == 1)
582 newconst = PyNumber_Negative(v);
583 break;
584 case UNARY_CONVERT:
585 newconst = PyObject_Repr(v);
586 break;
587 case UNARY_INVERT:
588 newconst = PyNumber_Invert(v);
589 break;
590 default:
591 /* Called with an unknown opcode */
592 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000593 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000594 opcode);
595 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000596 }
597 if (newconst == NULL) {
598 PyErr_Clear();
599 return 0;
600 }
601
602 /* Append folded constant into consts table */
603 len_consts = PyList_GET_SIZE(consts);
604 if (PyList_Append(consts, newconst)) {
605 Py_DECREF(newconst);
606 return 0;
607 }
608 Py_DECREF(newconst);
609
610 /* Write NOP LOAD_CONST newconst */
611 codestr[0] = NOP;
612 codestr[1] = LOAD_CONST;
613 SETARG(codestr, 1, len_consts);
614 return 1;
615}
616
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000617static unsigned int *
618markblocks(unsigned char *code, int len)
619{
Anthony Baxter7b782b62006-04-11 12:01:56 +0000620 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000621 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000622
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000623 if (blocks == NULL) {
624 PyErr_NoMemory();
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000625 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000626 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000627 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000628
629 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000630 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
631 opcode = code[i];
632 switch (opcode) {
633 case FOR_ITER:
634 case JUMP_FORWARD:
635 case JUMP_IF_FALSE:
636 case JUMP_IF_TRUE:
637 case JUMP_ABSOLUTE:
638 case CONTINUE_LOOP:
639 case SETUP_LOOP:
640 case SETUP_EXCEPT:
641 case SETUP_FINALLY:
642 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000643 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000644 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000645 }
646 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000647 /* Build block numbers in the second pass */
648 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000649 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000650 blocks[i] = blockcnt;
651 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000652 return blocks;
653}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000654
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000655/* Perform basic peephole optimizations to components of a code object.
656 The consts object should still be in list form to allow new constants
657 to be appended.
658
659 To keep the optimizer simple, it bails out (does nothing) for code
660 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000661 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000662 the lineno table has complex encoding for gaps >= 255.
663
664 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000665 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000666 smaller. For those that reduce size, the gaps are initially filled with
667 NOPs. Later those NOPs are removed and the jump addresses retargeted in
668 a single pass. Line numbering is adjusted accordingly. */
669
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000670static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000671optimize_code(PyObject *code, PyObject* consts, PyObject *names,
672 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000673{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000674 Py_ssize_t i, j, codelen;
675 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000676 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000677 unsigned char *codestr = NULL;
678 unsigned char *lineno;
679 int *addrmap = NULL;
680 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000681 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000682 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000683 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000684
Raymond Hettingereffb3932004-10-30 08:55:08 +0000685 /* Bail out if an exception is set */
686 if (PyErr_Occurred())
687 goto exitUnchanged;
688
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000689 /* Bypass optimization when the lineno table is too complex */
690 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000691 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000692 tabsiz = PyString_GET_SIZE(lineno_obj);
693 if (memchr(lineno, 255, tabsiz) != NULL)
694 goto exitUnchanged;
695
Raymond Hettingera12fa142004-08-24 04:34:16 +0000696 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000697 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000698 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000699 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000700 goto exitUnchanged;
701
702 /* Make a modifiable copy of the code string */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000703 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000704 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000705 goto exitUnchanged;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000706 codestr = (unsigned char *)memcpy(codestr,
707 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000708
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000709 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000710 the various transformation patterns to look ahead several
711 instructions without additional checks to make sure they are not
712 looking beyond the end of the code string.
713 */
714 if (codestr[codelen-1] != RETURN_VALUE)
715 goto exitUnchanged;
716
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000717 /* Mapping to new jump targets after NOPs are removed */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000718 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000719 if (addrmap == NULL)
720 goto exitUnchanged;
721
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000722 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000723 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000724 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000725 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000726
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000727 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000728 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000729
730 lastlc = cumlc;
731 cumlc = 0;
732
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000733 switch (opcode) {
734
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000735 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
736 with JUMP_IF_TRUE POP_TOP */
737 case UNARY_NOT:
738 if (codestr[i+1] != JUMP_IF_FALSE ||
739 codestr[i+4] != POP_TOP ||
740 !ISBASICBLOCK(blocks,i,5))
741 continue;
742 tgt = GETJUMPTGT(codestr, (i+1));
743 if (codestr[tgt] != POP_TOP)
744 continue;
745 j = GETARG(codestr, i+1) + 1;
746 codestr[i] = JUMP_IF_TRUE;
747 SETARG(codestr, i, j);
748 codestr[i+3] = POP_TOP;
749 codestr[i+4] = NOP;
750 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000751
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000752 /* not a is b --> a is not b
753 not a in b --> a not in b
754 not a is not b --> a is b
755 not a not in b --> a in b
756 */
757 case COMPARE_OP:
758 j = GETARG(codestr, i);
759 if (j < 6 || j > 9 ||
760 codestr[i+3] != UNARY_NOT ||
761 !ISBASICBLOCK(blocks,i,4))
762 continue;
763 SETARG(codestr, i, (j^1));
764 codestr[i+3] = NOP;
765 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000766
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000767 /* Replace LOAD_GLOBAL/LOAD_NAME None
768 with LOAD_CONST None */
769 case LOAD_NAME:
770 case LOAD_GLOBAL:
771 j = GETARG(codestr, i);
772 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
773 if (name == NULL || strcmp(name, "None") != 0)
774 continue;
775 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
Raymond Hettingerd882e362007-03-02 19:19:05 +0000776 if (PyList_GET_ITEM(consts, j) == Py_None)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000777 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000778 }
Raymond Hettingerd882e362007-03-02 19:19:05 +0000779 if (j == PyList_GET_SIZE(consts)) {
780 if (PyList_Append(consts, Py_None) == -1)
781 goto exitUnchanged;
782 }
783 assert(PyList_GET_ITEM(consts, j) == Py_None);
784 codestr[i] = LOAD_CONST;
785 SETARG(codestr, i, j);
786 cumlc = lastlc + 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000787 break;
788
789 /* Skip over LOAD_CONST trueconst
790 JUMP_IF_FALSE xx POP_TOP */
791 case LOAD_CONST:
792 cumlc = lastlc + 1;
793 j = GETARG(codestr, i);
794 if (codestr[i+3] != JUMP_IF_FALSE ||
795 codestr[i+6] != POP_TOP ||
796 !ISBASICBLOCK(blocks,i,7) ||
797 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
798 continue;
799 memset(codestr+i, NOP, 7);
800 cumlc = 0;
801 break;
802
803 /* Try to fold tuples of constants (includes a case for lists
804 which are only used for "in" and "not in" tests).
805 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
806 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
807 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
808 case BUILD_TUPLE:
809 case BUILD_LIST:
810 j = GETARG(codestr, i);
811 h = i - 3 * j;
812 if (h >= 0 &&
813 j <= lastlc &&
814 ((opcode == BUILD_TUPLE &&
815 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
816 (opcode == BUILD_LIST &&
817 codestr[i+3]==COMPARE_OP &&
818 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
819 (GETARG(codestr,i+3)==6 ||
820 GETARG(codestr,i+3)==7))) &&
821 tuple_of_constants(&codestr[h], j, consts)) {
822 assert(codestr[i] == LOAD_CONST);
823 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000824 break;
825 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000826 if (codestr[i+3] != UNPACK_SEQUENCE ||
827 !ISBASICBLOCK(blocks,i,6) ||
828 j != GETARG(codestr, i+3))
829 continue;
830 if (j == 1) {
831 memset(codestr+i, NOP, 6);
832 } else if (j == 2) {
833 codestr[i] = ROT_TWO;
834 memset(codestr+i+1, NOP, 5);
835 } else if (j == 3) {
836 codestr[i] = ROT_THREE;
837 codestr[i+1] = ROT_TWO;
838 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000839 }
840 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000841
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000842 /* Fold binary ops on constants.
843 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
844 case BINARY_POWER:
845 case BINARY_MULTIPLY:
846 case BINARY_TRUE_DIVIDE:
847 case BINARY_FLOOR_DIVIDE:
848 case BINARY_MODULO:
849 case BINARY_ADD:
850 case BINARY_SUBTRACT:
851 case BINARY_SUBSCR:
852 case BINARY_LSHIFT:
853 case BINARY_RSHIFT:
854 case BINARY_AND:
855 case BINARY_XOR:
856 case BINARY_OR:
857 if (lastlc >= 2 &&
858 ISBASICBLOCK(blocks, i-6, 7) &&
859 fold_binops_on_constants(&codestr[i-6], consts)) {
860 i -= 2;
861 assert(codestr[i] == LOAD_CONST);
862 cumlc = 1;
863 }
864 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000865
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000866 /* Fold unary ops on constants.
867 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
868 case UNARY_NEGATIVE:
869 case UNARY_CONVERT:
870 case UNARY_INVERT:
871 if (lastlc >= 1 &&
872 ISBASICBLOCK(blocks, i-3, 4) &&
873 fold_unaryops_on_constants(&codestr[i-3], consts)) {
874 i -= 2;
875 assert(codestr[i] == LOAD_CONST);
876 cumlc = 1;
877 }
878 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000879
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000880 /* Simplify conditional jump to conditional jump where the
881 result of the first test implies the success of a similar
882 test or the failure of the opposite test.
883 Arises in code like:
884 "if a and b:"
885 "if a or b:"
886 "a and b or c"
887 "(a and b) and c"
888 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
889 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
890 where y+3 is the instruction following the second test.
891 */
892 case JUMP_IF_FALSE:
893 case JUMP_IF_TRUE:
894 tgt = GETJUMPTGT(codestr, i);
895 j = codestr[tgt];
896 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
897 if (j == opcode) {
898 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
899 SETARG(codestr, i, tgttgt);
900 } else {
901 tgt -= i;
902 SETARG(codestr, i, tgt);
903 }
904 break;
905 }
906 /* Intentional fallthrough */
907
908 /* Replace jumps to unconditional jumps */
909 case FOR_ITER:
910 case JUMP_FORWARD:
911 case JUMP_ABSOLUTE:
912 case CONTINUE_LOOP:
913 case SETUP_LOOP:
914 case SETUP_EXCEPT:
915 case SETUP_FINALLY:
916 tgt = GETJUMPTGT(codestr, i);
917 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
918 continue;
919 tgttgt = GETJUMPTGT(codestr, tgt);
920 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
921 opcode = JUMP_ABSOLUTE;
922 if (!ABSOLUTE_JUMP(opcode))
923 tgttgt -= i + 3; /* Calc relative jump addr */
924 if (tgttgt < 0) /* No backward relative jumps */
925 continue;
926 codestr[i] = opcode;
927 SETARG(codestr, i, tgttgt);
928 break;
929
930 case EXTENDED_ARG:
931 goto exitUnchanged;
932
933 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
934 case RETURN_VALUE:
935 if (i+4 >= codelen ||
936 codestr[i+4] != RETURN_VALUE ||
937 !ISBASICBLOCK(blocks,i,5))
938 continue;
939 memset(codestr+i+1, NOP, 4);
940 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000941 }
942 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000943
944 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000945 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
946 addrmap[i] = i - nops;
947 if (codestr[i] == NOP)
948 nops++;
949 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000950 cum_orig_line = 0;
951 last_line = 0;
952 for (i=0 ; i < tabsiz ; i+=2) {
953 cum_orig_line += lineno[i];
954 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000955 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000956 lineno[i] =((unsigned char)(new_line - last_line));
957 last_line = new_line;
958 }
959
960 /* Remove NOPs and fixup jump targets */
961 for (i=0, h=0 ; i<codelen ; ) {
962 opcode = codestr[i];
963 switch (opcode) {
964 case NOP:
965 i++;
966 continue;
967
968 case JUMP_ABSOLUTE:
969 case CONTINUE_LOOP:
970 j = addrmap[GETARG(codestr, i)];
971 SETARG(codestr, i, j);
972 break;
973
974 case FOR_ITER:
975 case JUMP_FORWARD:
976 case JUMP_IF_FALSE:
977 case JUMP_IF_TRUE:
978 case SETUP_LOOP:
979 case SETUP_EXCEPT:
980 case SETUP_FINALLY:
981 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
982 SETARG(codestr, i, j);
983 break;
984 }
985 adj = CODESIZE(opcode);
986 while (adj--)
987 codestr[h++] = codestr[i++];
988 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000989 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000990
991 code = PyString_FromStringAndSize((char *)codestr, h);
992 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000993 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000994 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000995 return code;
996
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000997 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000998 if (blocks != NULL)
999 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +00001000 if (addrmap != NULL)
1001 PyMem_Free(addrmap);
1002 if (codestr != NULL)
1003 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +00001004 Py_INCREF(code);
1005 return code;
1006}
1007
Raymond Hettinger2c31a052004-09-22 18:44:21 +00001008/* End: Peephole optimizations ----------------------------------------- */
1009
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001010/*
1011
1012Leave this debugging code for just a little longer.
1013
1014static void
1015compiler_display_symbols(PyObject *name, PyObject *symbols)
1016{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001017PyObject *key, *value;
1018int flags;
1019Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001021fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1022while (PyDict_Next(symbols, &pos, &key, &value)) {
1023flags = PyInt_AsLong(value);
1024fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1025if (flags & DEF_GLOBAL)
1026fprintf(stderr, " declared_global");
1027if (flags & DEF_LOCAL)
1028fprintf(stderr, " local");
1029if (flags & DEF_PARAM)
1030fprintf(stderr, " param");
1031if (flags & DEF_STAR)
1032fprintf(stderr, " stararg");
1033if (flags & DEF_DOUBLESTAR)
1034fprintf(stderr, " starstar");
1035if (flags & DEF_INTUPLE)
1036fprintf(stderr, " tuple");
1037if (flags & DEF_FREE)
1038fprintf(stderr, " free");
1039if (flags & DEF_FREE_GLOBAL)
1040fprintf(stderr, " global");
1041if (flags & DEF_FREE_CLASS)
1042fprintf(stderr, " free/class");
1043if (flags & DEF_IMPORT)
1044fprintf(stderr, " import");
1045fprintf(stderr, "\n");
1046}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047 fprintf(stderr, "\n");
1048}
1049*/
1050
1051static void
1052compiler_unit_check(struct compiler_unit *u)
1053{
1054 basicblock *block;
1055 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1056 assert(block != (void *)0xcbcbcbcb);
1057 assert(block != (void *)0xfbfbfbfb);
1058 assert(block != (void *)0xdbdbdbdb);
1059 if (block->b_instr != NULL) {
1060 assert(block->b_ialloc > 0);
1061 assert(block->b_iused > 0);
1062 assert(block->b_ialloc >= block->b_iused);
1063 }
1064 else {
1065 assert (block->b_iused == 0);
1066 assert (block->b_ialloc == 0);
1067 }
1068 }
1069}
1070
1071static void
1072compiler_unit_free(struct compiler_unit *u)
1073{
1074 basicblock *b, *next;
1075
1076 compiler_unit_check(u);
1077 b = u->u_blocks;
1078 while (b != NULL) {
1079 if (b->b_instr)
1080 PyObject_Free((void *)b->b_instr);
1081 next = b->b_list;
1082 PyObject_Free((void *)b);
1083 b = next;
1084 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001085 Py_CLEAR(u->u_ste);
1086 Py_CLEAR(u->u_name);
1087 Py_CLEAR(u->u_consts);
1088 Py_CLEAR(u->u_names);
1089 Py_CLEAR(u->u_varnames);
1090 Py_CLEAR(u->u_freevars);
1091 Py_CLEAR(u->u_cellvars);
1092 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093 PyObject_Free(u);
1094}
1095
1096static int
1097compiler_enter_scope(struct compiler *c, identifier name, void *key,
1098 int lineno)
1099{
1100 struct compiler_unit *u;
1101
Anthony Baxter7b782b62006-04-11 12:01:56 +00001102 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1103 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001104 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001105 PyErr_NoMemory();
1106 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001107 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001108 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109 u->u_argcount = 0;
1110 u->u_ste = PySymtable_Lookup(c->c_st, key);
1111 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 compiler_unit_free(u);
1113 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001114 }
1115 Py_INCREF(name);
1116 u->u_name = name;
1117 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1118 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +00001119 if (!u->u_varnames || !u->u_cellvars) {
1120 compiler_unit_free(u);
1121 return 0;
1122 }
1123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001125 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +00001126 if (!u->u_freevars) {
1127 compiler_unit_free(u);
1128 return 0;
1129 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130
1131 u->u_blocks = NULL;
1132 u->u_tmpname = 0;
1133 u->u_nfblocks = 0;
1134 u->u_firstlineno = lineno;
1135 u->u_lineno = 0;
1136 u->u_lineno_set = false;
1137 u->u_consts = PyDict_New();
1138 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001139 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return 0;
1141 }
1142 u->u_names = PyDict_New();
1143 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001144 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 return 0;
1146 }
1147
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001148 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149
1150 /* Push the old compiler_unit on the stack. */
1151 if (c->u) {
1152 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001153 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
1154 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001155 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001156 return 0;
1157 }
1158 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001159 u->u_private = c->u->u_private;
1160 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 }
1162 c->u = u;
1163
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001164 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001165 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166 return 0;
1167
1168 return 1;
1169}
1170
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001171static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172compiler_exit_scope(struct compiler *c)
1173{
1174 int n;
1175 PyObject *wrapper;
1176
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001177 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178 compiler_unit_free(c->u);
1179 /* Restore c->u to the parent unit. */
1180 n = PyList_GET_SIZE(c->c_stack) - 1;
1181 if (n >= 0) {
1182 wrapper = PyList_GET_ITEM(c->c_stack, n);
1183 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001184 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001186 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 compiler_unit_check(c->u);
1188 }
1189 else
1190 c->u = NULL;
1191
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192}
1193
Guido van Rossumc2e20742006-02-27 22:32:47 +00001194/* Allocate a new "anonymous" local variable.
1195 Used by list comprehensions and with statements.
1196*/
1197
1198static PyObject *
1199compiler_new_tmpname(struct compiler *c)
1200{
1201 char tmpname[256];
1202 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1203 return PyString_FromString(tmpname);
1204}
1205
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206/* Allocate a new block and return a pointer to it.
1207 Returns NULL on error.
1208*/
1209
1210static basicblock *
1211compiler_new_block(struct compiler *c)
1212{
1213 basicblock *b;
1214 struct compiler_unit *u;
1215
1216 u = c->u;
1217 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001218 if (b == NULL) {
1219 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001222 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001223 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001224 b->b_list = u->u_blocks;
1225 u->u_blocks = b;
1226 return b;
1227}
1228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001229static basicblock *
1230compiler_use_new_block(struct compiler *c)
1231{
1232 basicblock *block = compiler_new_block(c);
1233 if (block == NULL)
1234 return NULL;
1235 c->u->u_curblock = block;
1236 return block;
1237}
1238
1239static basicblock *
1240compiler_next_block(struct compiler *c)
1241{
1242 basicblock *block = compiler_new_block(c);
1243 if (block == NULL)
1244 return NULL;
1245 c->u->u_curblock->b_next = block;
1246 c->u->u_curblock = block;
1247 return block;
1248}
1249
1250static basicblock *
1251compiler_use_next_block(struct compiler *c, basicblock *block)
1252{
1253 assert(block != NULL);
1254 c->u->u_curblock->b_next = block;
1255 c->u->u_curblock = block;
1256 return block;
1257}
1258
1259/* Returns the offset of the next instruction in the current block's
1260 b_instr array. Resizes the b_instr as necessary.
1261 Returns -1 on failure.
1262 */
1263
1264static int
1265compiler_next_instr(struct compiler *c, basicblock *b)
1266{
1267 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001268 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001269 b->b_instr = (struct instr *)PyObject_Malloc(
1270 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001271 if (b->b_instr == NULL) {
1272 PyErr_NoMemory();
1273 return -1;
1274 }
1275 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1276 memset((char *)b->b_instr, 0,
1277 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001278 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001280 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 size_t oldsize, newsize;
1282 oldsize = b->b_ialloc * sizeof(struct instr);
1283 newsize = oldsize << 1;
1284 if (newsize == 0) {
1285 PyErr_NoMemory();
1286 return -1;
1287 }
1288 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001289 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +00001290 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001291 if (tmp == NULL) {
1292 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001293 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001294 }
1295 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1297 }
1298 return b->b_iused++;
1299}
1300
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00001301/* Set the i_lineno member of the instruction at offset off if the
1302 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +00001303 already been set. If it has been set, the call has no effect.
1304
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00001305 The line number is reset in the following cases:
1306 - when entering a new scope
1307 - on each statement
1308 - on each expression that start a new line
1309 - before the "except" clause
1310 - before the "for" and "while" expressions
Jeremy Hylton12603c42006-04-01 16:18:02 +00001311 */
1312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001313static void
1314compiler_set_lineno(struct compiler *c, int off)
1315{
1316 basicblock *b;
1317 if (c->u->u_lineno_set)
1318 return;
1319 c->u->u_lineno_set = true;
1320 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001321 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001322}
1323
1324static int
1325opcode_stack_effect(int opcode, int oparg)
1326{
1327 switch (opcode) {
1328 case POP_TOP:
1329 return -1;
1330 case ROT_TWO:
1331 case ROT_THREE:
1332 return 0;
1333 case DUP_TOP:
1334 return 1;
1335 case ROT_FOUR:
1336 return 0;
1337
1338 case UNARY_POSITIVE:
1339 case UNARY_NEGATIVE:
1340 case UNARY_NOT:
1341 case UNARY_CONVERT:
1342 case UNARY_INVERT:
1343 return 0;
1344
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001345 case LIST_APPEND:
1346 return -2;
1347
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348 case BINARY_POWER:
1349 case BINARY_MULTIPLY:
1350 case BINARY_DIVIDE:
1351 case BINARY_MODULO:
1352 case BINARY_ADD:
1353 case BINARY_SUBTRACT:
1354 case BINARY_SUBSCR:
1355 case BINARY_FLOOR_DIVIDE:
1356 case BINARY_TRUE_DIVIDE:
1357 return -1;
1358 case INPLACE_FLOOR_DIVIDE:
1359 case INPLACE_TRUE_DIVIDE:
1360 return -1;
1361
1362 case SLICE+0:
1363 return 1;
1364 case SLICE+1:
1365 return 0;
1366 case SLICE+2:
1367 return 0;
1368 case SLICE+3:
1369 return -1;
1370
1371 case STORE_SLICE+0:
1372 return -2;
1373 case STORE_SLICE+1:
1374 return -3;
1375 case STORE_SLICE+2:
1376 return -3;
1377 case STORE_SLICE+3:
1378 return -4;
1379
1380 case DELETE_SLICE+0:
1381 return -1;
1382 case DELETE_SLICE+1:
1383 return -2;
1384 case DELETE_SLICE+2:
1385 return -2;
1386 case DELETE_SLICE+3:
1387 return -3;
1388
1389 case INPLACE_ADD:
1390 case INPLACE_SUBTRACT:
1391 case INPLACE_MULTIPLY:
1392 case INPLACE_DIVIDE:
1393 case INPLACE_MODULO:
1394 return -1;
1395 case STORE_SUBSCR:
1396 return -3;
1397 case DELETE_SUBSCR:
1398 return -2;
1399
1400 case BINARY_LSHIFT:
1401 case BINARY_RSHIFT:
1402 case BINARY_AND:
1403 case BINARY_XOR:
1404 case BINARY_OR:
1405 return -1;
1406 case INPLACE_POWER:
1407 return -1;
1408 case GET_ITER:
1409 return 0;
1410
1411 case PRINT_EXPR:
1412 return -1;
1413 case PRINT_ITEM:
1414 return -1;
1415 case PRINT_NEWLINE:
1416 return 0;
1417 case PRINT_ITEM_TO:
1418 return -2;
1419 case PRINT_NEWLINE_TO:
1420 return -1;
1421 case INPLACE_LSHIFT:
1422 case INPLACE_RSHIFT:
1423 case INPLACE_AND:
1424 case INPLACE_XOR:
1425 case INPLACE_OR:
1426 return -1;
1427 case BREAK_LOOP:
1428 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001429 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001430 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001431 case LOAD_LOCALS:
1432 return 1;
1433 case RETURN_VALUE:
1434 return -1;
1435 case IMPORT_STAR:
1436 return -1;
1437 case EXEC_STMT:
1438 return -3;
1439 case YIELD_VALUE:
1440 return 0;
1441
1442 case POP_BLOCK:
1443 return 0;
1444 case END_FINALLY:
1445 return -1; /* or -2 or -3 if exception occurred */
1446 case BUILD_CLASS:
1447 return -2;
1448
1449 case STORE_NAME:
1450 return -1;
1451 case DELETE_NAME:
1452 return 0;
1453 case UNPACK_SEQUENCE:
1454 return oparg-1;
1455 case FOR_ITER:
1456 return 1;
1457
1458 case STORE_ATTR:
1459 return -2;
1460 case DELETE_ATTR:
1461 return -1;
1462 case STORE_GLOBAL:
1463 return -1;
1464 case DELETE_GLOBAL:
1465 return 0;
1466 case DUP_TOPX:
1467 return oparg;
1468 case LOAD_CONST:
1469 return 1;
1470 case LOAD_NAME:
1471 return 1;
1472 case BUILD_TUPLE:
1473 case BUILD_LIST:
1474 return 1-oparg;
1475 case BUILD_MAP:
1476 return 1;
1477 case LOAD_ATTR:
1478 return 0;
1479 case COMPARE_OP:
1480 return -1;
1481 case IMPORT_NAME:
1482 return 0;
1483 case IMPORT_FROM:
1484 return 1;
1485
1486 case JUMP_FORWARD:
1487 case JUMP_IF_FALSE:
1488 case JUMP_IF_TRUE:
1489 case JUMP_ABSOLUTE:
1490 return 0;
1491
1492 case LOAD_GLOBAL:
1493 return 1;
1494
1495 case CONTINUE_LOOP:
1496 return 0;
1497 case SETUP_LOOP:
1498 return 0;
1499 case SETUP_EXCEPT:
1500 case SETUP_FINALLY:
1501 return 3; /* actually pushed by an exception */
1502
1503 case LOAD_FAST:
1504 return 1;
1505 case STORE_FAST:
1506 return -1;
1507 case DELETE_FAST:
1508 return 0;
1509
1510 case RAISE_VARARGS:
1511 return -oparg;
1512#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1513 case CALL_FUNCTION:
1514 return -NARGS(oparg);
1515 case CALL_FUNCTION_VAR:
1516 case CALL_FUNCTION_KW:
1517 return -NARGS(oparg)-1;
1518 case CALL_FUNCTION_VAR_KW:
1519 return -NARGS(oparg)-2;
1520#undef NARGS
1521 case MAKE_FUNCTION:
1522 return -oparg;
1523 case BUILD_SLICE:
1524 if (oparg == 3)
1525 return -2;
1526 else
1527 return -1;
1528
1529 case MAKE_CLOSURE:
1530 return -oparg;
1531 case LOAD_CLOSURE:
1532 return 1;
1533 case LOAD_DEREF:
1534 return 1;
1535 case STORE_DEREF:
1536 return -1;
1537 default:
1538 fprintf(stderr, "opcode = %d\n", opcode);
1539 Py_FatalError("opcode_stack_effect()");
1540
1541 }
1542 return 0; /* not reachable */
1543}
1544
1545/* Add an opcode with no argument.
1546 Returns 0 on failure, 1 on success.
1547*/
1548
1549static int
1550compiler_addop(struct compiler *c, int opcode)
1551{
1552 basicblock *b;
1553 struct instr *i;
1554 int off;
1555 off = compiler_next_instr(c, c->u->u_curblock);
1556 if (off < 0)
1557 return 0;
1558 b = c->u->u_curblock;
1559 i = &b->b_instr[off];
1560 i->i_opcode = opcode;
1561 i->i_hasarg = 0;
1562 if (opcode == RETURN_VALUE)
1563 b->b_return = 1;
1564 compiler_set_lineno(c, off);
1565 return 1;
1566}
1567
1568static int
1569compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1570{
1571 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001572 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001574 /* necessary to make sure types aren't coerced (e.g., int and long) */
Mark Dickinson2bebadf2008-01-21 21:54:47 +00001575 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1576 if (PyFloat_Check(o)) {
1577 double d = PyFloat_AS_DOUBLE(o);
1578 unsigned char* p = (unsigned char*) &d;
1579 /* all we need is to make the tuple different in either the 0.0
1580 * or -0.0 case from all others, just to avoid the "coercion".
1581 */
1582 if (*p==0 && p[sizeof(double)-1]==0)
1583 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1584 else
1585 t = PyTuple_Pack(2, o, o->ob_type);
1586 } else {
1587 t = PyTuple_Pack(2, o, o->ob_type);
1588 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001589 if (t == NULL)
1590 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001591
1592 v = PyDict_GetItem(dict, t);
1593 if (!v) {
1594 arg = PyDict_Size(dict);
1595 v = PyInt_FromLong(arg);
1596 if (!v) {
1597 Py_DECREF(t);
1598 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001599 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600 if (PyDict_SetItem(dict, t, v) < 0) {
1601 Py_DECREF(t);
1602 Py_DECREF(v);
1603 return -1;
1604 }
1605 Py_DECREF(v);
1606 }
1607 else
1608 arg = PyInt_AsLong(v);
1609 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001610 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611}
1612
1613static int
1614compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1615 PyObject *o)
1616{
1617 int arg = compiler_add_o(c, dict, o);
1618 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001619 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620 return compiler_addop_i(c, opcode, arg);
1621}
1622
1623static int
1624compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001625 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626{
1627 int arg;
1628 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1629 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001630 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631 arg = compiler_add_o(c, dict, mangled);
1632 Py_DECREF(mangled);
1633 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001634 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635 return compiler_addop_i(c, opcode, arg);
1636}
1637
1638/* Add an opcode with an integer argument.
1639 Returns 0 on failure, 1 on success.
1640*/
1641
1642static int
1643compiler_addop_i(struct compiler *c, int opcode, int oparg)
1644{
1645 struct instr *i;
1646 int off;
1647 off = compiler_next_instr(c, c->u->u_curblock);
1648 if (off < 0)
1649 return 0;
1650 i = &c->u->u_curblock->b_instr[off];
1651 i->i_opcode = opcode;
1652 i->i_oparg = oparg;
1653 i->i_hasarg = 1;
1654 compiler_set_lineno(c, off);
1655 return 1;
1656}
1657
1658static int
1659compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1660{
1661 struct instr *i;
1662 int off;
1663
1664 assert(b != NULL);
1665 off = compiler_next_instr(c, c->u->u_curblock);
1666 if (off < 0)
1667 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001668 i = &c->u->u_curblock->b_instr[off];
1669 i->i_opcode = opcode;
1670 i->i_target = b;
1671 i->i_hasarg = 1;
1672 if (absolute)
1673 i->i_jabs = 1;
1674 else
1675 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001676 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001677 return 1;
1678}
1679
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001680/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1681 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 it as the current block. NEXT_BLOCK() also creates an implicit jump
1683 from the current block to the new block.
1684*/
1685
1686/* XXX The returns inside these macros make it impossible to decref
1687 objects created in the local function.
1688*/
1689
1690
1691#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001692 if (compiler_use_new_block((C)) == NULL) \
1693 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694}
1695
1696#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001697 if (compiler_next_block((C)) == NULL) \
1698 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699}
1700
1701#define ADDOP(C, OP) { \
1702 if (!compiler_addop((C), (OP))) \
1703 return 0; \
1704}
1705
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001706#define ADDOP_IN_SCOPE(C, OP) { \
1707 if (!compiler_addop((C), (OP))) { \
1708 compiler_exit_scope(c); \
1709 return 0; \
1710 } \
1711}
1712
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001713#define ADDOP_O(C, OP, O, TYPE) { \
1714 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1715 return 0; \
1716}
1717
1718#define ADDOP_NAME(C, OP, O, TYPE) { \
1719 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1720 return 0; \
1721}
1722
1723#define ADDOP_I(C, OP, O) { \
1724 if (!compiler_addop_i((C), (OP), (O))) \
1725 return 0; \
1726}
1727
1728#define ADDOP_JABS(C, OP, O) { \
1729 if (!compiler_addop_j((C), (OP), (O), 1)) \
1730 return 0; \
1731}
1732
1733#define ADDOP_JREL(C, OP, O) { \
1734 if (!compiler_addop_j((C), (OP), (O), 0)) \
1735 return 0; \
1736}
1737
1738/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1739 the ASDL name to synthesize the name of the C type and the visit function.
1740*/
1741
1742#define VISIT(C, TYPE, V) {\
1743 if (!compiler_visit_ ## TYPE((C), (V))) \
1744 return 0; \
1745}
1746
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001747#define VISIT_IN_SCOPE(C, TYPE, V) {\
1748 if (!compiler_visit_ ## TYPE((C), (V))) { \
1749 compiler_exit_scope(c); \
1750 return 0; \
1751 } \
1752}
1753
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001754#define VISIT_SLICE(C, V, CTX) {\
1755 if (!compiler_visit_slice((C), (V), (CTX))) \
1756 return 0; \
1757}
1758
1759#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001760 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001762 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001763 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001764 if (!compiler_visit_ ## TYPE((C), elt)) \
1765 return 0; \
1766 } \
1767}
1768
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001769#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001770 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001771 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001772 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001773 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001774 if (!compiler_visit_ ## TYPE((C), elt)) { \
1775 compiler_exit_scope(c); \
1776 return 0; \
1777 } \
1778 } \
1779}
1780
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781static int
1782compiler_isdocstring(stmt_ty s)
1783{
1784 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001785 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786 return s->v.Expr.value->kind == Str_kind;
1787}
1788
1789/* Compile a sequence of statements, checking for a docstring. */
1790
1791static int
1792compiler_body(struct compiler *c, asdl_seq *stmts)
1793{
1794 int i = 0;
1795 stmt_ty st;
1796
1797 if (!asdl_seq_LEN(stmts))
1798 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001799 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandlba871a02007-06-01 11:33:45 +00001800 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1801 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802 i = 1;
1803 VISIT(c, expr, st->v.Expr.value);
1804 if (!compiler_nameop(c, __doc__, Store))
1805 return 0;
1806 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001807 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001808 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809 return 1;
1810}
1811
1812static PyCodeObject *
1813compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001814{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001815 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001816 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 static PyObject *module;
1818 if (!module) {
1819 module = PyString_FromString("<module>");
1820 if (!module)
1821 return NULL;
1822 }
Neal Norwitzed657552006-07-10 00:04:44 +00001823 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1824 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001825 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826 switch (mod->kind) {
1827 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001828 if (!compiler_body(c, mod->v.Module.body)) {
1829 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001831 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 break;
1833 case Interactive_kind:
1834 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001835 VISIT_SEQ_IN_SCOPE(c, stmt,
1836 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837 break;
1838 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001839 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001840 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841 break;
1842 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001843 PyErr_SetString(PyExc_SystemError,
1844 "suite should not be possible");
1845 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001846 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001847 PyErr_Format(PyExc_SystemError,
1848 "module kind %d should not be possible",
1849 mod->kind);
1850 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001851 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852 co = assemble(c, addNone);
1853 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001854 return co;
1855}
1856
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857/* The test for LOCAL must come before the test for FREE in order to
1858 handle classes where name is both local and free. The local var is
1859 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001860*/
1861
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862static int
1863get_ref_type(struct compiler *c, PyObject *name)
1864{
1865 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001866 if (scope == 0) {
1867 char buf[350];
1868 PyOS_snprintf(buf, sizeof(buf),
1869 "unknown scope for %.100s in %.100s(%s) in %s\n"
1870 "symbols: %s\nlocals: %s\nglobals: %s\n",
1871 PyString_AS_STRING(name),
1872 PyString_AS_STRING(c->u->u_name),
1873 PyObject_REPR(c->u->u_ste->ste_id),
1874 c->c_filename,
1875 PyObject_REPR(c->u->u_ste->ste_symbols),
1876 PyObject_REPR(c->u->u_varnames),
1877 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001879 Py_FatalError(buf);
1880 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001881
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001882 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883}
1884
1885static int
1886compiler_lookup_arg(PyObject *dict, PyObject *name)
1887{
1888 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001889 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001891 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001893 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001895 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896 return PyInt_AS_LONG(v);
1897}
1898
1899static int
1900compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1901{
1902 int i, free = PyCode_GetNumFree(co);
1903 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001904 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1905 ADDOP_I(c, MAKE_FUNCTION, args);
1906 return 1;
1907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 for (i = 0; i < free; ++i) {
1909 /* Bypass com_addop_varname because it will generate
1910 LOAD_DEREF but LOAD_CLOSURE is needed.
1911 */
1912 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1913 int arg, reftype;
1914
1915 /* Special case: If a class contains a method with a
1916 free variable that has the same name as a method,
1917 the name will be considered free *and* local in the
1918 class. It should be handled by the closure, as
1919 well as by the normal name loookup logic.
1920 */
1921 reftype = get_ref_type(c, name);
1922 if (reftype == CELL)
1923 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1924 else /* (reftype == FREE) */
1925 arg = compiler_lookup_arg(c->u->u_freevars, name);
1926 if (arg == -1) {
1927 printf("lookup %s in %s %d %d\n"
1928 "freevars of %s: %s\n",
1929 PyObject_REPR(name),
1930 PyString_AS_STRING(c->u->u_name),
1931 reftype, arg,
1932 PyString_AS_STRING(co->co_name),
1933 PyObject_REPR(co->co_freevars));
1934 Py_FatalError("compiler_make_closure()");
1935 }
1936 ADDOP_I(c, LOAD_CLOSURE, arg);
1937 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001938 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001940 ADDOP_I(c, MAKE_CLOSURE, args);
1941 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942}
1943
1944static int
1945compiler_decorators(struct compiler *c, asdl_seq* decos)
1946{
1947 int i;
1948
1949 if (!decos)
1950 return 1;
1951
1952 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001953 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954 }
1955 return 1;
1956}
1957
1958static int
1959compiler_arguments(struct compiler *c, arguments_ty args)
1960{
1961 int i;
1962 int n = asdl_seq_LEN(args->args);
1963 /* Correctly handle nested argument lists */
1964 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001965 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 if (arg->kind == Tuple_kind) {
1967 PyObject *id = PyString_FromFormat(".%d", i);
1968 if (id == NULL) {
1969 return 0;
1970 }
1971 if (!compiler_nameop(c, id, Load)) {
1972 Py_DECREF(id);
1973 return 0;
1974 }
1975 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001976 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 }
1978 }
1979 return 1;
1980}
1981
1982static int
1983compiler_function(struct compiler *c, stmt_ty s)
1984{
1985 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001986 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987 arguments_ty args = s->v.FunctionDef.args;
1988 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001989 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 int i, n, docstring;
1991
1992 assert(s->kind == FunctionDef_kind);
1993
1994 if (!compiler_decorators(c, decos))
1995 return 0;
1996 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001997 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1999 s->lineno))
2000 return 0;
2001
Anthony Baxter7b782b62006-04-11 12:01:56 +00002002 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002003 docstring = compiler_isdocstring(st);
Georg Brandldfecfdb2007-09-19 06:37:26 +00002004 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002005 first_const = st->v.Expr.value->v.Str.s;
2006 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002007 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002008 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002011 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 compiler_arguments(c, args);
2013
2014 c->u->u_argcount = asdl_seq_LEN(args->args);
2015 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002016 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002018 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
2019 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 }
2021 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002022 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023 if (co == NULL)
2024 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002026 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002027 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002028
2029 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2030 ADDOP_I(c, CALL_FUNCTION, 1);
2031 }
2032
2033 return compiler_nameop(c, s->v.FunctionDef.name, Store);
2034}
2035
2036static int
2037compiler_class(struct compiler *c, stmt_ty s)
2038{
2039 int n;
2040 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002041 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002042 /* push class name on stack, needed by BUILD_CLASS */
2043 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2044 /* push the tuple of base classes on the stack */
2045 n = asdl_seq_LEN(s->v.ClassDef.bases);
2046 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002047 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002048 ADDOP_I(c, BUILD_TUPLE, n);
2049 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2050 s->lineno))
2051 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002052 c->u->u_private = s->v.ClassDef.name;
2053 Py_INCREF(c->u->u_private);
2054 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002055 if (!str || !compiler_nameop(c, str, Load)) {
2056 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002057 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002058 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002059 }
2060
2061 Py_DECREF(str);
2062 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 if (!str || !compiler_nameop(c, str, Store)) {
2064 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002065 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002066 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002067 }
2068 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002070 if (!compiler_body(c, s->v.ClassDef.body)) {
2071 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002075 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2076 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002078 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 if (co == NULL)
2080 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002082 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002083 Py_DECREF(co);
2084
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 ADDOP_I(c, CALL_FUNCTION, 0);
2086 ADDOP(c, BUILD_CLASS);
2087 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2088 return 0;
2089 return 1;
2090}
2091
2092static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002093compiler_ifexp(struct compiler *c, expr_ty e)
2094{
2095 basicblock *end, *next;
2096
2097 assert(e->kind == IfExp_kind);
2098 end = compiler_new_block(c);
2099 if (end == NULL)
2100 return 0;
2101 next = compiler_new_block(c);
2102 if (next == NULL)
2103 return 0;
2104 VISIT(c, expr, e->v.IfExp.test);
2105 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2106 ADDOP(c, POP_TOP);
2107 VISIT(c, expr, e->v.IfExp.body);
2108 ADDOP_JREL(c, JUMP_FORWARD, end);
2109 compiler_use_next_block(c, next);
2110 ADDOP(c, POP_TOP);
2111 VISIT(c, expr, e->v.IfExp.orelse);
2112 compiler_use_next_block(c, end);
2113 return 1;
2114}
2115
2116static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117compiler_lambda(struct compiler *c, expr_ty e)
2118{
2119 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002120 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002121 arguments_ty args = e->v.Lambda.args;
2122 assert(e->kind == Lambda_kind);
2123
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002124 if (!name) {
2125 name = PyString_InternFromString("<lambda>");
2126 if (!name)
2127 return 0;
2128 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129
2130 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002131 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2133 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002134
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002135 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136 compiler_arguments(c, args);
2137
2138 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002139 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2140 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002142 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143 if (co == NULL)
2144 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002146 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002147 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148
2149 return 1;
2150}
2151
2152static int
2153compiler_print(struct compiler *c, stmt_ty s)
2154{
2155 int i, n;
2156 bool dest;
2157
2158 assert(s->kind == Print_kind);
2159 n = asdl_seq_LEN(s->v.Print.values);
2160 dest = false;
2161 if (s->v.Print.dest) {
2162 VISIT(c, expr, s->v.Print.dest);
2163 dest = true;
2164 }
2165 for (i = 0; i < n; i++) {
2166 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2167 if (dest) {
2168 ADDOP(c, DUP_TOP);
2169 VISIT(c, expr, e);
2170 ADDOP(c, ROT_TWO);
2171 ADDOP(c, PRINT_ITEM_TO);
2172 }
2173 else {
2174 VISIT(c, expr, e);
2175 ADDOP(c, PRINT_ITEM);
2176 }
2177 }
2178 if (s->v.Print.nl) {
2179 if (dest)
2180 ADDOP(c, PRINT_NEWLINE_TO)
2181 else
2182 ADDOP(c, PRINT_NEWLINE)
2183 }
2184 else if (dest)
2185 ADDOP(c, POP_TOP);
2186 return 1;
2187}
2188
2189static int
2190compiler_if(struct compiler *c, stmt_ty s)
2191{
2192 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00002193 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002194 assert(s->kind == If_kind);
2195 end = compiler_new_block(c);
2196 if (end == NULL)
2197 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002198 next = compiler_new_block(c);
2199 if (next == NULL)
2200 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00002201
2202 constant = expr_constant(s->v.If.test);
2203 /* constant = 0: "if 0"
2204 * constant = 1: "if 1", "if 2", ...
2205 * constant = -1: rest */
2206 if (constant == 0) {
2207 if (s->v.If.orelse)
2208 VISIT_SEQ(c, stmt, s->v.If.orelse);
2209 } else if (constant == 1) {
2210 VISIT_SEQ(c, stmt, s->v.If.body);
2211 } else {
2212 VISIT(c, expr, s->v.If.test);
2213 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2214 ADDOP(c, POP_TOP);
2215 VISIT_SEQ(c, stmt, s->v.If.body);
2216 ADDOP_JREL(c, JUMP_FORWARD, end);
2217 compiler_use_next_block(c, next);
2218 ADDOP(c, POP_TOP);
2219 if (s->v.If.orelse)
2220 VISIT_SEQ(c, stmt, s->v.If.orelse);
2221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222 compiler_use_next_block(c, end);
2223 return 1;
2224}
2225
2226static int
2227compiler_for(struct compiler *c, stmt_ty s)
2228{
2229 basicblock *start, *cleanup, *end;
2230
2231 start = compiler_new_block(c);
2232 cleanup = compiler_new_block(c);
2233 end = compiler_new_block(c);
2234 if (start == NULL || end == NULL || cleanup == NULL)
2235 return 0;
2236 ADDOP_JREL(c, SETUP_LOOP, end);
2237 if (!compiler_push_fblock(c, LOOP, start))
2238 return 0;
2239 VISIT(c, expr, s->v.For.iter);
2240 ADDOP(c, GET_ITER);
2241 compiler_use_next_block(c, start);
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002242 /* for expressions must be traced on each iteration,
2243 so we need to set an extra line number. */
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002244 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002245 ADDOP_JREL(c, FOR_ITER, cleanup);
2246 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002247 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2249 compiler_use_next_block(c, cleanup);
2250 ADDOP(c, POP_BLOCK);
2251 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002252 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253 compiler_use_next_block(c, end);
2254 return 1;
2255}
2256
2257static int
2258compiler_while(struct compiler *c, stmt_ty s)
2259{
2260 basicblock *loop, *orelse, *end, *anchor = NULL;
2261 int constant = expr_constant(s->v.While.test);
2262
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002263 if (constant == 0) {
2264 if (s->v.While.orelse)
2265 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 return 1;
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002268 loop = compiler_new_block(c);
2269 end = compiler_new_block(c);
2270 if (constant == -1) {
2271 anchor = compiler_new_block(c);
2272 if (anchor == NULL)
2273 return 0;
2274 }
2275 if (loop == NULL || end == NULL)
2276 return 0;
2277 if (s->v.While.orelse) {
2278 orelse = compiler_new_block(c);
2279 if (orelse == NULL)
2280 return 0;
2281 }
2282 else
2283 orelse = NULL;
2284
2285 ADDOP_JREL(c, SETUP_LOOP, end);
2286 compiler_use_next_block(c, loop);
2287 if (!compiler_push_fblock(c, LOOP, loop))
2288 return 0;
2289 if (constant == -1) {
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002290 /* while expressions must be traced on each iteration,
2291 so we need to set an extra line number. */
2292 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293 VISIT(c, expr, s->v.While.test);
2294 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2295 ADDOP(c, POP_TOP);
2296 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002297 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002298 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2299
2300 /* XXX should the two POP instructions be in a separate block
2301 if there is no else clause ?
2302 */
2303
2304 if (constant == -1) {
2305 compiler_use_next_block(c, anchor);
2306 ADDOP(c, POP_TOP);
2307 ADDOP(c, POP_BLOCK);
2308 }
2309 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002310 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002311 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002312 compiler_use_next_block(c, end);
2313
2314 return 1;
2315}
2316
2317static int
2318compiler_continue(struct compiler *c)
2319{
2320 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Georg Brandl74284b92006-10-08 07:06:29 +00002321 static const char IN_FINALLY_ERROR_MSG[] =
2322 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323 int i;
2324
2325 if (!c->u->u_nfblocks)
2326 return compiler_error(c, LOOP_ERROR_MSG);
2327 i = c->u->u_nfblocks - 1;
2328 switch (c->u->u_fblock[i].fb_type) {
2329 case LOOP:
2330 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2331 break;
2332 case EXCEPT:
2333 case FINALLY_TRY:
Georg Brandl74284b92006-10-08 07:06:29 +00002334 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2335 /* Prevent try: ... finally:
2336 try: continue ... or
2337 try: ... except: continue */
2338 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2339 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2340 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002341 if (i == -1)
2342 return compiler_error(c, LOOP_ERROR_MSG);
2343 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2344 break;
2345 case FINALLY_END:
Georg Brandl74284b92006-10-08 07:06:29 +00002346 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347 }
2348
2349 return 1;
2350}
2351
2352/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2353
2354 SETUP_FINALLY L
2355 <code for body>
2356 POP_BLOCK
2357 LOAD_CONST <None>
2358 L: <code for finalbody>
2359 END_FINALLY
2360
2361 The special instructions use the block stack. Each block
2362 stack entry contains the instruction that created it (here
2363 SETUP_FINALLY), the level of the value stack at the time the
2364 block stack entry was created, and a label (here L).
2365
2366 SETUP_FINALLY:
2367 Pushes the current value stack level and the label
2368 onto the block stack.
2369 POP_BLOCK:
2370 Pops en entry from the block stack, and pops the value
2371 stack until its level is the same as indicated on the
2372 block stack. (The label is ignored.)
2373 END_FINALLY:
2374 Pops a variable number of entries from the *value* stack
2375 and re-raises the exception they specify. The number of
2376 entries popped depends on the (pseudo) exception type.
2377
2378 The block stack is unwound when an exception is raised:
2379 when a SETUP_FINALLY entry is found, the exception is pushed
2380 onto the value stack (and the exception condition is cleared),
2381 and the interpreter jumps to the label gotten from the block
2382 stack.
2383*/
2384
2385static int
2386compiler_try_finally(struct compiler *c, stmt_ty s)
2387{
2388 basicblock *body, *end;
2389 body = compiler_new_block(c);
2390 end = compiler_new_block(c);
2391 if (body == NULL || end == NULL)
2392 return 0;
2393
2394 ADDOP_JREL(c, SETUP_FINALLY, end);
2395 compiler_use_next_block(c, body);
2396 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2397 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002398 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002399 ADDOP(c, POP_BLOCK);
2400 compiler_pop_fblock(c, FINALLY_TRY, body);
2401
2402 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2403 compiler_use_next_block(c, end);
2404 if (!compiler_push_fblock(c, FINALLY_END, end))
2405 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002406 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407 ADDOP(c, END_FINALLY);
2408 compiler_pop_fblock(c, FINALLY_END, end);
2409
2410 return 1;
2411}
2412
2413/*
2414 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2415 (The contents of the value stack is shown in [], with the top
2416 at the right; 'tb' is trace-back info, 'val' the exception's
2417 associated value, and 'exc' the exception.)
2418
2419 Value stack Label Instruction Argument
2420 [] SETUP_EXCEPT L1
2421 [] <code for S>
2422 [] POP_BLOCK
2423 [] JUMP_FORWARD L0
2424
2425 [tb, val, exc] L1: DUP )
2426 [tb, val, exc, exc] <evaluate E1> )
2427 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2428 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2429 [tb, val, exc, 1] POP )
2430 [tb, val, exc] POP
2431 [tb, val] <assign to V1> (or POP if no V1)
2432 [tb] POP
2433 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002434 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002435
2436 [tb, val, exc, 0] L2: POP
2437 [tb, val, exc] DUP
2438 .............................etc.......................
2439
2440 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002441 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442
2443 [] L0: <next statement>
2444
2445 Of course, parts are not generated if Vi or Ei is not present.
2446*/
2447static int
2448compiler_try_except(struct compiler *c, stmt_ty s)
2449{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002450 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002451 int i, n;
2452
2453 body = compiler_new_block(c);
2454 except = compiler_new_block(c);
2455 orelse = compiler_new_block(c);
2456 end = compiler_new_block(c);
2457 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2458 return 0;
2459 ADDOP_JREL(c, SETUP_EXCEPT, except);
2460 compiler_use_next_block(c, body);
2461 if (!compiler_push_fblock(c, EXCEPT, body))
2462 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002463 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 ADDOP(c, POP_BLOCK);
2465 compiler_pop_fblock(c, EXCEPT, body);
2466 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2467 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2468 compiler_use_next_block(c, except);
2469 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002470 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471 s->v.TryExcept.handlers, i);
2472 if (!handler->type && i < n-1)
2473 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002474 c->u->u_lineno_set = false;
2475 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 except = compiler_new_block(c);
2477 if (except == NULL)
2478 return 0;
2479 if (handler->type) {
2480 ADDOP(c, DUP_TOP);
2481 VISIT(c, expr, handler->type);
2482 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2483 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2484 ADDOP(c, POP_TOP);
2485 }
2486 ADDOP(c, POP_TOP);
2487 if (handler->name) {
2488 VISIT(c, expr, handler->name);
2489 }
2490 else {
2491 ADDOP(c, POP_TOP);
2492 }
2493 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002494 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002495 ADDOP_JREL(c, JUMP_FORWARD, end);
2496 compiler_use_next_block(c, except);
2497 if (handler->type)
2498 ADDOP(c, POP_TOP);
2499 }
2500 ADDOP(c, END_FINALLY);
2501 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002502 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002503 compiler_use_next_block(c, end);
2504 return 1;
2505}
2506
2507static int
2508compiler_import_as(struct compiler *c, identifier name, identifier asname)
2509{
2510 /* The IMPORT_NAME opcode was already generated. This function
2511 merely needs to bind the result to a name.
2512
2513 If there is a dot in name, we need to split it and emit a
2514 LOAD_ATTR for each name.
2515 */
2516 const char *src = PyString_AS_STRING(name);
2517 const char *dot = strchr(src, '.');
2518 if (dot) {
2519 /* Consume the base module name to get the first attribute */
2520 src = dot + 1;
2521 while (dot) {
2522 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002523 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002525 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002526 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002527 if (!attr)
2528 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002529 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002530 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 src = dot + 1;
2532 }
2533 }
2534 return compiler_nameop(c, asname, Store);
2535}
2536
2537static int
2538compiler_import(struct compiler *c, stmt_ty s)
2539{
2540 /* The Import node stores a module name like a.b.c as a single
2541 string. This is convenient for all cases except
2542 import a.b.c as d
2543 where we need to parse that string to extract the individual
2544 module names.
2545 XXX Perhaps change the representation to make this case simpler?
2546 */
2547 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002548
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002550 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002551 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002552 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553
Neal Norwitzcbce2802006-04-03 06:26:32 +00002554 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002555 level = PyInt_FromLong(0);
2556 else
2557 level = PyInt_FromLong(-1);
2558
2559 if (level == NULL)
2560 return 0;
2561
2562 ADDOP_O(c, LOAD_CONST, level, consts);
2563 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2565 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2566
2567 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002568 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002569 if (!r)
2570 return r;
2571 }
2572 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 identifier tmp = alias->name;
2574 const char *base = PyString_AS_STRING(alias->name);
2575 char *dot = strchr(base, '.');
2576 if (dot)
2577 tmp = PyString_FromStringAndSize(base,
2578 dot - base);
2579 r = compiler_nameop(c, tmp, Store);
2580 if (dot) {
2581 Py_DECREF(tmp);
2582 }
2583 if (!r)
2584 return r;
2585 }
2586 }
2587 return 1;
2588}
2589
2590static int
2591compiler_from_import(struct compiler *c, stmt_ty s)
2592{
2593 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002594
2595 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002596 PyObject *level;
2597
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 if (!names)
2599 return 0;
2600
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002601 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002602 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002603 level = PyInt_FromLong(-1);
2604 else
2605 level = PyInt_FromLong(s->v.ImportFrom.level);
2606
2607 if (!level) {
2608 Py_DECREF(names);
2609 return 0;
2610 }
2611
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 /* build up the names */
2613 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002614 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 Py_INCREF(alias->name);
2616 PyTuple_SET_ITEM(names, i, alias->name);
2617 }
2618
2619 if (s->lineno > c->c_future->ff_lineno) {
2620 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2621 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002622 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002623 Py_DECREF(names);
2624 return compiler_error(c,
2625 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002626 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627
2628 }
2629 }
2630
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002631 ADDOP_O(c, LOAD_CONST, level, consts);
2632 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002634 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2636 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002637 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 identifier store_name;
2639
2640 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2641 assert(n == 1);
2642 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002643 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644 }
2645
2646 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2647 store_name = alias->name;
2648 if (alias->asname)
2649 store_name = alias->asname;
2650
2651 if (!compiler_nameop(c, store_name, Store)) {
2652 Py_DECREF(names);
2653 return 0;
2654 }
2655 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002656 /* remove imported module */
2657 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 return 1;
2659}
2660
2661static int
2662compiler_assert(struct compiler *c, stmt_ty s)
2663{
2664 static PyObject *assertion_error = NULL;
2665 basicblock *end;
2666
2667 if (Py_OptimizeFlag)
2668 return 1;
2669 if (assertion_error == NULL) {
2670 assertion_error = PyString_FromString("AssertionError");
2671 if (assertion_error == NULL)
2672 return 0;
2673 }
2674 VISIT(c, expr, s->v.Assert.test);
2675 end = compiler_new_block(c);
2676 if (end == NULL)
2677 return 0;
2678 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2679 ADDOP(c, POP_TOP);
2680 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2681 if (s->v.Assert.msg) {
2682 VISIT(c, expr, s->v.Assert.msg);
2683 ADDOP_I(c, RAISE_VARARGS, 2);
2684 }
2685 else {
2686 ADDOP_I(c, RAISE_VARARGS, 1);
2687 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002688 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689 ADDOP(c, POP_TOP);
2690 return 1;
2691}
2692
2693static int
2694compiler_visit_stmt(struct compiler *c, stmt_ty s)
2695{
2696 int i, n;
2697
Jeremy Hylton12603c42006-04-01 16:18:02 +00002698 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 c->u->u_lineno = s->lineno;
2700 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002701
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002705 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002707 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 if (c->u->u_ste->ste_type != FunctionBlock)
2709 return compiler_error(c, "'return' outside function");
2710 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 VISIT(c, expr, s->v.Return.value);
2712 }
2713 else
2714 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2715 ADDOP(c, RETURN_VALUE);
2716 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002717 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002718 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002720 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 n = asdl_seq_LEN(s->v.Assign.targets);
2722 VISIT(c, expr, s->v.Assign.value);
2723 for (i = 0; i < n; i++) {
2724 if (i < n - 1)
2725 ADDOP(c, DUP_TOP);
2726 VISIT(c, expr,
2727 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2728 }
2729 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002731 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002732 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002734 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002736 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002737 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002738 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002739 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002740 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002741 n = 0;
2742 if (s->v.Raise.type) {
2743 VISIT(c, expr, s->v.Raise.type);
2744 n++;
2745 if (s->v.Raise.inst) {
2746 VISIT(c, expr, s->v.Raise.inst);
2747 n++;
2748 if (s->v.Raise.tback) {
2749 VISIT(c, expr, s->v.Raise.tback);
2750 n++;
2751 }
2752 }
2753 }
2754 ADDOP_I(c, RAISE_VARARGS, n);
2755 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002756 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002758 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002759 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002760 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002761 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002762 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002763 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002764 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002765 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002766 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002767 VISIT(c, expr, s->v.Exec.body);
2768 if (s->v.Exec.globals) {
2769 VISIT(c, expr, s->v.Exec.globals);
2770 if (s->v.Exec.locals) {
2771 VISIT(c, expr, s->v.Exec.locals);
2772 } else {
2773 ADDOP(c, DUP_TOP);
2774 }
2775 } else {
2776 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2777 ADDOP(c, DUP_TOP);
2778 }
2779 ADDOP(c, EXEC_STMT);
2780 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002781 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002783 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002785 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786 ADDOP(c, PRINT_EXPR);
2787 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002788 else if (s->v.Expr.value->kind != Str_kind &&
2789 s->v.Expr.value->kind != Num_kind) {
2790 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002791 ADDOP(c, POP_TOP);
2792 }
2793 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002794 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002796 case Break_kind:
Georg Brandla5fe3ef2006-10-08 07:12:23 +00002797 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798 return compiler_error(c, "'break' outside loop");
2799 ADDOP(c, BREAK_LOOP);
2800 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002801 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002802 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002803 case With_kind:
2804 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002805 }
2806 return 1;
2807}
2808
2809static int
2810unaryop(unaryop_ty op)
2811{
2812 switch (op) {
2813 case Invert:
2814 return UNARY_INVERT;
2815 case Not:
2816 return UNARY_NOT;
2817 case UAdd:
2818 return UNARY_POSITIVE;
2819 case USub:
2820 return UNARY_NEGATIVE;
2821 }
2822 return 0;
2823}
2824
2825static int
2826binop(struct compiler *c, operator_ty op)
2827{
2828 switch (op) {
2829 case Add:
2830 return BINARY_ADD;
2831 case Sub:
2832 return BINARY_SUBTRACT;
2833 case Mult:
2834 return BINARY_MULTIPLY;
2835 case Div:
2836 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2837 return BINARY_TRUE_DIVIDE;
2838 else
2839 return BINARY_DIVIDE;
2840 case Mod:
2841 return BINARY_MODULO;
2842 case Pow:
2843 return BINARY_POWER;
2844 case LShift:
2845 return BINARY_LSHIFT;
2846 case RShift:
2847 return BINARY_RSHIFT;
2848 case BitOr:
2849 return BINARY_OR;
2850 case BitXor:
2851 return BINARY_XOR;
2852 case BitAnd:
2853 return BINARY_AND;
2854 case FloorDiv:
2855 return BINARY_FLOOR_DIVIDE;
2856 }
2857 return 0;
2858}
2859
2860static int
2861cmpop(cmpop_ty op)
2862{
2863 switch (op) {
2864 case Eq:
2865 return PyCmp_EQ;
2866 case NotEq:
2867 return PyCmp_NE;
2868 case Lt:
2869 return PyCmp_LT;
2870 case LtE:
2871 return PyCmp_LE;
2872 case Gt:
2873 return PyCmp_GT;
2874 case GtE:
2875 return PyCmp_GE;
2876 case Is:
2877 return PyCmp_IS;
2878 case IsNot:
2879 return PyCmp_IS_NOT;
2880 case In:
2881 return PyCmp_IN;
2882 case NotIn:
2883 return PyCmp_NOT_IN;
2884 }
2885 return PyCmp_BAD;
2886}
2887
2888static int
2889inplace_binop(struct compiler *c, operator_ty op)
2890{
2891 switch (op) {
2892 case Add:
2893 return INPLACE_ADD;
2894 case Sub:
2895 return INPLACE_SUBTRACT;
2896 case Mult:
2897 return INPLACE_MULTIPLY;
2898 case Div:
2899 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2900 return INPLACE_TRUE_DIVIDE;
2901 else
2902 return INPLACE_DIVIDE;
2903 case Mod:
2904 return INPLACE_MODULO;
2905 case Pow:
2906 return INPLACE_POWER;
2907 case LShift:
2908 return INPLACE_LSHIFT;
2909 case RShift:
2910 return INPLACE_RSHIFT;
2911 case BitOr:
2912 return INPLACE_OR;
2913 case BitXor:
2914 return INPLACE_XOR;
2915 case BitAnd:
2916 return INPLACE_AND;
2917 case FloorDiv:
2918 return INPLACE_FLOOR_DIVIDE;
2919 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002920 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002921 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 return 0;
2923}
2924
2925static int
2926compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2927{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002928 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002929 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2930
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002931 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002932 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933 /* XXX AugStore isn't used anywhere! */
2934
2935 /* First check for assignment to __debug__. Param? */
2936 if ((ctx == Store || ctx == AugStore || ctx == Del)
2937 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2938 return compiler_error(c, "can not assign to __debug__");
2939 }
2940
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002941 mangled = _Py_Mangle(c->u->u_private, name);
2942 if (!mangled)
2943 return 0;
2944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 op = 0;
2946 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002947 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 switch (scope) {
2949 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002950 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951 optype = OP_DEREF;
2952 break;
2953 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002954 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955 optype = OP_DEREF;
2956 break;
2957 case LOCAL:
2958 if (c->u->u_ste->ste_type == FunctionBlock)
2959 optype = OP_FAST;
2960 break;
2961 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002962 if (c->u->u_ste->ste_type == FunctionBlock &&
2963 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 optype = OP_GLOBAL;
2965 break;
2966 case GLOBAL_EXPLICIT:
2967 optype = OP_GLOBAL;
2968 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002969 default:
2970 /* scope can be 0 */
2971 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972 }
2973
2974 /* XXX Leave assert here, but handle __doc__ and the like better */
2975 assert(scope || PyString_AS_STRING(name)[0] == '_');
2976
2977 switch (optype) {
2978 case OP_DEREF:
2979 switch (ctx) {
2980 case Load: op = LOAD_DEREF; break;
2981 case Store: op = STORE_DEREF; break;
2982 case AugLoad:
2983 case AugStore:
2984 break;
2985 case Del:
2986 PyErr_Format(PyExc_SyntaxError,
2987 "can not delete variable '%s' referenced "
2988 "in nested scope",
2989 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002990 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002992 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002993 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002994 PyErr_SetString(PyExc_SystemError,
2995 "param invalid for deref variable");
2996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 }
2998 break;
2999 case OP_FAST:
3000 switch (ctx) {
3001 case Load: op = LOAD_FAST; break;
3002 case Store: op = STORE_FAST; break;
3003 case Del: op = DELETE_FAST; break;
3004 case AugLoad:
3005 case AugStore:
3006 break;
3007 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003008 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003009 PyErr_SetString(PyExc_SystemError,
3010 "param invalid for local variable");
3011 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003012 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003013 ADDOP_O(c, op, mangled, varnames);
3014 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 return 1;
3016 case OP_GLOBAL:
3017 switch (ctx) {
3018 case Load: op = LOAD_GLOBAL; break;
3019 case Store: op = STORE_GLOBAL; break;
3020 case Del: op = DELETE_GLOBAL; break;
3021 case AugLoad:
3022 case AugStore:
3023 break;
3024 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003025 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003026 PyErr_SetString(PyExc_SystemError,
3027 "param invalid for global variable");
3028 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 }
3030 break;
3031 case OP_NAME:
3032 switch (ctx) {
3033 case Load: op = LOAD_NAME; break;
3034 case Store: op = STORE_NAME; break;
3035 case Del: op = DELETE_NAME; break;
3036 case AugLoad:
3037 case AugStore:
3038 break;
3039 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003040 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003041 PyErr_SetString(PyExc_SystemError,
3042 "param invalid for name variable");
3043 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 }
3045 break;
3046 }
3047
3048 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003049 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00003050 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003051 if (arg < 0)
3052 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00003053 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003054}
3055
3056static int
3057compiler_boolop(struct compiler *c, expr_ty e)
3058{
3059 basicblock *end;
3060 int jumpi, i, n;
3061 asdl_seq *s;
3062
3063 assert(e->kind == BoolOp_kind);
3064 if (e->v.BoolOp.op == And)
3065 jumpi = JUMP_IF_FALSE;
3066 else
3067 jumpi = JUMP_IF_TRUE;
3068 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003069 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003070 return 0;
3071 s = e->v.BoolOp.values;
3072 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00003073 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003074 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003075 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003076 ADDOP_JREL(c, jumpi, end);
3077 ADDOP(c, POP_TOP)
3078 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003079 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080 compiler_use_next_block(c, end);
3081 return 1;
3082}
3083
3084static int
3085compiler_list(struct compiler *c, expr_ty e)
3086{
3087 int n = asdl_seq_LEN(e->v.List.elts);
3088 if (e->v.List.ctx == Store) {
3089 ADDOP_I(c, UNPACK_SEQUENCE, n);
3090 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003091 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092 if (e->v.List.ctx == Load) {
3093 ADDOP_I(c, BUILD_LIST, n);
3094 }
3095 return 1;
3096}
3097
3098static int
3099compiler_tuple(struct compiler *c, expr_ty e)
3100{
3101 int n = asdl_seq_LEN(e->v.Tuple.elts);
3102 if (e->v.Tuple.ctx == Store) {
3103 ADDOP_I(c, UNPACK_SEQUENCE, n);
3104 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003105 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106 if (e->v.Tuple.ctx == Load) {
3107 ADDOP_I(c, BUILD_TUPLE, n);
3108 }
3109 return 1;
3110}
3111
3112static int
3113compiler_compare(struct compiler *c, expr_ty e)
3114{
3115 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117
3118 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3119 VISIT(c, expr, e->v.Compare.left);
3120 n = asdl_seq_LEN(e->v.Compare.ops);
3121 assert(n > 0);
3122 if (n > 1) {
3123 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003124 if (cleanup == NULL)
3125 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003126 VISIT(c, expr,
3127 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128 }
3129 for (i = 1; i < n; i++) {
3130 ADDOP(c, DUP_TOP);
3131 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003133 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003134 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003135 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3136 NEXT_BLOCK(c);
3137 ADDOP(c, POP_TOP);
3138 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003139 VISIT(c, expr,
3140 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003142 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003144 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 if (n > 1) {
3146 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 if (end == NULL)
3148 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149 ADDOP_JREL(c, JUMP_FORWARD, end);
3150 compiler_use_next_block(c, cleanup);
3151 ADDOP(c, ROT_TWO);
3152 ADDOP(c, POP_TOP);
3153 compiler_use_next_block(c, end);
3154 }
3155 return 1;
3156}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003157#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158
3159static int
3160compiler_call(struct compiler *c, expr_ty e)
3161{
3162 int n, code = 0;
3163
3164 VISIT(c, expr, e->v.Call.func);
3165 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003166 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003168 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3170 }
3171 if (e->v.Call.starargs) {
3172 VISIT(c, expr, e->v.Call.starargs);
3173 code |= 1;
3174 }
3175 if (e->v.Call.kwargs) {
3176 VISIT(c, expr, e->v.Call.kwargs);
3177 code |= 2;
3178 }
3179 switch (code) {
3180 case 0:
3181 ADDOP_I(c, CALL_FUNCTION, n);
3182 break;
3183 case 1:
3184 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3185 break;
3186 case 2:
3187 ADDOP_I(c, CALL_FUNCTION_KW, n);
3188 break;
3189 case 3:
3190 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3191 break;
3192 }
3193 return 1;
3194}
3195
3196static int
3197compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 asdl_seq *generators, int gen_index,
3199 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200{
3201 /* generate code for the iterator, then each of the ifs,
3202 and then write to the element */
3203
3204 comprehension_ty l;
3205 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003206 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207
3208 start = compiler_new_block(c);
3209 skip = compiler_new_block(c);
3210 if_cleanup = compiler_new_block(c);
3211 anchor = compiler_new_block(c);
3212
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3214 anchor == NULL)
3215 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216
Anthony Baxter7b782b62006-04-11 12:01:56 +00003217 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 VISIT(c, expr, l->iter);
3219 ADDOP(c, GET_ITER);
3220 compiler_use_next_block(c, start);
3221 ADDOP_JREL(c, FOR_ITER, anchor);
3222 NEXT_BLOCK(c);
3223 VISIT(c, expr, l->target);
3224
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003225 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003226 n = asdl_seq_LEN(l->ifs);
3227 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003228 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229 VISIT(c, expr, e);
3230 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3231 NEXT_BLOCK(c);
3232 ADDOP(c, POP_TOP);
3233 }
3234
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 if (++gen_index < asdl_seq_LEN(generators))
3236 if (!compiler_listcomp_generator(c, tmpname,
3237 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003240 /* only append after the last for generator */
3241 if (gen_index >= asdl_seq_LEN(generators)) {
3242 if (!compiler_nameop(c, tmpname, Load))
3243 return 0;
3244 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003245 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003246
3247 compiler_use_next_block(c, skip);
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249 for (i = 0; i < n; i++) {
3250 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 if (i == 0)
3252 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 ADDOP(c, POP_TOP);
3254 }
3255 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3256 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003257 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260 return 0;
3261
3262 return 1;
3263}
3264
3265static int
3266compiler_listcomp(struct compiler *c, expr_ty e)
3267{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 static identifier append;
3271 asdl_seq *generators = e->v.ListComp.generators;
3272
3273 assert(e->kind == ListComp_kind);
3274 if (!append) {
3275 append = PyString_InternFromString("append");
3276 if (!append)
3277 return 0;
3278 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003279 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 if (!tmp)
3281 return 0;
3282 ADDOP_I(c, BUILD_LIST, 0);
3283 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003285 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3286 e->v.ListComp.elt);
3287 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288 return rc;
3289}
3290
3291static int
3292compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003293 asdl_seq *generators, int gen_index,
3294 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295{
3296 /* generate code for the iterator, then each of the ifs,
3297 and then write to the element */
3298
3299 comprehension_ty ge;
3300 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003301 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302
3303 start = compiler_new_block(c);
3304 skip = compiler_new_block(c);
3305 if_cleanup = compiler_new_block(c);
3306 anchor = compiler_new_block(c);
3307 end = compiler_new_block(c);
3308
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003309 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 anchor == NULL || end == NULL)
3311 return 0;
3312
Anthony Baxter7b782b62006-04-11 12:01:56 +00003313 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314 ADDOP_JREL(c, SETUP_LOOP, end);
3315 if (!compiler_push_fblock(c, LOOP, start))
3316 return 0;
3317
3318 if (gen_index == 0) {
3319 /* Receive outermost iter as an implicit argument */
3320 c->u->u_argcount = 1;
3321 ADDOP_I(c, LOAD_FAST, 0);
3322 }
3323 else {
3324 /* Sub-iter - calculate on the fly */
3325 VISIT(c, expr, ge->iter);
3326 ADDOP(c, GET_ITER);
3327 }
3328 compiler_use_next_block(c, start);
3329 ADDOP_JREL(c, FOR_ITER, anchor);
3330 NEXT_BLOCK(c);
3331 VISIT(c, expr, ge->target);
3332
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003333 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334 n = asdl_seq_LEN(ge->ifs);
3335 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003336 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003337 VISIT(c, expr, e);
3338 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3339 NEXT_BLOCK(c);
3340 ADDOP(c, POP_TOP);
3341 }
3342
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003343 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3345 return 0;
3346
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003347 /* only append after the last 'for' generator */
3348 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003349 VISIT(c, expr, elt);
3350 ADDOP(c, YIELD_VALUE);
3351 ADDOP(c, POP_TOP);
3352
3353 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355 for (i = 0; i < n; i++) {
3356 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003357 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358 compiler_use_next_block(c, if_cleanup);
3359
3360 ADDOP(c, POP_TOP);
3361 }
3362 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3363 compiler_use_next_block(c, anchor);
3364 ADDOP(c, POP_BLOCK);
3365 compiler_pop_fblock(c, LOOP, start);
3366 compiler_use_next_block(c, end);
3367
3368 return 1;
3369}
3370
3371static int
3372compiler_genexp(struct compiler *c, expr_ty e)
3373{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003374 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375 PyCodeObject *co;
3376 expr_ty outermost_iter = ((comprehension_ty)
3377 (asdl_seq_GET(e->v.GeneratorExp.generators,
3378 0)))->iter;
3379
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003380 if (!name) {
3381 name = PyString_FromString("<genexpr>");
3382 if (!name)
3383 return 0;
3384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385
3386 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3387 return 0;
3388 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3389 e->v.GeneratorExp.elt);
3390 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003391 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003392 if (co == NULL)
3393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003396 Py_DECREF(co);
3397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398 VISIT(c, expr, outermost_iter);
3399 ADDOP(c, GET_ITER);
3400 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401
3402 return 1;
3403}
3404
3405static int
3406compiler_visit_keyword(struct compiler *c, keyword_ty k)
3407{
3408 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3409 VISIT(c, expr, k->value);
3410 return 1;
3411}
3412
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003413/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414 whether they are true or false.
3415
3416 Return values: 1 for true, 0 for false, -1 for non-constant.
3417 */
3418
3419static int
3420expr_constant(expr_ty e)
3421{
3422 switch (e->kind) {
3423 case Num_kind:
3424 return PyObject_IsTrue(e->v.Num.n);
3425 case Str_kind:
3426 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003427 case Name_kind:
3428 /* __debug__ is not assignable, so we can optimize
3429 * it away in if and while statements */
3430 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3431 "__debug__") == 0)
3432 return ! Py_OptimizeFlag;
3433 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003434 default:
3435 return -1;
3436 }
3437}
3438
Guido van Rossumc2e20742006-02-27 22:32:47 +00003439/*
3440 Implements the with statement from PEP 343.
3441
3442 The semantics outlined in that PEP are as follows:
3443
3444 with EXPR as VAR:
3445 BLOCK
3446
3447 It is implemented roughly as:
3448
Guido van Rossumda5b7012006-05-02 19:47:52 +00003449 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003450 exit = context.__exit__ # not calling it
3451 value = context.__enter__()
3452 try:
3453 VAR = value # if VAR present in the syntax
3454 BLOCK
3455 finally:
3456 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003458 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003459 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003460 exit(*exc)
3461 */
3462static int
3463compiler_with(struct compiler *c, stmt_ty s)
3464{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003465 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003466 basicblock *block, *finally;
3467 identifier tmpexit, tmpvalue = NULL;
3468
3469 assert(s->kind == With_kind);
3470
Guido van Rossumc2e20742006-02-27 22:32:47 +00003471 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003472 enter_attr = PyString_InternFromString("__enter__");
3473 if (!enter_attr)
3474 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003475 }
3476 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003477 exit_attr = PyString_InternFromString("__exit__");
3478 if (!exit_attr)
3479 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003480 }
3481
3482 block = compiler_new_block(c);
3483 finally = compiler_new_block(c);
3484 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003485 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003486
3487 /* Create a temporary variable to hold context.__exit__ */
3488 tmpexit = compiler_new_tmpname(c);
3489 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003490 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003491 PyArena_AddPyObject(c->c_arena, tmpexit);
3492
3493 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003494 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003495 We need to do this rather than preserving it on the stack
3496 because SETUP_FINALLY remembers the stack level.
3497 We need to do the assignment *inside* the try/finally
3498 so that context.__exit__() is called when the assignment
3499 fails. But we need to call context.__enter__() *before*
3500 the try/finally so that if it fails we won't call
3501 context.__exit__().
3502 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003503 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003504 if (tmpvalue == NULL)
3505 return 0;
3506 PyArena_AddPyObject(c->c_arena, tmpvalue);
3507 }
3508
Guido van Rossumda5b7012006-05-02 19:47:52 +00003509 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003510 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003511
3512 /* Squirrel away context.__exit__ */
3513 ADDOP(c, DUP_TOP);
3514 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3515 if (!compiler_nameop(c, tmpexit, Store))
3516 return 0;
3517
3518 /* Call context.__enter__() */
3519 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3520 ADDOP_I(c, CALL_FUNCTION, 0);
3521
3522 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 /* Store it in tmpvalue */
3524 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003525 return 0;
3526 }
3527 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003528 /* Discard result from context.__enter__() */
3529 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003530 }
3531
3532 /* Start the try block */
3533 ADDOP_JREL(c, SETUP_FINALLY, finally);
3534
3535 compiler_use_next_block(c, block);
3536 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003537 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003538 }
3539
3540 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003541 /* Bind saved result of context.__enter__() to VAR */
3542 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003543 !compiler_nameop(c, tmpvalue, Del))
3544 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003545 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003546 }
3547
3548 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003549 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003550
3551 /* End of try block; start the finally block */
3552 ADDOP(c, POP_BLOCK);
3553 compiler_pop_fblock(c, FINALLY_TRY, block);
3554
3555 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3556 compiler_use_next_block(c, finally);
3557 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003558 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003559
3560 /* Finally block starts; push tmpexit and issue our magic opcode. */
3561 if (!compiler_nameop(c, tmpexit, Load) ||
3562 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003564 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003565
3566 /* Finally block ends. */
3567 ADDOP(c, END_FINALLY);
3568 compiler_pop_fblock(c, FINALLY_END, finally);
3569 return 1;
3570}
3571
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003572static int
3573compiler_visit_expr(struct compiler *c, expr_ty e)
3574{
3575 int i, n;
3576
Jeremy Hylton12603c42006-04-01 16:18:02 +00003577 /* If expr e has a different line number than the last expr/stmt,
3578 set a new line number for the next instruction.
3579 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580 if (e->lineno > c->u->u_lineno) {
3581 c->u->u_lineno = e->lineno;
3582 c->u->u_lineno_set = false;
3583 }
3584 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003585 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003587 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 VISIT(c, expr, e->v.BinOp.left);
3589 VISIT(c, expr, e->v.BinOp.right);
3590 ADDOP(c, binop(c, e->v.BinOp.op));
3591 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003592 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 VISIT(c, expr, e->v.UnaryOp.operand);
3594 ADDOP(c, unaryop(e->v.UnaryOp.op));
3595 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003596 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003598 case IfExp_kind:
3599 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003600 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 /* XXX get rid of arg? */
3602 ADDOP_I(c, BUILD_MAP, 0);
3603 n = asdl_seq_LEN(e->v.Dict.values);
3604 /* We must arrange things just right for STORE_SUBSCR.
3605 It wants the stack to look like (value) (dict) (key) */
3606 for (i = 0; i < n; i++) {
3607 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003608 VISIT(c, expr,
3609 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003611 VISIT(c, expr,
3612 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 ADDOP(c, STORE_SUBSCR);
3614 }
3615 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003616 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003618 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 return compiler_genexp(c, e);
3620 case Yield_kind:
3621 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003622 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 /*
3624 for (i = 0; i < c->u->u_nfblocks; i++) {
3625 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3626 return compiler_error(
3627 c, "'yield' not allowed in a 'try' "
3628 "block with a 'finally' clause");
3629 }
3630 */
3631 if (e->v.Yield.value) {
3632 VISIT(c, expr, e->v.Yield.value);
3633 }
3634 else {
3635 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3636 }
3637 ADDOP(c, YIELD_VALUE);
3638 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003639 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003641 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003643 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 VISIT(c, expr, e->v.Repr.value);
3645 ADDOP(c, UNARY_CONVERT);
3646 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003647 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3649 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003650 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3652 break;
3653 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 if (e->v.Attribute.ctx != AugStore)
3656 VISIT(c, expr, e->v.Attribute.value);
3657 switch (e->v.Attribute.ctx) {
3658 case AugLoad:
3659 ADDOP(c, DUP_TOP);
3660 /* Fall through to load */
3661 case Load:
3662 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3663 break;
3664 case AugStore:
3665 ADDOP(c, ROT_TWO);
3666 /* Fall through to save */
3667 case Store:
3668 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3669 break;
3670 case Del:
3671 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3672 break;
3673 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003674 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003675 PyErr_SetString(PyExc_SystemError,
3676 "param invalid in attribute expression");
3677 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678 }
3679 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003680 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681 switch (e->v.Subscript.ctx) {
3682 case AugLoad:
3683 VISIT(c, expr, e->v.Subscript.value);
3684 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3685 break;
3686 case Load:
3687 VISIT(c, expr, e->v.Subscript.value);
3688 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3689 break;
3690 case AugStore:
3691 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3692 break;
3693 case Store:
3694 VISIT(c, expr, e->v.Subscript.value);
3695 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3696 break;
3697 case Del:
3698 VISIT(c, expr, e->v.Subscript.value);
3699 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3700 break;
3701 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003702 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003703 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003704 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003705 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003706 }
3707 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003708 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003709 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3710 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003711 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003712 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003713 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003714 return compiler_tuple(c, e);
3715 }
3716 return 1;
3717}
3718
3719static int
3720compiler_augassign(struct compiler *c, stmt_ty s)
3721{
3722 expr_ty e = s->v.AugAssign.target;
3723 expr_ty auge;
3724
3725 assert(s->kind == AugAssign_kind);
3726
3727 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003728 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003729 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003730 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003731 if (auge == NULL)
3732 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003733 VISIT(c, expr, auge);
3734 VISIT(c, expr, s->v.AugAssign.value);
3735 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3736 auge->v.Attribute.ctx = AugStore;
3737 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 break;
3739 case Subscript_kind:
3740 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003741 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742 if (auge == NULL)
3743 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 VISIT(c, expr, auge);
3745 VISIT(c, expr, s->v.AugAssign.value);
3746 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003747 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003749 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003751 if (!compiler_nameop(c, e->v.Name.id, Load))
3752 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753 VISIT(c, expr, s->v.AugAssign.value);
3754 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3755 return compiler_nameop(c, e->v.Name.id, Store);
3756 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003757 PyErr_Format(PyExc_SystemError,
3758 "invalid node type (%d) for augmented assignment",
3759 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003760 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 }
3762 return 1;
3763}
3764
3765static int
3766compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3767{
3768 struct fblockinfo *f;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003769 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3770 PyErr_SetString(PyExc_SystemError,
3771 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003772 return 0;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003773 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 f = &c->u->u_fblock[c->u->u_nfblocks++];
3775 f->fb_type = t;
3776 f->fb_block = b;
3777 return 1;
3778}
3779
3780static void
3781compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3782{
3783 struct compiler_unit *u = c->u;
3784 assert(u->u_nfblocks > 0);
3785 u->u_nfblocks--;
3786 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3787 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3788}
3789
Georg Brandla5fe3ef2006-10-08 07:12:23 +00003790static int
3791compiler_in_loop(struct compiler *c) {
3792 int i;
3793 struct compiler_unit *u = c->u;
3794 for (i = 0; i < u->u_nfblocks; ++i) {
3795 if (u->u_fblock[i].fb_type == LOOP)
3796 return 1;
3797 }
3798 return 0;
3799}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003800/* Raises a SyntaxError and returns 0.
3801 If something goes wrong, a different exception may be raised.
3802*/
3803
3804static int
3805compiler_error(struct compiler *c, const char *errstr)
3806{
3807 PyObject *loc;
3808 PyObject *u = NULL, *v = NULL;
3809
3810 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3811 if (!loc) {
3812 Py_INCREF(Py_None);
3813 loc = Py_None;
3814 }
3815 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3816 Py_None, loc);
3817 if (!u)
3818 goto exit;
3819 v = Py_BuildValue("(zO)", errstr, u);
3820 if (!v)
3821 goto exit;
3822 PyErr_SetObject(PyExc_SyntaxError, v);
3823 exit:
3824 Py_DECREF(loc);
3825 Py_XDECREF(u);
3826 Py_XDECREF(v);
3827 return 0;
3828}
3829
3830static int
3831compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003832 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003834 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003836 /* XXX this code is duplicated */
3837 switch (ctx) {
3838 case AugLoad: /* fall through to Load */
3839 case Load: op = BINARY_SUBSCR; break;
3840 case AugStore:/* fall through to Store */
3841 case Store: op = STORE_SUBSCR; break;
3842 case Del: op = DELETE_SUBSCR; break;
3843 case Param:
3844 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003845 "invalid %s kind %d in subscript\n",
3846 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003847 return 0;
3848 }
3849 if (ctx == AugLoad) {
3850 ADDOP_I(c, DUP_TOPX, 2);
3851 }
3852 else if (ctx == AugStore) {
3853 ADDOP(c, ROT_THREE);
3854 }
3855 ADDOP(c, op);
3856 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003857}
3858
3859static int
3860compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3861{
3862 int n = 2;
3863 assert(s->kind == Slice_kind);
3864
3865 /* only handles the cases where BUILD_SLICE is emitted */
3866 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003867 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003868 }
3869 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003870 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003872
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003874 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875 }
3876 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003877 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 }
3879
3880 if (s->v.Slice.step) {
3881 n++;
3882 VISIT(c, expr, s->v.Slice.step);
3883 }
3884 ADDOP_I(c, BUILD_SLICE, n);
3885 return 1;
3886}
3887
3888static int
3889compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3890{
3891 int op = 0, slice_offset = 0, stack_count = 0;
3892
3893 assert(s->v.Slice.step == NULL);
3894 if (s->v.Slice.lower) {
3895 slice_offset++;
3896 stack_count++;
3897 if (ctx != AugStore)
3898 VISIT(c, expr, s->v.Slice.lower);
3899 }
3900 if (s->v.Slice.upper) {
3901 slice_offset += 2;
3902 stack_count++;
3903 if (ctx != AugStore)
3904 VISIT(c, expr, s->v.Slice.upper);
3905 }
3906
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003907 if (ctx == AugLoad) {
3908 switch (stack_count) {
3909 case 0: ADDOP(c, DUP_TOP); break;
3910 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3911 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3912 }
3913 }
3914 else if (ctx == AugStore) {
3915 switch (stack_count) {
3916 case 0: ADDOP(c, ROT_TWO); break;
3917 case 1: ADDOP(c, ROT_THREE); break;
3918 case 2: ADDOP(c, ROT_FOUR); break;
3919 }
3920 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921
3922 switch (ctx) {
3923 case AugLoad: /* fall through to Load */
3924 case Load: op = SLICE; break;
3925 case AugStore:/* fall through to Store */
3926 case Store: op = STORE_SLICE; break;
3927 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003928 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003929 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003930 PyErr_SetString(PyExc_SystemError,
3931 "param invalid in simple slice");
3932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933 }
3934
3935 ADDOP(c, op + slice_offset);
3936 return 1;
3937}
3938
3939static int
3940compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3941 expr_context_ty ctx)
3942{
3943 switch (s->kind) {
3944 case Ellipsis_kind:
3945 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3946 break;
3947 case Slice_kind:
3948 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003949 case Index_kind:
3950 VISIT(c, expr, s->v.Index.value);
3951 break;
3952 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003953 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003954 PyErr_SetString(PyExc_SystemError,
3955 "extended slice invalid in nested slice");
3956 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003957 }
3958 return 1;
3959}
3960
3961
3962static int
3963compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3964{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003965 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003967 case Index_kind:
3968 kindname = "index";
3969 if (ctx != AugStore) {
3970 VISIT(c, expr, s->v.Index.value);
3971 }
3972 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003973 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003974 kindname = "ellipsis";
3975 if (ctx != AugStore) {
3976 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3977 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003978 break;
3979 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003980 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003981 if (!s->v.Slice.step)
3982 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003983 if (ctx != AugStore) {
3984 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985 return 0;
3986 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003987 break;
3988 case ExtSlice_kind:
3989 kindname = "extended slice";
3990 if (ctx != AugStore) {
3991 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3992 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003993 slice_ty sub = (slice_ty)asdl_seq_GET(
3994 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003995 if (!compiler_visit_nested_slice(c, sub, ctx))
3996 return 0;
3997 }
3998 ADDOP_I(c, BUILD_TUPLE, n);
3999 }
4000 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004001 default:
4002 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004003 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004006 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004007}
4008
4009/* do depth-first search of basic block graph, starting with block.
4010 post records the block indices in post-order.
4011
4012 XXX must handle implicit jumps from one block to next
4013*/
4014
4015static void
4016dfs(struct compiler *c, basicblock *b, struct assembler *a)
4017{
4018 int i;
4019 struct instr *instr = NULL;
4020
4021 if (b->b_seen)
4022 return;
4023 b->b_seen = 1;
4024 if (b->b_next != NULL)
4025 dfs(c, b->b_next, a);
4026 for (i = 0; i < b->b_iused; i++) {
4027 instr = &b->b_instr[i];
4028 if (instr->i_jrel || instr->i_jabs)
4029 dfs(c, instr->i_target, a);
4030 }
4031 a->a_postorder[a->a_nblocks++] = b;
4032}
4033
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004034static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004035stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4036{
4037 int i;
4038 struct instr *instr;
4039 if (b->b_seen || b->b_startdepth >= depth)
4040 return maxdepth;
4041 b->b_seen = 1;
4042 b->b_startdepth = depth;
4043 for (i = 0; i < b->b_iused; i++) {
4044 instr = &b->b_instr[i];
4045 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
4046 if (depth > maxdepth)
4047 maxdepth = depth;
4048 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4049 if (instr->i_jrel || instr->i_jabs) {
4050 maxdepth = stackdepth_walk(c, instr->i_target,
4051 depth, maxdepth);
4052 if (instr->i_opcode == JUMP_ABSOLUTE ||
4053 instr->i_opcode == JUMP_FORWARD) {
4054 goto out; /* remaining code is dead */
4055 }
4056 }
4057 }
4058 if (b->b_next)
4059 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
4060out:
4061 b->b_seen = 0;
4062 return maxdepth;
4063}
4064
4065/* Find the flow path that needs the largest stack. We assume that
4066 * cycles in the flow graph have no net effect on the stack depth.
4067 */
4068static int
4069stackdepth(struct compiler *c)
4070{
4071 basicblock *b, *entryblock;
4072 entryblock = NULL;
4073 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4074 b->b_seen = 0;
4075 b->b_startdepth = INT_MIN;
4076 entryblock = b;
4077 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00004078 if (!entryblock)
4079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080 return stackdepth_walk(c, entryblock, 0, 0);
4081}
4082
4083static int
4084assemble_init(struct assembler *a, int nblocks, int firstlineno)
4085{
4086 memset(a, 0, sizeof(struct assembler));
4087 a->a_lineno = firstlineno;
4088 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4089 if (!a->a_bytecode)
4090 return 0;
4091 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4092 if (!a->a_lnotab)
4093 return 0;
4094 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004095 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004096 if (!a->a_postorder) {
4097 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004099 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 return 1;
4101}
4102
4103static void
4104assemble_free(struct assembler *a)
4105{
4106 Py_XDECREF(a->a_bytecode);
4107 Py_XDECREF(a->a_lnotab);
4108 if (a->a_postorder)
4109 PyObject_Free(a->a_postorder);
4110}
4111
4112/* Return the size of a basic block in bytes. */
4113
4114static int
4115instrsize(struct instr *instr)
4116{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004117 if (!instr->i_hasarg)
4118 return 1;
4119 if (instr->i_oparg > 0xffff)
4120 return 6;
4121 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122}
4123
4124static int
4125blocksize(basicblock *b)
4126{
4127 int i;
4128 int size = 0;
4129
4130 for (i = 0; i < b->b_iused; i++)
4131 size += instrsize(&b->b_instr[i]);
4132 return size;
4133}
4134
4135/* All about a_lnotab.
4136
4137c_lnotab is an array of unsigned bytes disguised as a Python string.
4138It is used to map bytecode offsets to source code line #s (when needed
4139for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004140
Tim Peters2a7f3842001-06-09 09:26:21 +00004141The array is conceptually a list of
4142 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004143pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004144
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004145 byte code offset source code line number
4146 0 1
4147 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004148 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004149 350 307
4150 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004151
4152The first trick is that these numbers aren't stored, only the increments
4153from one row to the next (this doesn't really work, but it's a start):
4154
4155 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4156
4157The second trick is that an unsigned byte can't hold negative values, or
4158values larger than 255, so (a) there's a deep assumption that byte code
4159offsets and their corresponding line #s both increase monotonically, and (b)
4160if at least one column jumps by more than 255 from one row to the next, more
4161than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004162from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004163part. A user of c_lnotab desiring to find the source line number
4164corresponding to a bytecode address A should do something like this
4165
4166 lineno = addr = 0
4167 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004168 addr += addr_incr
4169 if addr > A:
4170 return lineno
4171 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004172
4173In order for this to work, when the addr field increments by more than 255,
4174the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004175increment is < 256. So, in the example above, assemble_lnotab (it used
4176to be called com_set_lineno) should not (as was actually done until 2.2)
4177expand 300, 300 to 255, 255, 45, 45,
4178 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004179*/
4180
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004181static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004183{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 int d_bytecode, d_lineno;
4185 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004186 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187
4188 d_bytecode = a->a_offset - a->a_lineno_off;
4189 d_lineno = i->i_lineno - a->a_lineno;
4190
4191 assert(d_bytecode >= 0);
4192 assert(d_lineno >= 0);
4193
Amaury Forgeot d'Arcbc212102008-02-04 23:51:55 +00004194 if(d_bytecode == 0 && d_lineno == 0)
4195 return 1;
4196
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004198 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 nbytes = a->a_lnotab_off + 2 * ncodes;
4200 len = PyString_GET_SIZE(a->a_lnotab);
4201 if (nbytes >= len) {
4202 if (len * 2 < nbytes)
4203 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004204 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205 len *= 2;
4206 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4207 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004208 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004209 lnotab = (unsigned char *)
4210 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004211 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004212 *lnotab++ = 255;
4213 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004215 d_bytecode -= ncodes * 255;
4216 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004217 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004218 assert(d_bytecode <= 255);
4219 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004220 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004221 nbytes = a->a_lnotab_off + 2 * ncodes;
4222 len = PyString_GET_SIZE(a->a_lnotab);
4223 if (nbytes >= len) {
4224 if (len * 2 < nbytes)
4225 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004226 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004227 len *= 2;
4228 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4229 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004230 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004231 lnotab = (unsigned char *)
4232 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004234 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004235 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004236 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004237 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004238 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004239 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004240 d_lineno -= ncodes * 255;
4241 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004242 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004243
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004244 len = PyString_GET_SIZE(a->a_lnotab);
4245 if (a->a_lnotab_off + 2 >= len) {
4246 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004247 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004248 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004249 lnotab = (unsigned char *)
4250 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004251
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004252 a->a_lnotab_off += 2;
4253 if (d_bytecode) {
4254 *lnotab++ = d_bytecode;
4255 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004256 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004257 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004258 *lnotab++ = 0;
4259 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004260 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004261 a->a_lineno = i->i_lineno;
4262 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004263 return 1;
4264}
4265
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004266/* assemble_emit()
4267 Extend the bytecode with a new instruction.
4268 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004269*/
4270
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004271static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004273{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004274 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004275 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004276 char *code;
4277
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004278 size = instrsize(i);
4279 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004280 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004281 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004282 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004284 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285 if (a->a_offset + size >= len) {
4286 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004287 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4290 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004291 if (size == 6) {
4292 assert(i->i_hasarg);
4293 *code++ = (char)EXTENDED_ARG;
4294 *code++ = ext & 0xff;
4295 *code++ = ext >> 8;
4296 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004297 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004298 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004299 if (i->i_hasarg) {
4300 assert(size == 3 || size == 6);
4301 *code++ = arg & 0xff;
4302 *code++ = arg >> 8;
4303 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004304 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004305}
4306
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004307static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004309{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004311 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004312 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004314 /* Compute the size of each block and fixup jump args.
4315 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004316start:
4317 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004318 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004319 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004320 bsize = blocksize(b);
4321 b->b_offset = totsize;
4322 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004323 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004324 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4326 bsize = b->b_offset;
4327 for (i = 0; i < b->b_iused; i++) {
4328 struct instr *instr = &b->b_instr[i];
4329 /* Relative jumps are computed relative to
4330 the instruction pointer after fetching
4331 the jump instruction.
4332 */
4333 bsize += instrsize(instr);
4334 if (instr->i_jabs)
4335 instr->i_oparg = instr->i_target->b_offset;
4336 else if (instr->i_jrel) {
4337 int delta = instr->i_target->b_offset - bsize;
4338 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004339 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004340 else
4341 continue;
4342 if (instr->i_oparg > 0xffff)
4343 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004344 }
4345 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004346
4347 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004348 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004349 with a better solution.
4350
4351 In the meantime, should the goto be dropped in favor
4352 of a loop?
4353
4354 The issue is that in the first loop blocksize() is called
4355 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004356 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004357 i_oparg is calculated in the second loop above.
4358
4359 So we loop until we stop seeing new EXTENDED_ARGs.
4360 The only EXTENDED_ARGs that could be popping up are
4361 ones in jump instructions. So this should converge
4362 fairly quickly.
4363 */
4364 if (last_extended_arg_count != extended_arg_count) {
4365 last_extended_arg_count = extended_arg_count;
4366 goto start;
4367 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004368}
4369
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004370static PyObject *
4371dict_keys_inorder(PyObject *dict, int offset)
4372{
4373 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004374 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004375
4376 tuple = PyTuple_New(size);
4377 if (tuple == NULL)
4378 return NULL;
4379 while (PyDict_Next(dict, &pos, &k, &v)) {
4380 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004381 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004382 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004383 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004384 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004385 PyTuple_SET_ITEM(tuple, i - offset, k);
4386 }
4387 return tuple;
4388}
4389
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004390static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004392{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393 PySTEntryObject *ste = c->u->u_ste;
4394 int flags = 0, n;
4395 if (ste->ste_type != ModuleBlock)
4396 flags |= CO_NEWLOCALS;
4397 if (ste->ste_type == FunctionBlock) {
4398 if (!ste->ste_unoptimized)
4399 flags |= CO_OPTIMIZED;
4400 if (ste->ste_nested)
4401 flags |= CO_NESTED;
4402 if (ste->ste_generator)
4403 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405 if (ste->ste_varargs)
4406 flags |= CO_VARARGS;
4407 if (ste->ste_varkeywords)
4408 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004409 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004410 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004411
4412 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004413 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004414
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415 n = PyDict_Size(c->u->u_freevars);
4416 if (n < 0)
4417 return -1;
4418 if (n == 0) {
4419 n = PyDict_Size(c->u->u_cellvars);
4420 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004421 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422 if (n == 0) {
4423 flags |= CO_NOFREE;
4424 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004425 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004426
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004427 return flags;
4428}
4429
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430static PyCodeObject *
4431makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004432{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004433 PyObject *tmp;
4434 PyCodeObject *co = NULL;
4435 PyObject *consts = NULL;
4436 PyObject *names = NULL;
4437 PyObject *varnames = NULL;
4438 PyObject *filename = NULL;
4439 PyObject *name = NULL;
4440 PyObject *freevars = NULL;
4441 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004442 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004444
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004445 tmp = dict_keys_inorder(c->u->u_consts, 0);
4446 if (!tmp)
4447 goto error;
4448 consts = PySequence_List(tmp); /* optimize_code requires a list */
4449 Py_DECREF(tmp);
4450
4451 names = dict_keys_inorder(c->u->u_names, 0);
4452 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4453 if (!consts || !names || !varnames)
4454 goto error;
4455
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004456 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4457 if (!cellvars)
4458 goto error;
4459 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4460 if (!freevars)
4461 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004462 filename = PyString_FromString(c->c_filename);
4463 if (!filename)
4464 goto error;
4465
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004466 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004467 flags = compute_code_flags(c);
4468 if (flags < 0)
4469 goto error;
4470
4471 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4472 if (!bytecode)
4473 goto error;
4474
4475 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4476 if (!tmp)
4477 goto error;
4478 Py_DECREF(consts);
4479 consts = tmp;
4480
4481 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4482 bytecode, consts, names, varnames,
4483 freevars, cellvars,
4484 filename, c->u->u_name,
4485 c->u->u_firstlineno,
4486 a->a_lnotab);
4487 error:
4488 Py_XDECREF(consts);
4489 Py_XDECREF(names);
4490 Py_XDECREF(varnames);
4491 Py_XDECREF(filename);
4492 Py_XDECREF(name);
4493 Py_XDECREF(freevars);
4494 Py_XDECREF(cellvars);
4495 Py_XDECREF(bytecode);
4496 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004497}
4498
Neal Norwitz4ffedad2006-08-04 04:58:47 +00004499
4500/* For debugging purposes only */
4501#if 0
4502static void
4503dump_instr(const struct instr *i)
4504{
4505 const char *jrel = i->i_jrel ? "jrel " : "";
4506 const char *jabs = i->i_jabs ? "jabs " : "";
4507 char arg[128];
4508
4509 *arg = '\0';
4510 if (i->i_hasarg)
4511 sprintf(arg, "arg: %d ", i->i_oparg);
4512
4513 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4514 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4515}
4516
4517static void
4518dump_basicblock(const basicblock *b)
4519{
4520 const char *seen = b->b_seen ? "seen " : "";
4521 const char *b_return = b->b_return ? "return " : "";
4522 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4523 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4524 if (b->b_instr) {
4525 int i;
4526 for (i = 0; i < b->b_iused; i++) {
4527 fprintf(stderr, " [%02d] ", i);
4528 dump_instr(b->b_instr + i);
4529 }
4530 }
4531}
4532#endif
4533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004534static PyCodeObject *
4535assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004536{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004537 basicblock *b, *entryblock;
4538 struct assembler a;
4539 int i, j, nblocks;
4540 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004541
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004542 /* Make sure every block that falls off the end returns None.
4543 XXX NEXT_BLOCK() isn't quite right, because if the last
4544 block ends with a jump or return b_next shouldn't set.
4545 */
4546 if (!c->u->u_curblock->b_return) {
4547 NEXT_BLOCK(c);
4548 if (addNone)
4549 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4550 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004551 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004552
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553 nblocks = 0;
4554 entryblock = NULL;
4555 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4556 nblocks++;
4557 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004558 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004559
Neal Norwitzed657552006-07-10 00:04:44 +00004560 /* Set firstlineno if it wasn't explicitly set. */
4561 if (!c->u->u_firstlineno) {
4562 if (entryblock && entryblock->b_instr)
4563 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4564 else
4565 c->u->u_firstlineno = 1;
4566 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004567 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4568 goto error;
4569 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004570
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004571 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004572 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004573
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004574 /* Emit code in reverse postorder from dfs. */
4575 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004576 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004577 for (j = 0; j < b->b_iused; j++)
4578 if (!assemble_emit(&a, &b->b_instr[j]))
4579 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004580 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004581
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004582 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4583 goto error;
4584 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4585 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004586
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004587 co = makecode(c, &a);
4588 error:
4589 assemble_free(&a);
4590 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004591}