blob: 1217c1e6aa88a88ce946533263486a642769140e [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_ {
61 /* next block in the list of blocks for a unit (don't confuse with
62 * b_next) */
63 struct basicblock_ *b_list;
64 /* number of instructions used */
65 int b_iused;
66 /* length of instruction array (b_instr) */
67 int b_ialloc;
68 /* pointer to an array of instructions, initially NULL */
69 struct instr *b_instr;
70 /* If b_next is non-NULL, it is a pointer to the next
71 block reached by normal control flow. */
72 struct basicblock_ *b_next;
73 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000076 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077 /* depth of stack upon entry of block, computed by stackdepth() */
78 int b_startdepth;
79 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000080 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081} basicblock;
82
83/* fblockinfo tracks the current frame block.
84
Jeremy Hyltone9357b22006-03-01 15:47:05 +000085A frame block is used to handle loops, try/except, and try/finally.
86It's called a frame block to distinguish it from a basic block in the
87compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000088*/
89
90enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
91
92struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000093 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094 basicblock *fb_block;
95};
96
97/* The following items change on entry and exit of code blocks.
98 They must be saved and restored when returning to a block.
99*/
100struct compiler_unit {
101 PySTEntryObject *u_ste;
102
103 PyObject *u_name;
104 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000105 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106 the argument for opcodes that refer to those collections.
107 */
108 PyObject *u_consts; /* all constants */
109 PyObject *u_names; /* all names */
110 PyObject *u_varnames; /* local variables */
111 PyObject *u_cellvars; /* cell variables */
112 PyObject *u_freevars; /* free variables */
113
114 PyObject *u_private; /* for private name mangling */
115
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000116 int u_argcount; /* number of arguments for block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000117 basicblock *u_blocks; /* pointer to list of blocks */
118 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000119 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
121 int u_nfblocks;
122 struct fblockinfo u_fblock[CO_MAXBLOCKS];
123
124 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000125 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126 bool u_lineno_set; /* boolean to indicate whether instr
127 has been generated with current lineno */
128};
129
130/* This struct captures the global state of a compilation.
131
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132The u pointer points to the current compilation unit, while units
133for enclosing blocks are stored in c_stack. The u and c_stack are
134managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135*/
136
137struct compiler {
138 const char *c_filename;
139 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141 PyCompilerFlags *c_flags;
142
143 int c_interactive;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150};
151
152struct assembler {
153 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000154 int a_offset; /* offset into bytecode */
155 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156 basicblock **a_postorder; /* list of blocks in dfs postorder */
157 PyObject *a_lnotab; /* string containing lnotab */
158 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000159 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160 int a_lineno_off; /* bytecode offset of last lineno */
161};
162
163static int compiler_enter_scope(struct compiler *, identifier, void *, int);
164static void compiler_free(struct compiler *);
165static basicblock *compiler_new_block(struct compiler *);
166static int compiler_next_instr(struct compiler *, basicblock *);
167static int compiler_addop(struct compiler *, int);
168static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
169static int compiler_addop_i(struct compiler *, int, int);
170static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static basicblock *compiler_use_new_block(struct compiler *);
172static int compiler_error(struct compiler *, const char *);
173static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
174
175static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
176static int compiler_visit_stmt(struct compiler *, stmt_ty);
177static int compiler_visit_keyword(struct compiler *, keyword_ty);
178static int compiler_visit_expr(struct compiler *, expr_ty);
179static int compiler_augassign(struct compiler *, stmt_ty);
180static int compiler_visit_slice(struct compiler *, slice_ty,
181 expr_context_ty);
182
183static int compiler_push_fblock(struct compiler *, enum fblocktype,
184 basicblock *);
185static void compiler_pop_fblock(struct compiler *, enum fblocktype,
186 basicblock *);
187
188static int inplace_binop(struct compiler *, operator_ty);
189static int expr_constant(expr_ty e);
190
Guido van Rossumc2e20742006-02-27 22:32:47 +0000191static int compiler_with(struct compiler *, stmt_ty);
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193static PyCodeObject *assemble(struct compiler *, int addNone);
194static PyObject *__doc__;
195
196PyObject *
197_Py_Mangle(PyObject *private, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000198{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199 /* Name mangling: __private becomes _classname__private.
200 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000201 const char *p, *name = PyString_AsString(ident);
202 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203 size_t nlen, plen;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 if (private == NULL || name == NULL || name[0] != '_' ||
205 name[1] != '_') {
206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
209 p = PyString_AsString(private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 nlen = strlen(name);
211 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000212 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 /* Strip leading underscores from class name */
216 while (*p == '_')
217 p++;
218 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
224 if (!ident)
225 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000227 buffer = PyString_AS_STRING(ident);
228 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 strncpy(buffer+1, p, plen);
230 strcpy(buffer+1+plen, name);
231 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000232}
233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234static int
235compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000236{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 c->c_stack = PyList_New(0);
240 if (!c->c_stack)
241 return 0;
242
243 return 1;
244}
245
246PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000247PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249{
250 struct compiler c;
251 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000252 PyCompilerFlags local_flags;
253 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 if (!__doc__) {
256 __doc__ = PyString_InternFromString("__doc__");
257 if (!__doc__)
258 return NULL;
259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260
261 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000262 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_future = PyFuture_FromAST(mod, filename);
266 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000267 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 local_flags.cf_flags = 0;
270 flags = &local_flags;
271 }
272 merged = c.c_future->ff_features | flags->cf_flags;
273 c.c_future->ff_features = merged;
274 flags->cf_flags = merged;
275 c.c_flags = flags;
276 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
278 c.c_st = PySymtable_Build(mod, filename, c.c_future);
279 if (c.c_st == NULL) {
280 if (!PyErr_Occurred())
281 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000282 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 }
284
285 /* XXX initialize to NULL for now, need to handle */
286 c.c_encoding = NULL;
287
288 co = compiler_mod(&c, mod);
289
Thomas Wouters1175c432006-02-27 22:49:54 +0000290 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000292 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293 return co;
294}
295
296PyCodeObject *
297PyNode_Compile(struct _node *n, const char *filename)
298{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000299 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000300 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 mod_ty mod = PyAST_FromNode(n, NULL, filename, arena);
302 if (mod)
303 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000305 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000306}
307
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000308static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000310{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311 if (c->c_st)
312 PySymtable_Free(c->c_st);
313 if (c->c_future)
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000314 PyMem_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316}
317
Guido van Rossum79f25d91997-04-29 20:08:16 +0000318static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000320{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000321 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000322 PyObject *v, *k;
323 PyObject *dict = PyDict_New();
324 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326 n = PyList_Size(list);
327 for (i = 0; i < n; i++) {
328 v = PyInt_FromLong(i);
329 if (!v) {
330 Py_DECREF(dict);
331 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000332 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000333 k = PyList_GET_ITEM(list, i);
334 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
336 Py_XDECREF(k);
337 Py_DECREF(v);
338 Py_DECREF(dict);
339 return NULL;
340 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000341 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344 return dict;
345}
346
347/* Return new dict containing names from src that match scope(s).
348
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000349src is a symbol table dictionary. If the scope of a name matches
350either scope_type or flag is set, insert it into the new dict. The
351values are integers, starting at offset and increasing by one for
352each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000353*/
354
355static PyObject *
356dictbytype(PyObject *src, int scope_type, int flag, int offset)
357{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000358 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000359 PyObject *k, *v, *dest = PyDict_New();
360
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000361 assert(offset >= 0);
362 if (dest == NULL)
363 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000364
365 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000366 /* XXX this should probably be a macro in symtable.h */
367 assert(PyInt_Check(v));
368 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000369
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000370 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
371 PyObject *tuple, *item = PyInt_FromLong(i);
372 if (item == NULL) {
373 Py_DECREF(dest);
374 return NULL;
375 }
376 i++;
377 tuple = Py_BuildValue("(OO)", k, k->ob_type);
378 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
379 Py_DECREF(item);
380 Py_DECREF(dest);
381 Py_XDECREF(tuple);
382 return NULL;
383 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000385 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000386 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000387 }
388 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000389}
390
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000391/* Begin: Peephole optimizations ----------------------------------------- */
392
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000393#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000394#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000395#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
396#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000397#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000398#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000399#define ISBASICBLOCK(blocks, start, bytes) \
400 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000401
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000402/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000403 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000404 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000405 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000406 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000407 Bails out with no change if one or more of the LOAD_CONSTs is missing.
408 Also works for BUILD_LIST when followed by an "in" or "not in" test.
409*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000410static int
411tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
412{
413 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000415
416 /* Pre-conditions */
417 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000418 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000419 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000420 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000421 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422
423 /* Buildup new tuple of constants */
424 newconst = PyTuple_New(n);
425 if (newconst == NULL)
426 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000427 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000428 for (i=0 ; i<n ; i++) {
429 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000430 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 constant = PyList_GET_ITEM(consts, arg);
432 Py_INCREF(constant);
433 PyTuple_SET_ITEM(newconst, i, constant);
434 }
435
436 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000437 if (PyList_Append(consts, newconst)) {
438 Py_DECREF(newconst);
439 return 0;
440 }
441 Py_DECREF(newconst);
442
443 /* Write NOPs over old LOAD_CONSTS and
444 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
445 memset(codestr, NOP, n*3);
446 codestr[n*3] = LOAD_CONST;
447 SETARG(codestr, (n*3), len_consts);
448 return 1;
449}
450
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000451/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000452 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000453 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000454 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000455 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000456 Abandons the transformation if the folding fails (i.e. 1+'a').
457 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000458 is below a threshold value. That keeps pyc files from
459 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000460*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000461static int
462fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
463{
464 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465 Py_ssize_t len_consts, size;
466 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000467
468 /* Pre-conditions */
469 assert(PyList_CheckExact(consts));
470 assert(codestr[0] == LOAD_CONST);
471 assert(codestr[3] == LOAD_CONST);
472
473 /* Create new constant */
474 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
475 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
476 opcode = codestr[6];
477 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000478 case BINARY_POWER:
479 newconst = PyNumber_Power(v, w, Py_None);
480 break;
481 case BINARY_MULTIPLY:
482 newconst = PyNumber_Multiply(v, w);
483 break;
484 case BINARY_DIVIDE:
485 /* Cannot fold this operation statically since
486 the result can depend on the run-time presence
487 of the -Qnew flag */
488 return 0;
489 case BINARY_TRUE_DIVIDE:
490 newconst = PyNumber_TrueDivide(v, w);
491 break;
492 case BINARY_FLOOR_DIVIDE:
493 newconst = PyNumber_FloorDivide(v, w);
494 break;
495 case BINARY_MODULO:
496 newconst = PyNumber_Remainder(v, w);
497 break;
498 case BINARY_ADD:
499 newconst = PyNumber_Add(v, w);
500 break;
501 case BINARY_SUBTRACT:
502 newconst = PyNumber_Subtract(v, w);
503 break;
504 case BINARY_SUBSCR:
505 newconst = PyObject_GetItem(v, w);
506 break;
507 case BINARY_LSHIFT:
508 newconst = PyNumber_Lshift(v, w);
509 break;
510 case BINARY_RSHIFT:
511 newconst = PyNumber_Rshift(v, w);
512 break;
513 case BINARY_AND:
514 newconst = PyNumber_And(v, w);
515 break;
516 case BINARY_XOR:
517 newconst = PyNumber_Xor(v, w);
518 break;
519 case BINARY_OR:
520 newconst = PyNumber_Or(v, w);
521 break;
522 default:
523 /* Called with an unknown opcode */
524 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000525 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000526 opcode);
527 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000528 }
529 if (newconst == NULL) {
530 PyErr_Clear();
531 return 0;
532 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000533 size = PyObject_Size(newconst);
534 if (size == -1)
535 PyErr_Clear();
536 else if (size > 20) {
537 Py_DECREF(newconst);
538 return 0;
539 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000540
541 /* Append folded constant into consts table */
542 len_consts = PyList_GET_SIZE(consts);
543 if (PyList_Append(consts, newconst)) {
544 Py_DECREF(newconst);
545 return 0;
546 }
547 Py_DECREF(newconst);
548
549 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
550 memset(codestr, NOP, 4);
551 codestr[4] = LOAD_CONST;
552 SETARG(codestr, 4, len_consts);
553 return 1;
554}
555
Raymond Hettinger80121492005-02-20 12:41:32 +0000556static int
557fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
558{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000559 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000560 Py_ssize_t len_consts;
561 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000562
563 /* Pre-conditions */
564 assert(PyList_CheckExact(consts));
565 assert(codestr[0] == LOAD_CONST);
566
567 /* Create new constant */
568 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
569 opcode = codestr[3];
570 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000571 case UNARY_NEGATIVE:
572 /* Preserve the sign of -0.0 */
573 if (PyObject_IsTrue(v) == 1)
574 newconst = PyNumber_Negative(v);
575 break;
576 case UNARY_CONVERT:
577 newconst = PyObject_Repr(v);
578 break;
579 case UNARY_INVERT:
580 newconst = PyNumber_Invert(v);
581 break;
582 default:
583 /* Called with an unknown opcode */
584 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000585 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000586 opcode);
587 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000588 }
589 if (newconst == NULL) {
590 PyErr_Clear();
591 return 0;
592 }
593
594 /* Append folded constant into consts table */
595 len_consts = PyList_GET_SIZE(consts);
596 if (PyList_Append(consts, newconst)) {
597 Py_DECREF(newconst);
598 return 0;
599 }
600 Py_DECREF(newconst);
601
602 /* Write NOP LOAD_CONST newconst */
603 codestr[0] = NOP;
604 codestr[1] = LOAD_CONST;
605 SETARG(codestr, 1, len_consts);
606 return 1;
607}
608
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000609static unsigned int *
610markblocks(unsigned char *code, int len)
611{
612 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000613 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000614
615 if (blocks == NULL)
616 return NULL;
617 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000618
619 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000620 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
621 opcode = code[i];
622 switch (opcode) {
623 case FOR_ITER:
624 case JUMP_FORWARD:
625 case JUMP_IF_FALSE:
626 case JUMP_IF_TRUE:
627 case JUMP_ABSOLUTE:
628 case CONTINUE_LOOP:
629 case SETUP_LOOP:
630 case SETUP_EXCEPT:
631 case SETUP_FINALLY:
632 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000633 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000634 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000635 }
636 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000637 /* Build block numbers in the second pass */
638 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000639 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000640 blocks[i] = blockcnt;
641 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000642 return blocks;
643}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000644
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000645/* Perform basic peephole optimizations to components of a code object.
646 The consts object should still be in list form to allow new constants
647 to be appended.
648
649 To keep the optimizer simple, it bails out (does nothing) for code
650 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000651 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000652 the lineno table has complex encoding for gaps >= 255.
653
654 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000655 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000656 smaller. For those that reduce size, the gaps are initially filled with
657 NOPs. Later those NOPs are removed and the jump addresses retargeted in
658 a single pass. Line numbering is adjusted accordingly. */
659
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000660static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000661optimize_code(PyObject *code, PyObject* consts, PyObject *names,
662 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000663{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000664 Py_ssize_t i, j, codelen;
665 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000666 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000667 unsigned char *codestr = NULL;
668 unsigned char *lineno;
669 int *addrmap = NULL;
670 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000671 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000672 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000673 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000674
Raymond Hettingereffb3932004-10-30 08:55:08 +0000675 /* Bail out if an exception is set */
676 if (PyErr_Occurred())
677 goto exitUnchanged;
678
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000679 /* Bypass optimization when the lineno table is too complex */
680 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000681 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000682 tabsiz = PyString_GET_SIZE(lineno_obj);
683 if (memchr(lineno, 255, tabsiz) != NULL)
684 goto exitUnchanged;
685
Raymond Hettingera12fa142004-08-24 04:34:16 +0000686 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000687 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000688 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000689 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000690 goto exitUnchanged;
691
692 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000693 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000694 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000695 goto exitUnchanged;
696 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000697
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000698 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000699 the various transformation patterns to look ahead several
700 instructions without additional checks to make sure they are not
701 looking beyond the end of the code string.
702 */
703 if (codestr[codelen-1] != RETURN_VALUE)
704 goto exitUnchanged;
705
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000706 /* Mapping to new jump targets after NOPs are removed */
707 addrmap = PyMem_Malloc(codelen * sizeof(int));
708 if (addrmap == NULL)
709 goto exitUnchanged;
710
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000711 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000712 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000713 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000714 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000715
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000716 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000717 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000718
719 lastlc = cumlc;
720 cumlc = 0;
721
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000722 switch (opcode) {
723
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000724 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
725 with JUMP_IF_TRUE POP_TOP */
726 case UNARY_NOT:
727 if (codestr[i+1] != JUMP_IF_FALSE ||
728 codestr[i+4] != POP_TOP ||
729 !ISBASICBLOCK(blocks,i,5))
730 continue;
731 tgt = GETJUMPTGT(codestr, (i+1));
732 if (codestr[tgt] != POP_TOP)
733 continue;
734 j = GETARG(codestr, i+1) + 1;
735 codestr[i] = JUMP_IF_TRUE;
736 SETARG(codestr, i, j);
737 codestr[i+3] = POP_TOP;
738 codestr[i+4] = NOP;
739 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000740
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000741 /* not a is b --> a is not b
742 not a in b --> a not in b
743 not a is not b --> a is b
744 not a not in b --> a in b
745 */
746 case COMPARE_OP:
747 j = GETARG(codestr, i);
748 if (j < 6 || j > 9 ||
749 codestr[i+3] != UNARY_NOT ||
750 !ISBASICBLOCK(blocks,i,4))
751 continue;
752 SETARG(codestr, i, (j^1));
753 codestr[i+3] = NOP;
754 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000755
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000756 /* Replace LOAD_GLOBAL/LOAD_NAME None
757 with LOAD_CONST None */
758 case LOAD_NAME:
759 case LOAD_GLOBAL:
760 j = GETARG(codestr, i);
761 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
762 if (name == NULL || strcmp(name, "None") != 0)
763 continue;
764 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
765 if (PyList_GET_ITEM(consts, j) == Py_None) {
766 codestr[i] = LOAD_CONST;
767 SETARG(codestr, i, j);
768 cumlc = lastlc + 1;
769 break;
770 }
771 }
772 break;
773
774 /* Skip over LOAD_CONST trueconst
775 JUMP_IF_FALSE xx POP_TOP */
776 case LOAD_CONST:
777 cumlc = lastlc + 1;
778 j = GETARG(codestr, i);
779 if (codestr[i+3] != JUMP_IF_FALSE ||
780 codestr[i+6] != POP_TOP ||
781 !ISBASICBLOCK(blocks,i,7) ||
782 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
783 continue;
784 memset(codestr+i, NOP, 7);
785 cumlc = 0;
786 break;
787
788 /* Try to fold tuples of constants (includes a case for lists
789 which are only used for "in" and "not in" tests).
790 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
791 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
792 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
793 case BUILD_TUPLE:
794 case BUILD_LIST:
795 j = GETARG(codestr, i);
796 h = i - 3 * j;
797 if (h >= 0 &&
798 j <= lastlc &&
799 ((opcode == BUILD_TUPLE &&
800 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
801 (opcode == BUILD_LIST &&
802 codestr[i+3]==COMPARE_OP &&
803 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
804 (GETARG(codestr,i+3)==6 ||
805 GETARG(codestr,i+3)==7))) &&
806 tuple_of_constants(&codestr[h], j, consts)) {
807 assert(codestr[i] == LOAD_CONST);
808 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000809 break;
810 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000811 if (codestr[i+3] != UNPACK_SEQUENCE ||
812 !ISBASICBLOCK(blocks,i,6) ||
813 j != GETARG(codestr, i+3))
814 continue;
815 if (j == 1) {
816 memset(codestr+i, NOP, 6);
817 } else if (j == 2) {
818 codestr[i] = ROT_TWO;
819 memset(codestr+i+1, NOP, 5);
820 } else if (j == 3) {
821 codestr[i] = ROT_THREE;
822 codestr[i+1] = ROT_TWO;
823 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000824 }
825 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000826
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000827 /* Fold binary ops on constants.
828 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
829 case BINARY_POWER:
830 case BINARY_MULTIPLY:
831 case BINARY_TRUE_DIVIDE:
832 case BINARY_FLOOR_DIVIDE:
833 case BINARY_MODULO:
834 case BINARY_ADD:
835 case BINARY_SUBTRACT:
836 case BINARY_SUBSCR:
837 case BINARY_LSHIFT:
838 case BINARY_RSHIFT:
839 case BINARY_AND:
840 case BINARY_XOR:
841 case BINARY_OR:
842 if (lastlc >= 2 &&
843 ISBASICBLOCK(blocks, i-6, 7) &&
844 fold_binops_on_constants(&codestr[i-6], consts)) {
845 i -= 2;
846 assert(codestr[i] == LOAD_CONST);
847 cumlc = 1;
848 }
849 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000850
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000851 /* Fold unary ops on constants.
852 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
853 case UNARY_NEGATIVE:
854 case UNARY_CONVERT:
855 case UNARY_INVERT:
856 if (lastlc >= 1 &&
857 ISBASICBLOCK(blocks, i-3, 4) &&
858 fold_unaryops_on_constants(&codestr[i-3], consts)) {
859 i -= 2;
860 assert(codestr[i] == LOAD_CONST);
861 cumlc = 1;
862 }
863 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000864
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000865 /* Simplify conditional jump to conditional jump where the
866 result of the first test implies the success of a similar
867 test or the failure of the opposite test.
868 Arises in code like:
869 "if a and b:"
870 "if a or b:"
871 "a and b or c"
872 "(a and b) and c"
873 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
874 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
875 where y+3 is the instruction following the second test.
876 */
877 case JUMP_IF_FALSE:
878 case JUMP_IF_TRUE:
879 tgt = GETJUMPTGT(codestr, i);
880 j = codestr[tgt];
881 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
882 if (j == opcode) {
883 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
884 SETARG(codestr, i, tgttgt);
885 } else {
886 tgt -= i;
887 SETARG(codestr, i, tgt);
888 }
889 break;
890 }
891 /* Intentional fallthrough */
892
893 /* Replace jumps to unconditional jumps */
894 case FOR_ITER:
895 case JUMP_FORWARD:
896 case JUMP_ABSOLUTE:
897 case CONTINUE_LOOP:
898 case SETUP_LOOP:
899 case SETUP_EXCEPT:
900 case SETUP_FINALLY:
901 tgt = GETJUMPTGT(codestr, i);
902 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
903 continue;
904 tgttgt = GETJUMPTGT(codestr, tgt);
905 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
906 opcode = JUMP_ABSOLUTE;
907 if (!ABSOLUTE_JUMP(opcode))
908 tgttgt -= i + 3; /* Calc relative jump addr */
909 if (tgttgt < 0) /* No backward relative jumps */
910 continue;
911 codestr[i] = opcode;
912 SETARG(codestr, i, tgttgt);
913 break;
914
915 case EXTENDED_ARG:
916 goto exitUnchanged;
917
918 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
919 case RETURN_VALUE:
920 if (i+4 >= codelen ||
921 codestr[i+4] != RETURN_VALUE ||
922 !ISBASICBLOCK(blocks,i,5))
923 continue;
924 memset(codestr+i+1, NOP, 4);
925 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000926 }
927 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000928
929 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000930 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
931 addrmap[i] = i - nops;
932 if (codestr[i] == NOP)
933 nops++;
934 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000935 cum_orig_line = 0;
936 last_line = 0;
937 for (i=0 ; i < tabsiz ; i+=2) {
938 cum_orig_line += lineno[i];
939 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000940 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000941 lineno[i] =((unsigned char)(new_line - last_line));
942 last_line = new_line;
943 }
944
945 /* Remove NOPs and fixup jump targets */
946 for (i=0, h=0 ; i<codelen ; ) {
947 opcode = codestr[i];
948 switch (opcode) {
949 case NOP:
950 i++;
951 continue;
952
953 case JUMP_ABSOLUTE:
954 case CONTINUE_LOOP:
955 j = addrmap[GETARG(codestr, i)];
956 SETARG(codestr, i, j);
957 break;
958
959 case FOR_ITER:
960 case JUMP_FORWARD:
961 case JUMP_IF_FALSE:
962 case JUMP_IF_TRUE:
963 case SETUP_LOOP:
964 case SETUP_EXCEPT:
965 case SETUP_FINALLY:
966 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
967 SETARG(codestr, i, j);
968 break;
969 }
970 adj = CODESIZE(opcode);
971 while (adj--)
972 codestr[h++] = codestr[i++];
973 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000974 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000975
976 code = PyString_FromStringAndSize((char *)codestr, h);
977 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000978 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000979 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000980 return code;
981
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000982 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000983 if (blocks != NULL)
984 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000985 if (addrmap != NULL)
986 PyMem_Free(addrmap);
987 if (codestr != NULL)
988 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000989 Py_INCREF(code);
990 return code;
991}
992
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000993/* End: Peephole optimizations ----------------------------------------- */
994
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000995/*
996
997Leave this debugging code for just a little longer.
998
999static void
1000compiler_display_symbols(PyObject *name, PyObject *symbols)
1001{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001002PyObject *key, *value;
1003int flags;
1004Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001006fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1007while (PyDict_Next(symbols, &pos, &key, &value)) {
1008flags = PyInt_AsLong(value);
1009fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1010if (flags & DEF_GLOBAL)
1011fprintf(stderr, " declared_global");
1012if (flags & DEF_LOCAL)
1013fprintf(stderr, " local");
1014if (flags & DEF_PARAM)
1015fprintf(stderr, " param");
1016if (flags & DEF_STAR)
1017fprintf(stderr, " stararg");
1018if (flags & DEF_DOUBLESTAR)
1019fprintf(stderr, " starstar");
1020if (flags & DEF_INTUPLE)
1021fprintf(stderr, " tuple");
1022if (flags & DEF_FREE)
1023fprintf(stderr, " free");
1024if (flags & DEF_FREE_GLOBAL)
1025fprintf(stderr, " global");
1026if (flags & DEF_FREE_CLASS)
1027fprintf(stderr, " free/class");
1028if (flags & DEF_IMPORT)
1029fprintf(stderr, " import");
1030fprintf(stderr, "\n");
1031}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032 fprintf(stderr, "\n");
1033}
1034*/
1035
1036static void
1037compiler_unit_check(struct compiler_unit *u)
1038{
1039 basicblock *block;
1040 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1041 assert(block != (void *)0xcbcbcbcb);
1042 assert(block != (void *)0xfbfbfbfb);
1043 assert(block != (void *)0xdbdbdbdb);
1044 if (block->b_instr != NULL) {
1045 assert(block->b_ialloc > 0);
1046 assert(block->b_iused > 0);
1047 assert(block->b_ialloc >= block->b_iused);
1048 }
1049 else {
1050 assert (block->b_iused == 0);
1051 assert (block->b_ialloc == 0);
1052 }
1053 }
1054}
1055
1056static void
1057compiler_unit_free(struct compiler_unit *u)
1058{
1059 basicblock *b, *next;
1060
1061 compiler_unit_check(u);
1062 b = u->u_blocks;
1063 while (b != NULL) {
1064 if (b->b_instr)
1065 PyObject_Free((void *)b->b_instr);
1066 next = b->b_list;
1067 PyObject_Free((void *)b);
1068 b = next;
1069 }
1070 Py_XDECREF(u->u_ste);
1071 Py_XDECREF(u->u_name);
1072 Py_XDECREF(u->u_consts);
1073 Py_XDECREF(u->u_names);
1074 Py_XDECREF(u->u_varnames);
1075 Py_XDECREF(u->u_freevars);
1076 Py_XDECREF(u->u_cellvars);
1077 Py_XDECREF(u->u_private);
1078 PyObject_Free(u);
1079}
1080
1081static int
1082compiler_enter_scope(struct compiler *c, identifier name, void *key,
1083 int lineno)
1084{
1085 struct compiler_unit *u;
1086
1087 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001088 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001089 PyErr_NoMemory();
1090 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001091 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001092 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001093 u->u_argcount = 0;
1094 u->u_ste = PySymtable_Lookup(c->c_st, key);
1095 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001096 compiler_unit_free(u);
1097 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098 }
1099 Py_INCREF(name);
1100 u->u_name = name;
1101 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1102 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1103 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001104 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001105
1106 u->u_blocks = NULL;
1107 u->u_tmpname = 0;
1108 u->u_nfblocks = 0;
1109 u->u_firstlineno = lineno;
1110 u->u_lineno = 0;
1111 u->u_lineno_set = false;
1112 u->u_consts = PyDict_New();
1113 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001114 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001115 return 0;
1116 }
1117 u->u_names = PyDict_New();
1118 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001119 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 return 0;
1121 }
1122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001123 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001124
1125 /* Push the old compiler_unit on the stack. */
1126 if (c->u) {
1127 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1128 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001129 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 return 0;
1131 }
1132 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001133 u->u_private = c->u->u_private;
1134 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001135 }
1136 c->u = u;
1137
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001138 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001139 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001140 return 0;
1141
1142 return 1;
1143}
1144
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001145static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146compiler_exit_scope(struct compiler *c)
1147{
1148 int n;
1149 PyObject *wrapper;
1150
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001151 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 compiler_unit_free(c->u);
1153 /* Restore c->u to the parent unit. */
1154 n = PyList_GET_SIZE(c->c_stack) - 1;
1155 if (n >= 0) {
1156 wrapper = PyList_GET_ITEM(c->c_stack, n);
1157 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001158 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001160 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001161 compiler_unit_check(c->u);
1162 }
1163 else
1164 c->u = NULL;
1165
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001166}
1167
Guido van Rossumc2e20742006-02-27 22:32:47 +00001168/* Allocate a new "anonymous" local variable.
1169 Used by list comprehensions and with statements.
1170*/
1171
1172static PyObject *
1173compiler_new_tmpname(struct compiler *c)
1174{
1175 char tmpname[256];
1176 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1177 return PyString_FromString(tmpname);
1178}
1179
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180/* Allocate a new block and return a pointer to it.
1181 Returns NULL on error.
1182*/
1183
1184static basicblock *
1185compiler_new_block(struct compiler *c)
1186{
1187 basicblock *b;
1188 struct compiler_unit *u;
1189
1190 u = c->u;
1191 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001192 if (b == NULL) {
1193 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001195 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196 memset((void *)b, 0, sizeof(basicblock));
1197 assert (b->b_next == NULL);
1198 b->b_list = u->u_blocks;
1199 u->u_blocks = b;
1200 return b;
1201}
1202
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001203static basicblock *
1204compiler_use_new_block(struct compiler *c)
1205{
1206 basicblock *block = compiler_new_block(c);
1207 if (block == NULL)
1208 return NULL;
1209 c->u->u_curblock = block;
1210 return block;
1211}
1212
1213static basicblock *
1214compiler_next_block(struct compiler *c)
1215{
1216 basicblock *block = compiler_new_block(c);
1217 if (block == NULL)
1218 return NULL;
1219 c->u->u_curblock->b_next = block;
1220 c->u->u_curblock = block;
1221 return block;
1222}
1223
1224static basicblock *
1225compiler_use_next_block(struct compiler *c, basicblock *block)
1226{
1227 assert(block != NULL);
1228 c->u->u_curblock->b_next = block;
1229 c->u->u_curblock = block;
1230 return block;
1231}
1232
1233/* Returns the offset of the next instruction in the current block's
1234 b_instr array. Resizes the b_instr as necessary.
1235 Returns -1 on failure.
1236 */
1237
1238static int
1239compiler_next_instr(struct compiler *c, basicblock *b)
1240{
1241 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001242 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001243 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1244 DEFAULT_BLOCK_SIZE);
1245 if (b->b_instr == NULL) {
1246 PyErr_NoMemory();
1247 return -1;
1248 }
1249 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1250 memset((char *)b->b_instr, 0,
1251 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253 else if (b->b_iused == b->b_ialloc) {
1254 size_t oldsize, newsize;
1255 oldsize = b->b_ialloc * sizeof(struct instr);
1256 newsize = oldsize << 1;
1257 if (newsize == 0) {
1258 PyErr_NoMemory();
1259 return -1;
1260 }
1261 b->b_ialloc <<= 1;
1262 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1263 if (b->b_instr == NULL)
1264 return -1;
1265 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1266 }
1267 return b->b_iused++;
1268}
1269
1270static void
1271compiler_set_lineno(struct compiler *c, int off)
1272{
1273 basicblock *b;
1274 if (c->u->u_lineno_set)
1275 return;
1276 c->u->u_lineno_set = true;
1277 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001278 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001279}
1280
1281static int
1282opcode_stack_effect(int opcode, int oparg)
1283{
1284 switch (opcode) {
1285 case POP_TOP:
1286 return -1;
1287 case ROT_TWO:
1288 case ROT_THREE:
1289 return 0;
1290 case DUP_TOP:
1291 return 1;
1292 case ROT_FOUR:
1293 return 0;
1294
1295 case UNARY_POSITIVE:
1296 case UNARY_NEGATIVE:
1297 case UNARY_NOT:
1298 case UNARY_CONVERT:
1299 case UNARY_INVERT:
1300 return 0;
1301
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001302 case LIST_APPEND:
1303 return -2;
1304
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305 case BINARY_POWER:
1306 case BINARY_MULTIPLY:
1307 case BINARY_DIVIDE:
1308 case BINARY_MODULO:
1309 case BINARY_ADD:
1310 case BINARY_SUBTRACT:
1311 case BINARY_SUBSCR:
1312 case BINARY_FLOOR_DIVIDE:
1313 case BINARY_TRUE_DIVIDE:
1314 return -1;
1315 case INPLACE_FLOOR_DIVIDE:
1316 case INPLACE_TRUE_DIVIDE:
1317 return -1;
1318
1319 case SLICE+0:
1320 return 1;
1321 case SLICE+1:
1322 return 0;
1323 case SLICE+2:
1324 return 0;
1325 case SLICE+3:
1326 return -1;
1327
1328 case STORE_SLICE+0:
1329 return -2;
1330 case STORE_SLICE+1:
1331 return -3;
1332 case STORE_SLICE+2:
1333 return -3;
1334 case STORE_SLICE+3:
1335 return -4;
1336
1337 case DELETE_SLICE+0:
1338 return -1;
1339 case DELETE_SLICE+1:
1340 return -2;
1341 case DELETE_SLICE+2:
1342 return -2;
1343 case DELETE_SLICE+3:
1344 return -3;
1345
1346 case INPLACE_ADD:
1347 case INPLACE_SUBTRACT:
1348 case INPLACE_MULTIPLY:
1349 case INPLACE_DIVIDE:
1350 case INPLACE_MODULO:
1351 return -1;
1352 case STORE_SUBSCR:
1353 return -3;
1354 case DELETE_SUBSCR:
1355 return -2;
1356
1357 case BINARY_LSHIFT:
1358 case BINARY_RSHIFT:
1359 case BINARY_AND:
1360 case BINARY_XOR:
1361 case BINARY_OR:
1362 return -1;
1363 case INPLACE_POWER:
1364 return -1;
1365 case GET_ITER:
1366 return 0;
1367
1368 case PRINT_EXPR:
1369 return -1;
1370 case PRINT_ITEM:
1371 return -1;
1372 case PRINT_NEWLINE:
1373 return 0;
1374 case PRINT_ITEM_TO:
1375 return -2;
1376 case PRINT_NEWLINE_TO:
1377 return -1;
1378 case INPLACE_LSHIFT:
1379 case INPLACE_RSHIFT:
1380 case INPLACE_AND:
1381 case INPLACE_XOR:
1382 case INPLACE_OR:
1383 return -1;
1384 case BREAK_LOOP:
1385 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001386 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001387 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388 case LOAD_LOCALS:
1389 return 1;
1390 case RETURN_VALUE:
1391 return -1;
1392 case IMPORT_STAR:
1393 return -1;
1394 case EXEC_STMT:
1395 return -3;
1396 case YIELD_VALUE:
1397 return 0;
1398
1399 case POP_BLOCK:
1400 return 0;
1401 case END_FINALLY:
1402 return -1; /* or -2 or -3 if exception occurred */
1403 case BUILD_CLASS:
1404 return -2;
1405
1406 case STORE_NAME:
1407 return -1;
1408 case DELETE_NAME:
1409 return 0;
1410 case UNPACK_SEQUENCE:
1411 return oparg-1;
1412 case FOR_ITER:
1413 return 1;
1414
1415 case STORE_ATTR:
1416 return -2;
1417 case DELETE_ATTR:
1418 return -1;
1419 case STORE_GLOBAL:
1420 return -1;
1421 case DELETE_GLOBAL:
1422 return 0;
1423 case DUP_TOPX:
1424 return oparg;
1425 case LOAD_CONST:
1426 return 1;
1427 case LOAD_NAME:
1428 return 1;
1429 case BUILD_TUPLE:
1430 case BUILD_LIST:
1431 return 1-oparg;
1432 case BUILD_MAP:
1433 return 1;
1434 case LOAD_ATTR:
1435 return 0;
1436 case COMPARE_OP:
1437 return -1;
1438 case IMPORT_NAME:
1439 return 0;
1440 case IMPORT_FROM:
1441 return 1;
1442
1443 case JUMP_FORWARD:
1444 case JUMP_IF_FALSE:
1445 case JUMP_IF_TRUE:
1446 case JUMP_ABSOLUTE:
1447 return 0;
1448
1449 case LOAD_GLOBAL:
1450 return 1;
1451
1452 case CONTINUE_LOOP:
1453 return 0;
1454 case SETUP_LOOP:
1455 return 0;
1456 case SETUP_EXCEPT:
1457 case SETUP_FINALLY:
1458 return 3; /* actually pushed by an exception */
1459
1460 case LOAD_FAST:
1461 return 1;
1462 case STORE_FAST:
1463 return -1;
1464 case DELETE_FAST:
1465 return 0;
1466
1467 case RAISE_VARARGS:
1468 return -oparg;
1469#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1470 case CALL_FUNCTION:
1471 return -NARGS(oparg);
1472 case CALL_FUNCTION_VAR:
1473 case CALL_FUNCTION_KW:
1474 return -NARGS(oparg)-1;
1475 case CALL_FUNCTION_VAR_KW:
1476 return -NARGS(oparg)-2;
1477#undef NARGS
1478 case MAKE_FUNCTION:
1479 return -oparg;
1480 case BUILD_SLICE:
1481 if (oparg == 3)
1482 return -2;
1483 else
1484 return -1;
1485
1486 case MAKE_CLOSURE:
1487 return -oparg;
1488 case LOAD_CLOSURE:
1489 return 1;
1490 case LOAD_DEREF:
1491 return 1;
1492 case STORE_DEREF:
1493 return -1;
1494 default:
1495 fprintf(stderr, "opcode = %d\n", opcode);
1496 Py_FatalError("opcode_stack_effect()");
1497
1498 }
1499 return 0; /* not reachable */
1500}
1501
1502/* Add an opcode with no argument.
1503 Returns 0 on failure, 1 on success.
1504*/
1505
1506static int
1507compiler_addop(struct compiler *c, int opcode)
1508{
1509 basicblock *b;
1510 struct instr *i;
1511 int off;
1512 off = compiler_next_instr(c, c->u->u_curblock);
1513 if (off < 0)
1514 return 0;
1515 b = c->u->u_curblock;
1516 i = &b->b_instr[off];
1517 i->i_opcode = opcode;
1518 i->i_hasarg = 0;
1519 if (opcode == RETURN_VALUE)
1520 b->b_return = 1;
1521 compiler_set_lineno(c, off);
1522 return 1;
1523}
1524
1525static int
1526compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1527{
1528 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001529 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001531 /* necessary to make sure types aren't coerced (e.g., int and long) */
1532 t = PyTuple_Pack(2, o, o->ob_type);
1533 if (t == NULL)
1534 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535
1536 v = PyDict_GetItem(dict, t);
1537 if (!v) {
1538 arg = PyDict_Size(dict);
1539 v = PyInt_FromLong(arg);
1540 if (!v) {
1541 Py_DECREF(t);
1542 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001543 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001544 if (PyDict_SetItem(dict, t, v) < 0) {
1545 Py_DECREF(t);
1546 Py_DECREF(v);
1547 return -1;
1548 }
1549 Py_DECREF(v);
1550 }
1551 else
1552 arg = PyInt_AsLong(v);
1553 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001554 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555}
1556
1557static int
1558compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1559 PyObject *o)
1560{
1561 int arg = compiler_add_o(c, dict, o);
1562 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001563 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564 return compiler_addop_i(c, opcode, arg);
1565}
1566
1567static int
1568compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001569 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570{
1571 int arg;
1572 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1573 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001574 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001575 arg = compiler_add_o(c, dict, mangled);
1576 Py_DECREF(mangled);
1577 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001578 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001579 return compiler_addop_i(c, opcode, arg);
1580}
1581
1582/* Add an opcode with an integer argument.
1583 Returns 0 on failure, 1 on success.
1584*/
1585
1586static int
1587compiler_addop_i(struct compiler *c, int opcode, int oparg)
1588{
1589 struct instr *i;
1590 int off;
1591 off = compiler_next_instr(c, c->u->u_curblock);
1592 if (off < 0)
1593 return 0;
1594 i = &c->u->u_curblock->b_instr[off];
1595 i->i_opcode = opcode;
1596 i->i_oparg = oparg;
1597 i->i_hasarg = 1;
1598 compiler_set_lineno(c, off);
1599 return 1;
1600}
1601
1602static int
1603compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1604{
1605 struct instr *i;
1606 int off;
1607
1608 assert(b != NULL);
1609 off = compiler_next_instr(c, c->u->u_curblock);
1610 if (off < 0)
1611 return 0;
1612 compiler_set_lineno(c, off);
1613 i = &c->u->u_curblock->b_instr[off];
1614 i->i_opcode = opcode;
1615 i->i_target = b;
1616 i->i_hasarg = 1;
1617 if (absolute)
1618 i->i_jabs = 1;
1619 else
1620 i->i_jrel = 1;
1621 return 1;
1622}
1623
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001624/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1625 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001626 it as the current block. NEXT_BLOCK() also creates an implicit jump
1627 from the current block to the new block.
1628*/
1629
1630/* XXX The returns inside these macros make it impossible to decref
1631 objects created in the local function.
1632*/
1633
1634
1635#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001636 if (compiler_use_new_block((C)) == NULL) \
1637 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638}
1639
1640#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001641 if (compiler_next_block((C)) == NULL) \
1642 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643}
1644
1645#define ADDOP(C, OP) { \
1646 if (!compiler_addop((C), (OP))) \
1647 return 0; \
1648}
1649
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001650#define ADDOP_IN_SCOPE(C, OP) { \
1651 if (!compiler_addop((C), (OP))) { \
1652 compiler_exit_scope(c); \
1653 return 0; \
1654 } \
1655}
1656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001657#define ADDOP_O(C, OP, O, TYPE) { \
1658 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1659 return 0; \
1660}
1661
1662#define ADDOP_NAME(C, OP, O, TYPE) { \
1663 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1664 return 0; \
1665}
1666
1667#define ADDOP_I(C, OP, O) { \
1668 if (!compiler_addop_i((C), (OP), (O))) \
1669 return 0; \
1670}
1671
1672#define ADDOP_JABS(C, OP, O) { \
1673 if (!compiler_addop_j((C), (OP), (O), 1)) \
1674 return 0; \
1675}
1676
1677#define ADDOP_JREL(C, OP, O) { \
1678 if (!compiler_addop_j((C), (OP), (O), 0)) \
1679 return 0; \
1680}
1681
1682/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1683 the ASDL name to synthesize the name of the C type and the visit function.
1684*/
1685
1686#define VISIT(C, TYPE, V) {\
1687 if (!compiler_visit_ ## TYPE((C), (V))) \
1688 return 0; \
1689}
1690
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001691#define VISIT_IN_SCOPE(C, TYPE, V) {\
1692 if (!compiler_visit_ ## TYPE((C), (V))) { \
1693 compiler_exit_scope(c); \
1694 return 0; \
1695 } \
1696}
1697
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698#define VISIT_SLICE(C, V, CTX) {\
1699 if (!compiler_visit_slice((C), (V), (CTX))) \
1700 return 0; \
1701}
1702
1703#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001704 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001706 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1707 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708 if (!compiler_visit_ ## TYPE((C), elt)) \
1709 return 0; \
1710 } \
1711}
1712
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001713#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001714 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001715 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001716 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1717 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001718 if (!compiler_visit_ ## TYPE((C), elt)) { \
1719 compiler_exit_scope(c); \
1720 return 0; \
1721 } \
1722 } \
1723}
1724
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725static int
1726compiler_isdocstring(stmt_ty s)
1727{
1728 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001729 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001730 return s->v.Expr.value->kind == Str_kind;
1731}
1732
1733/* Compile a sequence of statements, checking for a docstring. */
1734
1735static int
1736compiler_body(struct compiler *c, asdl_seq *stmts)
1737{
1738 int i = 0;
1739 stmt_ty st;
1740
1741 if (!asdl_seq_LEN(stmts))
1742 return 1;
1743 st = asdl_seq_GET(stmts, 0);
1744 if (compiler_isdocstring(st)) {
1745 i = 1;
1746 VISIT(c, expr, st->v.Expr.value);
1747 if (!compiler_nameop(c, __doc__, Store))
1748 return 0;
1749 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001750 for (; i < asdl_seq_LEN(stmts); i++)
1751 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752 return 1;
1753}
1754
1755static PyCodeObject *
1756compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001757{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001758 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001759 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760 static PyObject *module;
1761 if (!module) {
1762 module = PyString_FromString("<module>");
1763 if (!module)
1764 return NULL;
1765 }
1766 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001767 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768 switch (mod->kind) {
1769 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001770 if (!compiler_body(c, mod->v.Module.body)) {
1771 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001773 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 break;
1775 case Interactive_kind:
1776 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001777 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778 break;
1779 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001780 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001781 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 break;
1783 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001784 PyErr_SetString(PyExc_SystemError,
1785 "suite should not be possible");
1786 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001787 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001788 PyErr_Format(PyExc_SystemError,
1789 "module kind %d should not be possible",
1790 mod->kind);
1791 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001792 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793 co = assemble(c, addNone);
1794 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001795 return co;
1796}
1797
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798/* The test for LOCAL must come before the test for FREE in order to
1799 handle classes where name is both local and free. The local var is
1800 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001801*/
1802
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803static int
1804get_ref_type(struct compiler *c, PyObject *name)
1805{
1806 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001807 if (scope == 0) {
1808 char buf[350];
1809 PyOS_snprintf(buf, sizeof(buf),
1810 "unknown scope for %.100s in %.100s(%s) in %s\n"
1811 "symbols: %s\nlocals: %s\nglobals: %s\n",
1812 PyString_AS_STRING(name),
1813 PyString_AS_STRING(c->u->u_name),
1814 PyObject_REPR(c->u->u_ste->ste_id),
1815 c->c_filename,
1816 PyObject_REPR(c->u->u_ste->ste_symbols),
1817 PyObject_REPR(c->u->u_varnames),
1818 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001820 Py_FatalError(buf);
1821 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001822
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001823 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824}
1825
1826static int
1827compiler_lookup_arg(PyObject *dict, PyObject *name)
1828{
1829 PyObject *k, *v;
1830 k = Py_BuildValue("(OO)", name, name->ob_type);
1831 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001832 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001834 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001836 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837 return PyInt_AS_LONG(v);
1838}
1839
1840static int
1841compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1842{
1843 int i, free = PyCode_GetNumFree(co);
1844 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001845 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1846 ADDOP_I(c, MAKE_FUNCTION, args);
1847 return 1;
1848 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 for (i = 0; i < free; ++i) {
1850 /* Bypass com_addop_varname because it will generate
1851 LOAD_DEREF but LOAD_CLOSURE is needed.
1852 */
1853 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1854 int arg, reftype;
1855
1856 /* Special case: If a class contains a method with a
1857 free variable that has the same name as a method,
1858 the name will be considered free *and* local in the
1859 class. It should be handled by the closure, as
1860 well as by the normal name loookup logic.
1861 */
1862 reftype = get_ref_type(c, name);
1863 if (reftype == CELL)
1864 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1865 else /* (reftype == FREE) */
1866 arg = compiler_lookup_arg(c->u->u_freevars, name);
1867 if (arg == -1) {
1868 printf("lookup %s in %s %d %d\n"
1869 "freevars of %s: %s\n",
1870 PyObject_REPR(name),
1871 PyString_AS_STRING(c->u->u_name),
1872 reftype, arg,
1873 PyString_AS_STRING(co->co_name),
1874 PyObject_REPR(co->co_freevars));
1875 Py_FatalError("compiler_make_closure()");
1876 }
1877 ADDOP_I(c, LOAD_CLOSURE, arg);
1878 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001879 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001880 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001881 ADDOP_I(c, MAKE_CLOSURE, args);
1882 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883}
1884
1885static int
1886compiler_decorators(struct compiler *c, asdl_seq* decos)
1887{
1888 int i;
1889
1890 if (!decos)
1891 return 1;
1892
1893 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1894 VISIT(c, expr, asdl_seq_GET(decos, i));
1895 }
1896 return 1;
1897}
1898
1899static int
1900compiler_arguments(struct compiler *c, arguments_ty args)
1901{
1902 int i;
1903 int n = asdl_seq_LEN(args->args);
1904 /* Correctly handle nested argument lists */
1905 for (i = 0; i < n; i++) {
1906 expr_ty arg = asdl_seq_GET(args->args, i);
1907 if (arg->kind == Tuple_kind) {
1908 PyObject *id = PyString_FromFormat(".%d", i);
1909 if (id == NULL) {
1910 return 0;
1911 }
1912 if (!compiler_nameop(c, id, Load)) {
1913 Py_DECREF(id);
1914 return 0;
1915 }
1916 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001917 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 }
1919 }
1920 return 1;
1921}
1922
1923static int
1924compiler_function(struct compiler *c, stmt_ty s)
1925{
1926 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001927 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928 arguments_ty args = s->v.FunctionDef.args;
1929 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001930 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931 int i, n, docstring;
1932
1933 assert(s->kind == FunctionDef_kind);
1934
1935 if (!compiler_decorators(c, decos))
1936 return 0;
1937 if (args->defaults)
1938 VISIT_SEQ(c, expr, args->defaults);
1939 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1940 s->lineno))
1941 return 0;
1942
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001943 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1944 docstring = compiler_isdocstring(st);
1945 if (docstring)
1946 first_const = st->v.Expr.value->v.Str.s;
1947 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001948 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001949 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001950 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001952 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953 compiler_arguments(c, args);
1954
1955 c->u->u_argcount = asdl_seq_LEN(args->args);
1956 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001957 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 for (i = docstring; i < n; i++) {
1959 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1960 if (i == 0 && s2->kind == Expr_kind &&
1961 s2->v.Expr.value->kind == Str_kind)
1962 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001963 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964 }
1965 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001966 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967 if (co == NULL)
1968 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001969
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001970 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001971 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
1973 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1974 ADDOP_I(c, CALL_FUNCTION, 1);
1975 }
1976
1977 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1978}
1979
1980static int
1981compiler_class(struct compiler *c, stmt_ty s)
1982{
1983 int n;
1984 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001985 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001986 /* push class name on stack, needed by BUILD_CLASS */
1987 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1988 /* push the tuple of base classes on the stack */
1989 n = asdl_seq_LEN(s->v.ClassDef.bases);
1990 if (n > 0)
1991 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1992 ADDOP_I(c, BUILD_TUPLE, n);
1993 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1994 s->lineno))
1995 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001996 c->u->u_private = s->v.ClassDef.name;
1997 Py_INCREF(c->u->u_private);
1998 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 if (!str || !compiler_nameop(c, str, Load)) {
2000 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002001 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002003 }
2004
2005 Py_DECREF(str);
2006 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 if (!str || !compiler_nameop(c, str, Store)) {
2008 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002009 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002011 }
2012 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002014 if (!compiler_body(c, s->v.ClassDef.body)) {
2015 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002017 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002018
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002019 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2020 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 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, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002027 Py_DECREF(co);
2028
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029 ADDOP_I(c, CALL_FUNCTION, 0);
2030 ADDOP(c, BUILD_CLASS);
2031 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2032 return 0;
2033 return 1;
2034}
2035
2036static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002037compiler_ifexp(struct compiler *c, expr_ty e)
2038{
2039 basicblock *end, *next;
2040
2041 assert(e->kind == IfExp_kind);
2042 end = compiler_new_block(c);
2043 if (end == NULL)
2044 return 0;
2045 next = compiler_new_block(c);
2046 if (next == NULL)
2047 return 0;
2048 VISIT(c, expr, e->v.IfExp.test);
2049 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2050 ADDOP(c, POP_TOP);
2051 VISIT(c, expr, e->v.IfExp.body);
2052 ADDOP_JREL(c, JUMP_FORWARD, end);
2053 compiler_use_next_block(c, next);
2054 ADDOP(c, POP_TOP);
2055 VISIT(c, expr, e->v.IfExp.orelse);
2056 compiler_use_next_block(c, end);
2057 return 1;
2058}
2059
2060static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002061compiler_lambda(struct compiler *c, expr_ty e)
2062{
2063 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002064 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065 arguments_ty args = e->v.Lambda.args;
2066 assert(e->kind == Lambda_kind);
2067
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002068 if (!name) {
2069 name = PyString_InternFromString("<lambda>");
2070 if (!name)
2071 return 0;
2072 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002073
2074 if (args->defaults)
2075 VISIT_SEQ(c, expr, args->defaults);
2076 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2077 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002078
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002079 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 compiler_arguments(c, args);
2081
2082 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002083 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2084 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002086 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087 if (co == NULL)
2088 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002090 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002091 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092
2093 return 1;
2094}
2095
2096static int
2097compiler_print(struct compiler *c, stmt_ty s)
2098{
2099 int i, n;
2100 bool dest;
2101
2102 assert(s->kind == Print_kind);
2103 n = asdl_seq_LEN(s->v.Print.values);
2104 dest = false;
2105 if (s->v.Print.dest) {
2106 VISIT(c, expr, s->v.Print.dest);
2107 dest = true;
2108 }
2109 for (i = 0; i < n; i++) {
2110 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2111 if (dest) {
2112 ADDOP(c, DUP_TOP);
2113 VISIT(c, expr, e);
2114 ADDOP(c, ROT_TWO);
2115 ADDOP(c, PRINT_ITEM_TO);
2116 }
2117 else {
2118 VISIT(c, expr, e);
2119 ADDOP(c, PRINT_ITEM);
2120 }
2121 }
2122 if (s->v.Print.nl) {
2123 if (dest)
2124 ADDOP(c, PRINT_NEWLINE_TO)
2125 else
2126 ADDOP(c, PRINT_NEWLINE)
2127 }
2128 else if (dest)
2129 ADDOP(c, POP_TOP);
2130 return 1;
2131}
2132
2133static int
2134compiler_if(struct compiler *c, stmt_ty s)
2135{
2136 basicblock *end, *next;
2137
2138 assert(s->kind == If_kind);
2139 end = compiler_new_block(c);
2140 if (end == NULL)
2141 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002142 next = compiler_new_block(c);
2143 if (next == NULL)
2144 return 0;
2145 VISIT(c, expr, s->v.If.test);
2146 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2147 ADDOP(c, POP_TOP);
2148 VISIT_SEQ(c, stmt, s->v.If.body);
2149 ADDOP_JREL(c, JUMP_FORWARD, end);
2150 compiler_use_next_block(c, next);
2151 ADDOP(c, POP_TOP);
2152 if (s->v.If.orelse)
2153 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 compiler_use_next_block(c, end);
2155 return 1;
2156}
2157
2158static int
2159compiler_for(struct compiler *c, stmt_ty s)
2160{
2161 basicblock *start, *cleanup, *end;
2162
2163 start = compiler_new_block(c);
2164 cleanup = compiler_new_block(c);
2165 end = compiler_new_block(c);
2166 if (start == NULL || end == NULL || cleanup == NULL)
2167 return 0;
2168 ADDOP_JREL(c, SETUP_LOOP, end);
2169 if (!compiler_push_fblock(c, LOOP, start))
2170 return 0;
2171 VISIT(c, expr, s->v.For.iter);
2172 ADDOP(c, GET_ITER);
2173 compiler_use_next_block(c, start);
2174 ADDOP_JREL(c, FOR_ITER, cleanup);
2175 VISIT(c, expr, s->v.For.target);
2176 VISIT_SEQ(c, stmt, s->v.For.body);
2177 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2178 compiler_use_next_block(c, cleanup);
2179 ADDOP(c, POP_BLOCK);
2180 compiler_pop_fblock(c, LOOP, start);
2181 VISIT_SEQ(c, stmt, s->v.For.orelse);
2182 compiler_use_next_block(c, end);
2183 return 1;
2184}
2185
2186static int
2187compiler_while(struct compiler *c, stmt_ty s)
2188{
2189 basicblock *loop, *orelse, *end, *anchor = NULL;
2190 int constant = expr_constant(s->v.While.test);
2191
2192 if (constant == 0)
2193 return 1;
2194 loop = compiler_new_block(c);
2195 end = compiler_new_block(c);
2196 if (constant == -1) {
2197 anchor = compiler_new_block(c);
2198 if (anchor == NULL)
2199 return 0;
2200 }
2201 if (loop == NULL || end == NULL)
2202 return 0;
2203 if (s->v.While.orelse) {
2204 orelse = compiler_new_block(c);
2205 if (orelse == NULL)
2206 return 0;
2207 }
2208 else
2209 orelse = NULL;
2210
2211 ADDOP_JREL(c, SETUP_LOOP, end);
2212 compiler_use_next_block(c, loop);
2213 if (!compiler_push_fblock(c, LOOP, loop))
2214 return 0;
2215 if (constant == -1) {
2216 VISIT(c, expr, s->v.While.test);
2217 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2218 ADDOP(c, POP_TOP);
2219 }
2220 VISIT_SEQ(c, stmt, s->v.While.body);
2221 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2222
2223 /* XXX should the two POP instructions be in a separate block
2224 if there is no else clause ?
2225 */
2226
2227 if (constant == -1) {
2228 compiler_use_next_block(c, anchor);
2229 ADDOP(c, POP_TOP);
2230 ADDOP(c, POP_BLOCK);
2231 }
2232 compiler_pop_fblock(c, LOOP, loop);
2233 if (orelse != NULL)
2234 VISIT_SEQ(c, stmt, s->v.While.orelse);
2235 compiler_use_next_block(c, end);
2236
2237 return 1;
2238}
2239
2240static int
2241compiler_continue(struct compiler *c)
2242{
2243 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2244 int i;
2245
2246 if (!c->u->u_nfblocks)
2247 return compiler_error(c, LOOP_ERROR_MSG);
2248 i = c->u->u_nfblocks - 1;
2249 switch (c->u->u_fblock[i].fb_type) {
2250 case LOOP:
2251 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2252 break;
2253 case EXCEPT:
2254 case FINALLY_TRY:
2255 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2256 ;
2257 if (i == -1)
2258 return compiler_error(c, LOOP_ERROR_MSG);
2259 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2260 break;
2261 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002262 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263 "'continue' not supported inside 'finally' clause");
2264 }
2265
2266 return 1;
2267}
2268
2269/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2270
2271 SETUP_FINALLY L
2272 <code for body>
2273 POP_BLOCK
2274 LOAD_CONST <None>
2275 L: <code for finalbody>
2276 END_FINALLY
2277
2278 The special instructions use the block stack. Each block
2279 stack entry contains the instruction that created it (here
2280 SETUP_FINALLY), the level of the value stack at the time the
2281 block stack entry was created, and a label (here L).
2282
2283 SETUP_FINALLY:
2284 Pushes the current value stack level and the label
2285 onto the block stack.
2286 POP_BLOCK:
2287 Pops en entry from the block stack, and pops the value
2288 stack until its level is the same as indicated on the
2289 block stack. (The label is ignored.)
2290 END_FINALLY:
2291 Pops a variable number of entries from the *value* stack
2292 and re-raises the exception they specify. The number of
2293 entries popped depends on the (pseudo) exception type.
2294
2295 The block stack is unwound when an exception is raised:
2296 when a SETUP_FINALLY entry is found, the exception is pushed
2297 onto the value stack (and the exception condition is cleared),
2298 and the interpreter jumps to the label gotten from the block
2299 stack.
2300*/
2301
2302static int
2303compiler_try_finally(struct compiler *c, stmt_ty s)
2304{
2305 basicblock *body, *end;
2306 body = compiler_new_block(c);
2307 end = compiler_new_block(c);
2308 if (body == NULL || end == NULL)
2309 return 0;
2310
2311 ADDOP_JREL(c, SETUP_FINALLY, end);
2312 compiler_use_next_block(c, body);
2313 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2314 return 0;
2315 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2316 ADDOP(c, POP_BLOCK);
2317 compiler_pop_fblock(c, FINALLY_TRY, body);
2318
2319 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2320 compiler_use_next_block(c, end);
2321 if (!compiler_push_fblock(c, FINALLY_END, end))
2322 return 0;
2323 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2324 ADDOP(c, END_FINALLY);
2325 compiler_pop_fblock(c, FINALLY_END, end);
2326
2327 return 1;
2328}
2329
2330/*
2331 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2332 (The contents of the value stack is shown in [], with the top
2333 at the right; 'tb' is trace-back info, 'val' the exception's
2334 associated value, and 'exc' the exception.)
2335
2336 Value stack Label Instruction Argument
2337 [] SETUP_EXCEPT L1
2338 [] <code for S>
2339 [] POP_BLOCK
2340 [] JUMP_FORWARD L0
2341
2342 [tb, val, exc] L1: DUP )
2343 [tb, val, exc, exc] <evaluate E1> )
2344 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2345 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2346 [tb, val, exc, 1] POP )
2347 [tb, val, exc] POP
2348 [tb, val] <assign to V1> (or POP if no V1)
2349 [tb] POP
2350 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002351 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002352
2353 [tb, val, exc, 0] L2: POP
2354 [tb, val, exc] DUP
2355 .............................etc.......................
2356
2357 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002358 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359
2360 [] L0: <next statement>
2361
2362 Of course, parts are not generated if Vi or Ei is not present.
2363*/
2364static int
2365compiler_try_except(struct compiler *c, stmt_ty s)
2366{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002367 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368 int i, n;
2369
2370 body = compiler_new_block(c);
2371 except = compiler_new_block(c);
2372 orelse = compiler_new_block(c);
2373 end = compiler_new_block(c);
2374 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2375 return 0;
2376 ADDOP_JREL(c, SETUP_EXCEPT, except);
2377 compiler_use_next_block(c, body);
2378 if (!compiler_push_fblock(c, EXCEPT, body))
2379 return 0;
2380 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2381 ADDOP(c, POP_BLOCK);
2382 compiler_pop_fblock(c, EXCEPT, body);
2383 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2384 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2385 compiler_use_next_block(c, except);
2386 for (i = 0; i < n; i++) {
2387 excepthandler_ty handler = asdl_seq_GET(
2388 s->v.TryExcept.handlers, i);
2389 if (!handler->type && i < n-1)
2390 return compiler_error(c, "default 'except:' must be last");
2391 except = compiler_new_block(c);
2392 if (except == NULL)
2393 return 0;
2394 if (handler->type) {
2395 ADDOP(c, DUP_TOP);
2396 VISIT(c, expr, handler->type);
2397 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2398 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2399 ADDOP(c, POP_TOP);
2400 }
2401 ADDOP(c, POP_TOP);
2402 if (handler->name) {
2403 VISIT(c, expr, handler->name);
2404 }
2405 else {
2406 ADDOP(c, POP_TOP);
2407 }
2408 ADDOP(c, POP_TOP);
2409 VISIT_SEQ(c, stmt, handler->body);
2410 ADDOP_JREL(c, JUMP_FORWARD, end);
2411 compiler_use_next_block(c, except);
2412 if (handler->type)
2413 ADDOP(c, POP_TOP);
2414 }
2415 ADDOP(c, END_FINALLY);
2416 compiler_use_next_block(c, orelse);
2417 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2418 compiler_use_next_block(c, end);
2419 return 1;
2420}
2421
2422static int
2423compiler_import_as(struct compiler *c, identifier name, identifier asname)
2424{
2425 /* The IMPORT_NAME opcode was already generated. This function
2426 merely needs to bind the result to a name.
2427
2428 If there is a dot in name, we need to split it and emit a
2429 LOAD_ATTR for each name.
2430 */
2431 const char *src = PyString_AS_STRING(name);
2432 const char *dot = strchr(src, '.');
2433 if (dot) {
2434 /* Consume the base module name to get the first attribute */
2435 src = dot + 1;
2436 while (dot) {
2437 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002438 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002440 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002442 if (!attr)
2443 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002445 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002446 src = dot + 1;
2447 }
2448 }
2449 return compiler_nameop(c, asname, Store);
2450}
2451
2452static int
2453compiler_import(struct compiler *c, stmt_ty s)
2454{
2455 /* The Import node stores a module name like a.b.c as a single
2456 string. This is convenient for all cases except
2457 import a.b.c as d
2458 where we need to parse that string to extract the individual
2459 module names.
2460 XXX Perhaps change the representation to make this case simpler?
2461 */
2462 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002463
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 for (i = 0; i < n; i++) {
2465 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2466 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002467 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002469 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2470 level = PyInt_FromLong(0);
2471 else
2472 level = PyInt_FromLong(-1);
2473
2474 if (level == NULL)
2475 return 0;
2476
2477 ADDOP_O(c, LOAD_CONST, level, consts);
2478 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2480 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2481
2482 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002483 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002484 if (!r)
2485 return r;
2486 }
2487 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002488 identifier tmp = alias->name;
2489 const char *base = PyString_AS_STRING(alias->name);
2490 char *dot = strchr(base, '.');
2491 if (dot)
2492 tmp = PyString_FromStringAndSize(base,
2493 dot - base);
2494 r = compiler_nameop(c, tmp, Store);
2495 if (dot) {
2496 Py_DECREF(tmp);
2497 }
2498 if (!r)
2499 return r;
2500 }
2501 }
2502 return 1;
2503}
2504
2505static int
2506compiler_from_import(struct compiler *c, stmt_ty s)
2507{
2508 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509
2510 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002511 PyObject *level;
2512
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002513 if (!names)
2514 return 0;
2515
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002516 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2517 !(c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2518 level = PyInt_FromLong(-1);
2519 else
2520 level = PyInt_FromLong(s->v.ImportFrom.level);
2521
2522 if (!level) {
2523 Py_DECREF(names);
2524 return 0;
2525 }
2526
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002527 /* build up the names */
2528 for (i = 0; i < n; i++) {
2529 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2530 Py_INCREF(alias->name);
2531 PyTuple_SET_ITEM(names, i, alias->name);
2532 }
2533
2534 if (s->lineno > c->c_future->ff_lineno) {
2535 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2536 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002537 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538 Py_DECREF(names);
2539 return compiler_error(c,
2540 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002541 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542
2543 }
2544 }
2545
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002546 ADDOP_O(c, LOAD_CONST, level, consts);
2547 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002549 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002550 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2551 for (i = 0; i < n; i++) {
2552 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2553 identifier store_name;
2554
2555 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2556 assert(n == 1);
2557 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002558 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002559 }
2560
2561 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2562 store_name = alias->name;
2563 if (alias->asname)
2564 store_name = alias->asname;
2565
2566 if (!compiler_nameop(c, store_name, Store)) {
2567 Py_DECREF(names);
2568 return 0;
2569 }
2570 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002571 /* remove imported module */
2572 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002573 return 1;
2574}
2575
2576static int
2577compiler_assert(struct compiler *c, stmt_ty s)
2578{
2579 static PyObject *assertion_error = NULL;
2580 basicblock *end;
2581
2582 if (Py_OptimizeFlag)
2583 return 1;
2584 if (assertion_error == NULL) {
2585 assertion_error = PyString_FromString("AssertionError");
2586 if (assertion_error == NULL)
2587 return 0;
2588 }
2589 VISIT(c, expr, s->v.Assert.test);
2590 end = compiler_new_block(c);
2591 if (end == NULL)
2592 return 0;
2593 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2594 ADDOP(c, POP_TOP);
2595 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2596 if (s->v.Assert.msg) {
2597 VISIT(c, expr, s->v.Assert.msg);
2598 ADDOP_I(c, RAISE_VARARGS, 2);
2599 }
2600 else {
2601 ADDOP_I(c, RAISE_VARARGS, 1);
2602 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002603 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604 ADDOP(c, POP_TOP);
2605 return 1;
2606}
2607
2608static int
2609compiler_visit_stmt(struct compiler *c, stmt_ty s)
2610{
2611 int i, n;
2612
2613 c->u->u_lineno = s->lineno;
2614 c->u->u_lineno_set = false;
2615 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002616 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002618 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002620 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 if (c->u->u_ste->ste_type != FunctionBlock)
2622 return compiler_error(c, "'return' outside function");
2623 if (s->v.Return.value) {
2624 if (c->u->u_ste->ste_generator) {
2625 return compiler_error(c,
2626 "'return' with argument inside generator");
2627 }
2628 VISIT(c, expr, s->v.Return.value);
2629 }
2630 else
2631 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2632 ADDOP(c, RETURN_VALUE);
2633 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 VISIT_SEQ(c, expr, s->v.Delete.targets)
2636 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002637 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 n = asdl_seq_LEN(s->v.Assign.targets);
2639 VISIT(c, expr, s->v.Assign.value);
2640 for (i = 0; i < n; i++) {
2641 if (i < n - 1)
2642 ADDOP(c, DUP_TOP);
2643 VISIT(c, expr,
2644 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2645 }
2646 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 n = 0;
2659 if (s->v.Raise.type) {
2660 VISIT(c, expr, s->v.Raise.type);
2661 n++;
2662 if (s->v.Raise.inst) {
2663 VISIT(c, expr, s->v.Raise.inst);
2664 n++;
2665 if (s->v.Raise.tback) {
2666 VISIT(c, expr, s->v.Raise.tback);
2667 n++;
2668 }
2669 }
2670 }
2671 ADDOP_I(c, RAISE_VARARGS, n);
2672 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002679 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002681 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 VISIT(c, expr, s->v.Exec.body);
2685 if (s->v.Exec.globals) {
2686 VISIT(c, expr, s->v.Exec.globals);
2687 if (s->v.Exec.locals) {
2688 VISIT(c, expr, s->v.Exec.locals);
2689 } else {
2690 ADDOP(c, DUP_TOP);
2691 }
2692 } else {
2693 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2694 ADDOP(c, DUP_TOP);
2695 }
2696 ADDOP(c, EXEC_STMT);
2697 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002698 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701 VISIT(c, expr, s->v.Expr.value);
2702 if (c->c_interactive && c->c_nestlevel <= 1) {
2703 ADDOP(c, PRINT_EXPR);
2704 }
2705 else {
2706 ADDOP(c, POP_TOP);
2707 }
2708 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002709 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 if (!c->u->u_nfblocks)
2713 return compiler_error(c, "'break' outside loop");
2714 ADDOP(c, BREAK_LOOP);
2715 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 case With_kind:
2719 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002720 }
2721 return 1;
2722}
2723
2724static int
2725unaryop(unaryop_ty op)
2726{
2727 switch (op) {
2728 case Invert:
2729 return UNARY_INVERT;
2730 case Not:
2731 return UNARY_NOT;
2732 case UAdd:
2733 return UNARY_POSITIVE;
2734 case USub:
2735 return UNARY_NEGATIVE;
2736 }
2737 return 0;
2738}
2739
2740static int
2741binop(struct compiler *c, operator_ty op)
2742{
2743 switch (op) {
2744 case Add:
2745 return BINARY_ADD;
2746 case Sub:
2747 return BINARY_SUBTRACT;
2748 case Mult:
2749 return BINARY_MULTIPLY;
2750 case Div:
2751 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2752 return BINARY_TRUE_DIVIDE;
2753 else
2754 return BINARY_DIVIDE;
2755 case Mod:
2756 return BINARY_MODULO;
2757 case Pow:
2758 return BINARY_POWER;
2759 case LShift:
2760 return BINARY_LSHIFT;
2761 case RShift:
2762 return BINARY_RSHIFT;
2763 case BitOr:
2764 return BINARY_OR;
2765 case BitXor:
2766 return BINARY_XOR;
2767 case BitAnd:
2768 return BINARY_AND;
2769 case FloorDiv:
2770 return BINARY_FLOOR_DIVIDE;
2771 }
2772 return 0;
2773}
2774
2775static int
2776cmpop(cmpop_ty op)
2777{
2778 switch (op) {
2779 case Eq:
2780 return PyCmp_EQ;
2781 case NotEq:
2782 return PyCmp_NE;
2783 case Lt:
2784 return PyCmp_LT;
2785 case LtE:
2786 return PyCmp_LE;
2787 case Gt:
2788 return PyCmp_GT;
2789 case GtE:
2790 return PyCmp_GE;
2791 case Is:
2792 return PyCmp_IS;
2793 case IsNot:
2794 return PyCmp_IS_NOT;
2795 case In:
2796 return PyCmp_IN;
2797 case NotIn:
2798 return PyCmp_NOT_IN;
2799 }
2800 return PyCmp_BAD;
2801}
2802
2803static int
2804inplace_binop(struct compiler *c, operator_ty op)
2805{
2806 switch (op) {
2807 case Add:
2808 return INPLACE_ADD;
2809 case Sub:
2810 return INPLACE_SUBTRACT;
2811 case Mult:
2812 return INPLACE_MULTIPLY;
2813 case Div:
2814 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2815 return INPLACE_TRUE_DIVIDE;
2816 else
2817 return INPLACE_DIVIDE;
2818 case Mod:
2819 return INPLACE_MODULO;
2820 case Pow:
2821 return INPLACE_POWER;
2822 case LShift:
2823 return INPLACE_LSHIFT;
2824 case RShift:
2825 return INPLACE_RSHIFT;
2826 case BitOr:
2827 return INPLACE_OR;
2828 case BitXor:
2829 return INPLACE_XOR;
2830 case BitAnd:
2831 return INPLACE_AND;
2832 case FloorDiv:
2833 return INPLACE_FLOOR_DIVIDE;
2834 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002835 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002836 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837 return 0;
2838}
2839
2840static int
2841compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2842{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002843 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2845
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002846 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002847 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848 /* XXX AugStore isn't used anywhere! */
2849
2850 /* First check for assignment to __debug__. Param? */
2851 if ((ctx == Store || ctx == AugStore || ctx == Del)
2852 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2853 return compiler_error(c, "can not assign to __debug__");
2854 }
2855
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002856 mangled = _Py_Mangle(c->u->u_private, name);
2857 if (!mangled)
2858 return 0;
2859
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860 op = 0;
2861 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002862 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863 switch (scope) {
2864 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002865 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866 optype = OP_DEREF;
2867 break;
2868 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002869 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870 optype = OP_DEREF;
2871 break;
2872 case LOCAL:
2873 if (c->u->u_ste->ste_type == FunctionBlock)
2874 optype = OP_FAST;
2875 break;
2876 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002877 if (c->u->u_ste->ste_type == FunctionBlock &&
2878 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002879 optype = OP_GLOBAL;
2880 break;
2881 case GLOBAL_EXPLICIT:
2882 optype = OP_GLOBAL;
2883 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002884 default:
2885 /* scope can be 0 */
2886 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002887 }
2888
2889 /* XXX Leave assert here, but handle __doc__ and the like better */
2890 assert(scope || PyString_AS_STRING(name)[0] == '_');
2891
2892 switch (optype) {
2893 case OP_DEREF:
2894 switch (ctx) {
2895 case Load: op = LOAD_DEREF; break;
2896 case Store: op = STORE_DEREF; break;
2897 case AugLoad:
2898 case AugStore:
2899 break;
2900 case Del:
2901 PyErr_Format(PyExc_SyntaxError,
2902 "can not delete variable '%s' referenced "
2903 "in nested scope",
2904 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002905 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002908 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002909 PyErr_SetString(PyExc_SystemError,
2910 "param invalid for deref variable");
2911 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912 }
2913 break;
2914 case OP_FAST:
2915 switch (ctx) {
2916 case Load: op = LOAD_FAST; break;
2917 case Store: op = STORE_FAST; break;
2918 case Del: op = DELETE_FAST; break;
2919 case AugLoad:
2920 case AugStore:
2921 break;
2922 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002923 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002924 PyErr_SetString(PyExc_SystemError,
2925 "param invalid for local variable");
2926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002927 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002928 ADDOP_O(c, op, mangled, varnames);
2929 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930 return 1;
2931 case OP_GLOBAL:
2932 switch (ctx) {
2933 case Load: op = LOAD_GLOBAL; break;
2934 case Store: op = STORE_GLOBAL; break;
2935 case Del: op = DELETE_GLOBAL; break;
2936 case AugLoad:
2937 case AugStore:
2938 break;
2939 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002940 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002941 PyErr_SetString(PyExc_SystemError,
2942 "param invalid for global variable");
2943 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002944 }
2945 break;
2946 case OP_NAME:
2947 switch (ctx) {
2948 case Load: op = LOAD_NAME; break;
2949 case Store: op = STORE_NAME; break;
2950 case Del: op = DELETE_NAME; break;
2951 case AugLoad:
2952 case AugStore:
2953 break;
2954 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002955 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002956 PyErr_SetString(PyExc_SystemError,
2957 "param invalid for name variable");
2958 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 }
2960 break;
2961 }
2962
2963 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002964 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002965 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002966 if (arg < 0)
2967 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002968 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969}
2970
2971static int
2972compiler_boolop(struct compiler *c, expr_ty e)
2973{
2974 basicblock *end;
2975 int jumpi, i, n;
2976 asdl_seq *s;
2977
2978 assert(e->kind == BoolOp_kind);
2979 if (e->v.BoolOp.op == And)
2980 jumpi = JUMP_IF_FALSE;
2981 else
2982 jumpi = JUMP_IF_TRUE;
2983 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002984 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 return 0;
2986 s = e->v.BoolOp.values;
2987 n = asdl_seq_LEN(s) - 1;
2988 for (i = 0; i < n; ++i) {
2989 VISIT(c, expr, asdl_seq_GET(s, i));
2990 ADDOP_JREL(c, jumpi, end);
2991 ADDOP(c, POP_TOP)
2992 }
2993 VISIT(c, expr, asdl_seq_GET(s, n));
2994 compiler_use_next_block(c, end);
2995 return 1;
2996}
2997
2998static int
2999compiler_list(struct compiler *c, expr_ty e)
3000{
3001 int n = asdl_seq_LEN(e->v.List.elts);
3002 if (e->v.List.ctx == Store) {
3003 ADDOP_I(c, UNPACK_SEQUENCE, n);
3004 }
3005 VISIT_SEQ(c, expr, e->v.List.elts);
3006 if (e->v.List.ctx == Load) {
3007 ADDOP_I(c, BUILD_LIST, n);
3008 }
3009 return 1;
3010}
3011
3012static int
3013compiler_tuple(struct compiler *c, expr_ty e)
3014{
3015 int n = asdl_seq_LEN(e->v.Tuple.elts);
3016 if (e->v.Tuple.ctx == Store) {
3017 ADDOP_I(c, UNPACK_SEQUENCE, n);
3018 }
3019 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3020 if (e->v.Tuple.ctx == Load) {
3021 ADDOP_I(c, BUILD_TUPLE, n);
3022 }
3023 return 1;
3024}
3025
3026static int
3027compiler_compare(struct compiler *c, expr_ty e)
3028{
3029 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003030 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031
3032 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3033 VISIT(c, expr, e->v.Compare.left);
3034 n = asdl_seq_LEN(e->v.Compare.ops);
3035 assert(n > 0);
3036 if (n > 1) {
3037 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003038 if (cleanup == NULL)
3039 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003040 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3041 }
3042 for (i = 1; i < n; i++) {
3043 ADDOP(c, DUP_TOP);
3044 ADDOP(c, ROT_THREE);
3045 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3046 ADDOP_I(c, COMPARE_OP,
3047 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3048 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3049 NEXT_BLOCK(c);
3050 ADDOP(c, POP_TOP);
3051 if (i < (n - 1))
3052 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3053 }
3054 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3055 ADDOP_I(c, COMPARE_OP,
3056 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3057 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3058 if (n > 1) {
3059 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003060 if (end == NULL)
3061 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062 ADDOP_JREL(c, JUMP_FORWARD, end);
3063 compiler_use_next_block(c, cleanup);
3064 ADDOP(c, ROT_TWO);
3065 ADDOP(c, POP_TOP);
3066 compiler_use_next_block(c, end);
3067 }
3068 return 1;
3069}
3070
3071static int
3072compiler_call(struct compiler *c, expr_ty e)
3073{
3074 int n, code = 0;
3075
3076 VISIT(c, expr, e->v.Call.func);
3077 n = asdl_seq_LEN(e->v.Call.args);
3078 VISIT_SEQ(c, expr, e->v.Call.args);
3079 if (e->v.Call.keywords) {
3080 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3081 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3082 }
3083 if (e->v.Call.starargs) {
3084 VISIT(c, expr, e->v.Call.starargs);
3085 code |= 1;
3086 }
3087 if (e->v.Call.kwargs) {
3088 VISIT(c, expr, e->v.Call.kwargs);
3089 code |= 2;
3090 }
3091 switch (code) {
3092 case 0:
3093 ADDOP_I(c, CALL_FUNCTION, n);
3094 break;
3095 case 1:
3096 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3097 break;
3098 case 2:
3099 ADDOP_I(c, CALL_FUNCTION_KW, n);
3100 break;
3101 case 3:
3102 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3103 break;
3104 }
3105 return 1;
3106}
3107
3108static int
3109compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003110 asdl_seq *generators, int gen_index,
3111 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003112{
3113 /* generate code for the iterator, then each of the ifs,
3114 and then write to the element */
3115
3116 comprehension_ty l;
3117 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003118 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119
3120 start = compiler_new_block(c);
3121 skip = compiler_new_block(c);
3122 if_cleanup = compiler_new_block(c);
3123 anchor = compiler_new_block(c);
3124
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003125 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3126 anchor == NULL)
3127 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128
3129 l = asdl_seq_GET(generators, gen_index);
3130 VISIT(c, expr, l->iter);
3131 ADDOP(c, GET_ITER);
3132 compiler_use_next_block(c, start);
3133 ADDOP_JREL(c, FOR_ITER, anchor);
3134 NEXT_BLOCK(c);
3135 VISIT(c, expr, l->target);
3136
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138 n = asdl_seq_LEN(l->ifs);
3139 for (i = 0; i < n; i++) {
3140 expr_ty e = asdl_seq_GET(l->ifs, i);
3141 VISIT(c, expr, e);
3142 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3143 NEXT_BLOCK(c);
3144 ADDOP(c, POP_TOP);
3145 }
3146
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 if (++gen_index < asdl_seq_LEN(generators))
3148 if (!compiler_listcomp_generator(c, tmpname,
3149 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003150 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003152 /* only append after the last for generator */
3153 if (gen_index >= asdl_seq_LEN(generators)) {
3154 if (!compiler_nameop(c, tmpname, Load))
3155 return 0;
3156 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003157 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158
3159 compiler_use_next_block(c, skip);
3160 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 for (i = 0; i < n; i++) {
3162 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003163 if (i == 0)
3164 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 ADDOP(c, POP_TOP);
3166 }
3167 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3168 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003171 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172 return 0;
3173
3174 return 1;
3175}
3176
3177static int
3178compiler_listcomp(struct compiler *c, expr_ty e)
3179{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 static identifier append;
3183 asdl_seq *generators = e->v.ListComp.generators;
3184
3185 assert(e->kind == ListComp_kind);
3186 if (!append) {
3187 append = PyString_InternFromString("append");
3188 if (!append)
3189 return 0;
3190 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003191 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192 if (!tmp)
3193 return 0;
3194 ADDOP_I(c, BUILD_LIST, 0);
3195 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3198 e->v.ListComp.elt);
3199 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003200 return rc;
3201}
3202
3203static int
3204compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003205 asdl_seq *generators, int gen_index,
3206 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003207{
3208 /* generate code for the iterator, then each of the ifs,
3209 and then write to the element */
3210
3211 comprehension_ty ge;
3212 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003213 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
3215 start = compiler_new_block(c);
3216 skip = compiler_new_block(c);
3217 if_cleanup = compiler_new_block(c);
3218 anchor = compiler_new_block(c);
3219 end = compiler_new_block(c);
3220
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 anchor == NULL || end == NULL)
3223 return 0;
3224
3225 ge = asdl_seq_GET(generators, gen_index);
3226 ADDOP_JREL(c, SETUP_LOOP, end);
3227 if (!compiler_push_fblock(c, LOOP, start))
3228 return 0;
3229
3230 if (gen_index == 0) {
3231 /* Receive outermost iter as an implicit argument */
3232 c->u->u_argcount = 1;
3233 ADDOP_I(c, LOAD_FAST, 0);
3234 }
3235 else {
3236 /* Sub-iter - calculate on the fly */
3237 VISIT(c, expr, ge->iter);
3238 ADDOP(c, GET_ITER);
3239 }
3240 compiler_use_next_block(c, start);
3241 ADDOP_JREL(c, FOR_ITER, anchor);
3242 NEXT_BLOCK(c);
3243 VISIT(c, expr, ge->target);
3244
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003245 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246 n = asdl_seq_LEN(ge->ifs);
3247 for (i = 0; i < n; i++) {
3248 expr_ty e = asdl_seq_GET(ge->ifs, i);
3249 VISIT(c, expr, e);
3250 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3251 NEXT_BLOCK(c);
3252 ADDOP(c, POP_TOP);
3253 }
3254
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003255 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003256 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3257 return 0;
3258
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259 /* only append after the last 'for' generator */
3260 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261 VISIT(c, expr, elt);
3262 ADDOP(c, YIELD_VALUE);
3263 ADDOP(c, POP_TOP);
3264
3265 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 for (i = 0; i < n; i++) {
3268 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003269 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003270 compiler_use_next_block(c, if_cleanup);
3271
3272 ADDOP(c, POP_TOP);
3273 }
3274 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3275 compiler_use_next_block(c, anchor);
3276 ADDOP(c, POP_BLOCK);
3277 compiler_pop_fblock(c, LOOP, start);
3278 compiler_use_next_block(c, end);
3279
3280 return 1;
3281}
3282
3283static int
3284compiler_genexp(struct compiler *c, expr_ty e)
3285{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003286 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 PyCodeObject *co;
3288 expr_ty outermost_iter = ((comprehension_ty)
3289 (asdl_seq_GET(e->v.GeneratorExp.generators,
3290 0)))->iter;
3291
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003292 if (!name) {
3293 name = PyString_FromString("<genexpr>");
3294 if (!name)
3295 return 0;
3296 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297
3298 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3299 return 0;
3300 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3301 e->v.GeneratorExp.elt);
3302 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003303 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304 if (co == NULL)
3305 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003307 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003308 Py_DECREF(co);
3309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310 VISIT(c, expr, outermost_iter);
3311 ADDOP(c, GET_ITER);
3312 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
3314 return 1;
3315}
3316
3317static int
3318compiler_visit_keyword(struct compiler *c, keyword_ty k)
3319{
3320 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3321 VISIT(c, expr, k->value);
3322 return 1;
3323}
3324
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003325/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326 whether they are true or false.
3327
3328 Return values: 1 for true, 0 for false, -1 for non-constant.
3329 */
3330
3331static int
3332expr_constant(expr_ty e)
3333{
3334 switch (e->kind) {
3335 case Num_kind:
3336 return PyObject_IsTrue(e->v.Num.n);
3337 case Str_kind:
3338 return PyObject_IsTrue(e->v.Str.s);
3339 default:
3340 return -1;
3341 }
3342}
3343
Guido van Rossumc2e20742006-02-27 22:32:47 +00003344/*
3345 Implements the with statement from PEP 343.
3346
3347 The semantics outlined in that PEP are as follows:
3348
3349 with EXPR as VAR:
3350 BLOCK
3351
3352 It is implemented roughly as:
3353
3354 context = (EXPR).__context__()
3355 exit = context.__exit__ # not calling it
3356 value = context.__enter__()
3357 try:
3358 VAR = value # if VAR present in the syntax
3359 BLOCK
3360 finally:
3361 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003362 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003363 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003364 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003365 exit(*exc)
3366 */
3367static int
3368compiler_with(struct compiler *c, stmt_ty s)
3369{
3370 static identifier context_attr, enter_attr, exit_attr;
3371 basicblock *block, *finally;
3372 identifier tmpexit, tmpvalue = NULL;
3373
3374 assert(s->kind == With_kind);
3375
3376 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003377 context_attr = PyString_InternFromString("__context__");
3378 if (!context_attr)
3379 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003380 }
3381 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003382 enter_attr = PyString_InternFromString("__enter__");
3383 if (!enter_attr)
3384 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003385 }
3386 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003387 exit_attr = PyString_InternFromString("__exit__");
3388 if (!exit_attr)
3389 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003390 }
3391
3392 block = compiler_new_block(c);
3393 finally = compiler_new_block(c);
3394 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003395 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003396
3397 /* Create a temporary variable to hold context.__exit__ */
3398 tmpexit = compiler_new_tmpname(c);
3399 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003400 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003401 PyArena_AddPyObject(c->c_arena, tmpexit);
3402
3403 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003404 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003405 We need to do this rather than preserving it on the stack
3406 because SETUP_FINALLY remembers the stack level.
3407 We need to do the assignment *inside* the try/finally
3408 so that context.__exit__() is called when the assignment
3409 fails. But we need to call context.__enter__() *before*
3410 the try/finally so that if it fails we won't call
3411 context.__exit__().
3412 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003413 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003414 if (tmpvalue == NULL)
3415 return 0;
3416 PyArena_AddPyObject(c->c_arena, tmpvalue);
3417 }
3418
3419 /* Evaluate (EXPR).__context__() */
3420 VISIT(c, expr, s->v.With.context_expr);
3421 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3422 ADDOP_I(c, CALL_FUNCTION, 0);
3423
3424 /* Squirrel away context.__exit__ */
3425 ADDOP(c, DUP_TOP);
3426 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3427 if (!compiler_nameop(c, tmpexit, Store))
3428 return 0;
3429
3430 /* Call context.__enter__() */
3431 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3432 ADDOP_I(c, CALL_FUNCTION, 0);
3433
3434 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003435 /* Store it in tmpvalue */
3436 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003437 return 0;
3438 }
3439 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003440 /* Discard result from context.__enter__() */
3441 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003442 }
3443
3444 /* Start the try block */
3445 ADDOP_JREL(c, SETUP_FINALLY, finally);
3446
3447 compiler_use_next_block(c, block);
3448 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003449 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003450 }
3451
3452 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 /* Bind saved result of context.__enter__() to VAR */
3454 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003455 !compiler_nameop(c, tmpvalue, Del))
3456 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003457 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003458 }
3459
3460 /* BLOCK code */
3461 VISIT_SEQ(c, stmt, s->v.With.body);
3462
3463 /* End of try block; start the finally block */
3464 ADDOP(c, POP_BLOCK);
3465 compiler_pop_fblock(c, FINALLY_TRY, block);
3466
3467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3468 compiler_use_next_block(c, finally);
3469 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003471
3472 /* Finally block starts; push tmpexit and issue our magic opcode. */
3473 if (!compiler_nameop(c, tmpexit, Load) ||
3474 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003475 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003476 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003477
3478 /* Finally block ends. */
3479 ADDOP(c, END_FINALLY);
3480 compiler_pop_fblock(c, FINALLY_END, finally);
3481 return 1;
3482}
3483
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484static int
3485compiler_visit_expr(struct compiler *c, expr_ty e)
3486{
3487 int i, n;
3488
3489 if (e->lineno > c->u->u_lineno) {
3490 c->u->u_lineno = e->lineno;
3491 c->u->u_lineno_set = false;
3492 }
3493 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003494 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003496 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497 VISIT(c, expr, e->v.BinOp.left);
3498 VISIT(c, expr, e->v.BinOp.right);
3499 ADDOP(c, binop(c, e->v.BinOp.op));
3500 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502 VISIT(c, expr, e->v.UnaryOp.operand);
3503 ADDOP(c, unaryop(e->v.UnaryOp.op));
3504 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003507 case IfExp_kind:
3508 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003509 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003510 /* XXX get rid of arg? */
3511 ADDOP_I(c, BUILD_MAP, 0);
3512 n = asdl_seq_LEN(e->v.Dict.values);
3513 /* We must arrange things just right for STORE_SUBSCR.
3514 It wants the stack to look like (value) (dict) (key) */
3515 for (i = 0; i < n; i++) {
3516 ADDOP(c, DUP_TOP);
3517 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3518 ADDOP(c, ROT_TWO);
3519 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3520 ADDOP(c, STORE_SUBSCR);
3521 }
3522 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003525 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 return compiler_genexp(c, e);
3527 case Yield_kind:
3528 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003529 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530 /*
3531 for (i = 0; i < c->u->u_nfblocks; i++) {
3532 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3533 return compiler_error(
3534 c, "'yield' not allowed in a 'try' "
3535 "block with a 'finally' clause");
3536 }
3537 */
3538 if (e->v.Yield.value) {
3539 VISIT(c, expr, e->v.Yield.value);
3540 }
3541 else {
3542 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3543 }
3544 ADDOP(c, YIELD_VALUE);
3545 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003546 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003548 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003550 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003551 VISIT(c, expr, e->v.Repr.value);
3552 ADDOP(c, UNARY_CONVERT);
3553 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003554 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3556 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003557 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003558 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3559 break;
3560 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003561 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 if (e->v.Attribute.ctx != AugStore)
3563 VISIT(c, expr, e->v.Attribute.value);
3564 switch (e->v.Attribute.ctx) {
3565 case AugLoad:
3566 ADDOP(c, DUP_TOP);
3567 /* Fall through to load */
3568 case Load:
3569 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3570 break;
3571 case AugStore:
3572 ADDOP(c, ROT_TWO);
3573 /* Fall through to save */
3574 case Store:
3575 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3576 break;
3577 case Del:
3578 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3579 break;
3580 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003581 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003582 PyErr_SetString(PyExc_SystemError,
3583 "param invalid in attribute expression");
3584 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585 }
3586 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003587 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003588 switch (e->v.Subscript.ctx) {
3589 case AugLoad:
3590 VISIT(c, expr, e->v.Subscript.value);
3591 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3592 break;
3593 case Load:
3594 VISIT(c, expr, e->v.Subscript.value);
3595 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3596 break;
3597 case AugStore:
3598 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3599 break;
3600 case Store:
3601 VISIT(c, expr, e->v.Subscript.value);
3602 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3603 break;
3604 case Del:
3605 VISIT(c, expr, e->v.Subscript.value);
3606 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3607 break;
3608 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003609 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003610 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003611 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003612 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 }
3614 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003615 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3617 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003618 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003620 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 return compiler_tuple(c, e);
3622 }
3623 return 1;
3624}
3625
3626static int
3627compiler_augassign(struct compiler *c, stmt_ty s)
3628{
3629 expr_ty e = s->v.AugAssign.target;
3630 expr_ty auge;
3631
3632 assert(s->kind == AugAssign_kind);
3633
3634 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003635 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003637 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003638 if (auge == NULL)
3639 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003640 VISIT(c, expr, auge);
3641 VISIT(c, expr, s->v.AugAssign.value);
3642 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3643 auge->v.Attribute.ctx = AugStore;
3644 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003645 break;
3646 case Subscript_kind:
3647 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003648 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003649 if (auge == NULL)
3650 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003651 VISIT(c, expr, auge);
3652 VISIT(c, expr, s->v.AugAssign.value);
3653 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003656 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 case Name_kind:
3658 VISIT(c, expr, s->v.AugAssign.target);
3659 VISIT(c, expr, s->v.AugAssign.value);
3660 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3661 return compiler_nameop(c, e->v.Name.id, Store);
3662 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003663 PyErr_Format(PyExc_SystemError,
3664 "invalid node type (%d) for augmented assignment",
3665 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003666 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667 }
3668 return 1;
3669}
3670
3671static int
3672compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3673{
3674 struct fblockinfo *f;
3675 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3676 return 0;
3677 f = &c->u->u_fblock[c->u->u_nfblocks++];
3678 f->fb_type = t;
3679 f->fb_block = b;
3680 return 1;
3681}
3682
3683static void
3684compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3685{
3686 struct compiler_unit *u = c->u;
3687 assert(u->u_nfblocks > 0);
3688 u->u_nfblocks--;
3689 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3690 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3691}
3692
3693/* Raises a SyntaxError and returns 0.
3694 If something goes wrong, a different exception may be raised.
3695*/
3696
3697static int
3698compiler_error(struct compiler *c, const char *errstr)
3699{
3700 PyObject *loc;
3701 PyObject *u = NULL, *v = NULL;
3702
3703 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3704 if (!loc) {
3705 Py_INCREF(Py_None);
3706 loc = Py_None;
3707 }
3708 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3709 Py_None, loc);
3710 if (!u)
3711 goto exit;
3712 v = Py_BuildValue("(zO)", errstr, u);
3713 if (!v)
3714 goto exit;
3715 PyErr_SetObject(PyExc_SyntaxError, v);
3716 exit:
3717 Py_DECREF(loc);
3718 Py_XDECREF(u);
3719 Py_XDECREF(v);
3720 return 0;
3721}
3722
3723static int
3724compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003725 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003727 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003728
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003729 /* XXX this code is duplicated */
3730 switch (ctx) {
3731 case AugLoad: /* fall through to Load */
3732 case Load: op = BINARY_SUBSCR; break;
3733 case AugStore:/* fall through to Store */
3734 case Store: op = STORE_SUBSCR; break;
3735 case Del: op = DELETE_SUBSCR; break;
3736 case Param:
3737 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003738 "invalid %s kind %d in subscript\n",
3739 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740 return 0;
3741 }
3742 if (ctx == AugLoad) {
3743 ADDOP_I(c, DUP_TOPX, 2);
3744 }
3745 else if (ctx == AugStore) {
3746 ADDOP(c, ROT_THREE);
3747 }
3748 ADDOP(c, op);
3749 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003750}
3751
3752static int
3753compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3754{
3755 int n = 2;
3756 assert(s->kind == Slice_kind);
3757
3758 /* only handles the cases where BUILD_SLICE is emitted */
3759 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003760 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 }
3762 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003763 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003767 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003768 }
3769 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003770 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771 }
3772
3773 if (s->v.Slice.step) {
3774 n++;
3775 VISIT(c, expr, s->v.Slice.step);
3776 }
3777 ADDOP_I(c, BUILD_SLICE, n);
3778 return 1;
3779}
3780
3781static int
3782compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3783{
3784 int op = 0, slice_offset = 0, stack_count = 0;
3785
3786 assert(s->v.Slice.step == NULL);
3787 if (s->v.Slice.lower) {
3788 slice_offset++;
3789 stack_count++;
3790 if (ctx != AugStore)
3791 VISIT(c, expr, s->v.Slice.lower);
3792 }
3793 if (s->v.Slice.upper) {
3794 slice_offset += 2;
3795 stack_count++;
3796 if (ctx != AugStore)
3797 VISIT(c, expr, s->v.Slice.upper);
3798 }
3799
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003800 if (ctx == AugLoad) {
3801 switch (stack_count) {
3802 case 0: ADDOP(c, DUP_TOP); break;
3803 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3804 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3805 }
3806 }
3807 else if (ctx == AugStore) {
3808 switch (stack_count) {
3809 case 0: ADDOP(c, ROT_TWO); break;
3810 case 1: ADDOP(c, ROT_THREE); break;
3811 case 2: ADDOP(c, ROT_FOUR); break;
3812 }
3813 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003814
3815 switch (ctx) {
3816 case AugLoad: /* fall through to Load */
3817 case Load: op = SLICE; break;
3818 case AugStore:/* fall through to Store */
3819 case Store: op = STORE_SLICE; break;
3820 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003821 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003822 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003823 PyErr_SetString(PyExc_SystemError,
3824 "param invalid in simple slice");
3825 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826 }
3827
3828 ADDOP(c, op + slice_offset);
3829 return 1;
3830}
3831
3832static int
3833compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3834 expr_context_ty ctx)
3835{
3836 switch (s->kind) {
3837 case Ellipsis_kind:
3838 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3839 break;
3840 case Slice_kind:
3841 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 case Index_kind:
3843 VISIT(c, expr, s->v.Index.value);
3844 break;
3845 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003846 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003847 PyErr_SetString(PyExc_SystemError,
3848 "extended slice invalid in nested slice");
3849 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 }
3851 return 1;
3852}
3853
3854
3855static int
3856compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3857{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003858 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003859 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003860 case Index_kind:
3861 kindname = "index";
3862 if (ctx != AugStore) {
3863 VISIT(c, expr, s->v.Index.value);
3864 }
3865 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003867 kindname = "ellipsis";
3868 if (ctx != AugStore) {
3869 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3870 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003871 break;
3872 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003873 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874 if (!s->v.Slice.step)
3875 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003876 if (ctx != AugStore) {
3877 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003878 return 0;
3879 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003880 break;
3881 case ExtSlice_kind:
3882 kindname = "extended slice";
3883 if (ctx != AugStore) {
3884 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3885 for (i = 0; i < n; i++) {
3886 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3887 if (!compiler_visit_nested_slice(c, sub, ctx))
3888 return 0;
3889 }
3890 ADDOP_I(c, BUILD_TUPLE, n);
3891 }
3892 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003893 default:
3894 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003895 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003896 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003897 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003898 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003899}
3900
3901/* do depth-first search of basic block graph, starting with block.
3902 post records the block indices in post-order.
3903
3904 XXX must handle implicit jumps from one block to next
3905*/
3906
3907static void
3908dfs(struct compiler *c, basicblock *b, struct assembler *a)
3909{
3910 int i;
3911 struct instr *instr = NULL;
3912
3913 if (b->b_seen)
3914 return;
3915 b->b_seen = 1;
3916 if (b->b_next != NULL)
3917 dfs(c, b->b_next, a);
3918 for (i = 0; i < b->b_iused; i++) {
3919 instr = &b->b_instr[i];
3920 if (instr->i_jrel || instr->i_jabs)
3921 dfs(c, instr->i_target, a);
3922 }
3923 a->a_postorder[a->a_nblocks++] = b;
3924}
3925
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003926static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003927stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3928{
3929 int i;
3930 struct instr *instr;
3931 if (b->b_seen || b->b_startdepth >= depth)
3932 return maxdepth;
3933 b->b_seen = 1;
3934 b->b_startdepth = depth;
3935 for (i = 0; i < b->b_iused; i++) {
3936 instr = &b->b_instr[i];
3937 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3938 if (depth > maxdepth)
3939 maxdepth = depth;
3940 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3941 if (instr->i_jrel || instr->i_jabs) {
3942 maxdepth = stackdepth_walk(c, instr->i_target,
3943 depth, maxdepth);
3944 if (instr->i_opcode == JUMP_ABSOLUTE ||
3945 instr->i_opcode == JUMP_FORWARD) {
3946 goto out; /* remaining code is dead */
3947 }
3948 }
3949 }
3950 if (b->b_next)
3951 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3952out:
3953 b->b_seen = 0;
3954 return maxdepth;
3955}
3956
3957/* Find the flow path that needs the largest stack. We assume that
3958 * cycles in the flow graph have no net effect on the stack depth.
3959 */
3960static int
3961stackdepth(struct compiler *c)
3962{
3963 basicblock *b, *entryblock;
3964 entryblock = NULL;
3965 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3966 b->b_seen = 0;
3967 b->b_startdepth = INT_MIN;
3968 entryblock = b;
3969 }
3970 return stackdepth_walk(c, entryblock, 0, 0);
3971}
3972
3973static int
3974assemble_init(struct assembler *a, int nblocks, int firstlineno)
3975{
3976 memset(a, 0, sizeof(struct assembler));
3977 a->a_lineno = firstlineno;
3978 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3979 if (!a->a_bytecode)
3980 return 0;
3981 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3982 if (!a->a_lnotab)
3983 return 0;
3984 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003985 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003986 if (!a->a_postorder) {
3987 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003988 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003989 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003990 return 1;
3991}
3992
3993static void
3994assemble_free(struct assembler *a)
3995{
3996 Py_XDECREF(a->a_bytecode);
3997 Py_XDECREF(a->a_lnotab);
3998 if (a->a_postorder)
3999 PyObject_Free(a->a_postorder);
4000}
4001
4002/* Return the size of a basic block in bytes. */
4003
4004static int
4005instrsize(struct instr *instr)
4006{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004007 if (!instr->i_hasarg)
4008 return 1;
4009 if (instr->i_oparg > 0xffff)
4010 return 6;
4011 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004012}
4013
4014static int
4015blocksize(basicblock *b)
4016{
4017 int i;
4018 int size = 0;
4019
4020 for (i = 0; i < b->b_iused; i++)
4021 size += instrsize(&b->b_instr[i]);
4022 return size;
4023}
4024
4025/* All about a_lnotab.
4026
4027c_lnotab is an array of unsigned bytes disguised as a Python string.
4028It is used to map bytecode offsets to source code line #s (when needed
4029for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004030
Tim Peters2a7f3842001-06-09 09:26:21 +00004031The array is conceptually a list of
4032 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004033pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004034
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004035 byte code offset source code line number
4036 0 1
4037 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004038 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004039 350 307
4040 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004041
4042The first trick is that these numbers aren't stored, only the increments
4043from one row to the next (this doesn't really work, but it's a start):
4044
4045 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4046
4047The second trick is that an unsigned byte can't hold negative values, or
4048values larger than 255, so (a) there's a deep assumption that byte code
4049offsets and their corresponding line #s both increase monotonically, and (b)
4050if at least one column jumps by more than 255 from one row to the next, more
4051than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004052from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004053part. A user of c_lnotab desiring to find the source line number
4054corresponding to a bytecode address A should do something like this
4055
4056 lineno = addr = 0
4057 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004058 addr += addr_incr
4059 if addr > A:
4060 return lineno
4061 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004062
4063In order for this to work, when the addr field increments by more than 255,
4064the line # increment in each pair generated must be 0 until the remaining addr
4065increment is < 256. So, in the example above, com_set_lineno should not (as
4066was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004067255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004068*/
4069
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004070static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004072{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004073 int d_bytecode, d_lineno;
4074 int len;
4075 char *lnotab;
4076
4077 d_bytecode = a->a_offset - a->a_lineno_off;
4078 d_lineno = i->i_lineno - a->a_lineno;
4079
4080 assert(d_bytecode >= 0);
4081 assert(d_lineno >= 0);
4082
4083 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004084 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004085
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004086 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004087 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088 nbytes = a->a_lnotab_off + 2 * ncodes;
4089 len = PyString_GET_SIZE(a->a_lnotab);
4090 if (nbytes >= len) {
4091 if (len * 2 < nbytes)
4092 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004093 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094 len *= 2;
4095 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4096 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004097 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004099 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 *lnotab++ = 255;
4101 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 d_bytecode -= ncodes * 255;
4104 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004105 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106 assert(d_bytecode <= 255);
4107 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004108 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109 nbytes = a->a_lnotab_off + 2 * ncodes;
4110 len = PyString_GET_SIZE(a->a_lnotab);
4111 if (nbytes >= len) {
4112 if (len * 2 < nbytes)
4113 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004114 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115 len *= 2;
4116 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4117 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004118 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4120 *lnotab++ = 255;
4121 *lnotab++ = d_bytecode;
4122 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004123 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 *lnotab++ = 255;
4125 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004126 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004127 d_lineno -= ncodes * 255;
4128 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004129 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131 len = PyString_GET_SIZE(a->a_lnotab);
4132 if (a->a_lnotab_off + 2 >= len) {
4133 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004134 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004135 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004136 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 a->a_lnotab_off += 2;
4139 if (d_bytecode) {
4140 *lnotab++ = d_bytecode;
4141 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004142 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004143 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004144 *lnotab++ = 0;
4145 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004146 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 a->a_lineno = i->i_lineno;
4148 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004149 return 1;
4150}
4151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152/* assemble_emit()
4153 Extend the bytecode with a new instruction.
4154 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004155*/
4156
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004157static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004158assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004159{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004160 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 int len = PyString_GET_SIZE(a->a_bytecode);
4162 char *code;
4163
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004164 size = instrsize(i);
4165 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004167 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004168 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004170 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171 if (a->a_offset + size >= len) {
4172 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004173 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4176 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004177 if (size == 6) {
4178 assert(i->i_hasarg);
4179 *code++ = (char)EXTENDED_ARG;
4180 *code++ = ext & 0xff;
4181 *code++ = ext >> 8;
4182 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004185 if (i->i_hasarg) {
4186 assert(size == 3 || size == 6);
4187 *code++ = arg & 0xff;
4188 *code++ = arg >> 8;
4189 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004191}
4192
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004193static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004195{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004196 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004197 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004198 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 /* Compute the size of each block and fixup jump args.
4201 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004202start:
4203 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004205 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206 bsize = blocksize(b);
4207 b->b_offset = totsize;
4208 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004209 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004210 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004211 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4212 bsize = b->b_offset;
4213 for (i = 0; i < b->b_iused; i++) {
4214 struct instr *instr = &b->b_instr[i];
4215 /* Relative jumps are computed relative to
4216 the instruction pointer after fetching
4217 the jump instruction.
4218 */
4219 bsize += instrsize(instr);
4220 if (instr->i_jabs)
4221 instr->i_oparg = instr->i_target->b_offset;
4222 else if (instr->i_jrel) {
4223 int delta = instr->i_target->b_offset - bsize;
4224 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004225 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004226 else
4227 continue;
4228 if (instr->i_oparg > 0xffff)
4229 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004230 }
4231 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004232
4233 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004234 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004235 with a better solution.
4236
4237 In the meantime, should the goto be dropped in favor
4238 of a loop?
4239
4240 The issue is that in the first loop blocksize() is called
4241 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004242 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004243 i_oparg is calculated in the second loop above.
4244
4245 So we loop until we stop seeing new EXTENDED_ARGs.
4246 The only EXTENDED_ARGs that could be popping up are
4247 ones in jump instructions. So this should converge
4248 fairly quickly.
4249 */
4250 if (last_extended_arg_count != extended_arg_count) {
4251 last_extended_arg_count = extended_arg_count;
4252 goto start;
4253 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004254}
4255
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004256static PyObject *
4257dict_keys_inorder(PyObject *dict, int offset)
4258{
4259 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004260 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004261
4262 tuple = PyTuple_New(size);
4263 if (tuple == NULL)
4264 return NULL;
4265 while (PyDict_Next(dict, &pos, &k, &v)) {
4266 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004267 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004268 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004269 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004270 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004271 PyTuple_SET_ITEM(tuple, i - offset, k);
4272 }
4273 return tuple;
4274}
4275
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004276static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004278{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004279 PySTEntryObject *ste = c->u->u_ste;
4280 int flags = 0, n;
4281 if (ste->ste_type != ModuleBlock)
4282 flags |= CO_NEWLOCALS;
4283 if (ste->ste_type == FunctionBlock) {
4284 if (!ste->ste_unoptimized)
4285 flags |= CO_OPTIMIZED;
4286 if (ste->ste_nested)
4287 flags |= CO_NESTED;
4288 if (ste->ste_generator)
4289 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004290 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291 if (ste->ste_varargs)
4292 flags |= CO_VARARGS;
4293 if (ste->ste_varkeywords)
4294 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004295 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004297
4298 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004299 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004300
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301 n = PyDict_Size(c->u->u_freevars);
4302 if (n < 0)
4303 return -1;
4304 if (n == 0) {
4305 n = PyDict_Size(c->u->u_cellvars);
4306 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004307 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308 if (n == 0) {
4309 flags |= CO_NOFREE;
4310 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004311 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004312
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004313 return flags;
4314}
4315
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316static PyCodeObject *
4317makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004318{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004319 PyObject *tmp;
4320 PyCodeObject *co = NULL;
4321 PyObject *consts = NULL;
4322 PyObject *names = NULL;
4323 PyObject *varnames = NULL;
4324 PyObject *filename = NULL;
4325 PyObject *name = NULL;
4326 PyObject *freevars = NULL;
4327 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004328 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004329 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004330
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331 tmp = dict_keys_inorder(c->u->u_consts, 0);
4332 if (!tmp)
4333 goto error;
4334 consts = PySequence_List(tmp); /* optimize_code requires a list */
4335 Py_DECREF(tmp);
4336
4337 names = dict_keys_inorder(c->u->u_names, 0);
4338 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4339 if (!consts || !names || !varnames)
4340 goto error;
4341
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004342 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4343 if (!cellvars)
4344 goto error;
4345 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4346 if (!freevars)
4347 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004348 filename = PyString_FromString(c->c_filename);
4349 if (!filename)
4350 goto error;
4351
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004352 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004353 flags = compute_code_flags(c);
4354 if (flags < 0)
4355 goto error;
4356
4357 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4358 if (!bytecode)
4359 goto error;
4360
4361 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4362 if (!tmp)
4363 goto error;
4364 Py_DECREF(consts);
4365 consts = tmp;
4366
4367 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4368 bytecode, consts, names, varnames,
4369 freevars, cellvars,
4370 filename, c->u->u_name,
4371 c->u->u_firstlineno,
4372 a->a_lnotab);
4373 error:
4374 Py_XDECREF(consts);
4375 Py_XDECREF(names);
4376 Py_XDECREF(varnames);
4377 Py_XDECREF(filename);
4378 Py_XDECREF(name);
4379 Py_XDECREF(freevars);
4380 Py_XDECREF(cellvars);
4381 Py_XDECREF(bytecode);
4382 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004383}
4384
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385static PyCodeObject *
4386assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004387{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004388 basicblock *b, *entryblock;
4389 struct assembler a;
4390 int i, j, nblocks;
4391 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004392
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004393 /* Make sure every block that falls off the end returns None.
4394 XXX NEXT_BLOCK() isn't quite right, because if the last
4395 block ends with a jump or return b_next shouldn't set.
4396 */
4397 if (!c->u->u_curblock->b_return) {
4398 NEXT_BLOCK(c);
4399 if (addNone)
4400 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4401 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004402 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404 nblocks = 0;
4405 entryblock = NULL;
4406 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4407 nblocks++;
4408 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004409 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4412 goto error;
4413 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004414
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004416 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004417
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418 /* Emit code in reverse postorder from dfs. */
4419 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004420 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421 for (j = 0; j < b->b_iused; j++)
4422 if (!assemble_emit(&a, &b->b_instr[j]))
4423 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004424 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4427 goto error;
4428 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4429 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004430
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004431 co = makecode(c, &a);
4432 error:
4433 assemble_free(&a);
4434 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004435}