blob: c07b6d346da38797fb136c4c1b0c988abd8241d1 [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;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322 PyObject *v, *k, *dict = PyDict_New();
Guido van Rossumd076c731998-10-07 19:42:25 +0000323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 n = PyList_Size(list);
325 for (i = 0; i < n; i++) {
326 v = PyInt_FromLong(i);
327 if (!v) {
328 Py_DECREF(dict);
329 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000330 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000331 k = PyList_GET_ITEM(list, i);
332 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
334 Py_XDECREF(k);
335 Py_DECREF(v);
336 Py_DECREF(dict);
337 return NULL;
338 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000339 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 return dict;
343}
344
345/* Return new dict containing names from src that match scope(s).
346
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000347src is a symbol table dictionary. If the scope of a name matches
348either scope_type or flag is set, insert it into the new dict. The
349values are integers, starting at offset and increasing by one for
350each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351*/
352
353static PyObject *
354dictbytype(PyObject *src, int scope_type, int flag, int offset)
355{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357 PyObject *k, *v, *dest = PyDict_New();
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359 assert(offset >= 0);
360 if (dest == NULL)
361 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
363 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 /* XXX this should probably be a macro in symtable.h */
365 assert(PyInt_Check(v));
366 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
369 PyObject *tuple, *item = PyInt_FromLong(i);
370 if (item == NULL) {
371 Py_DECREF(dest);
372 return NULL;
373 }
374 i++;
375 tuple = Py_BuildValue("(OO)", k, k->ob_type);
376 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
377 Py_DECREF(item);
378 Py_DECREF(dest);
379 Py_XDECREF(tuple);
380 return NULL;
381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000383 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
386 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000387}
388
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000389/* Begin: Peephole optimizations ----------------------------------------- */
390
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000391#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000392#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000393#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
394#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000395#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000396#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define ISBASICBLOCK(blocks, start, bytes) \
398 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000399
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000400/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000401 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000402 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000403 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000404 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000405 Bails out with no change if one or more of the LOAD_CONSTs is missing.
406 Also works for BUILD_LIST when followed by an "in" or "not in" test.
407*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000408static int
409tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
410{
411 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413
414 /* Pre-conditions */
415 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000416 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000417 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000419 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000420
421 /* Buildup new tuple of constants */
422 newconst = PyTuple_New(n);
423 if (newconst == NULL)
424 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000425 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000426 for (i=0 ; i<n ; i++) {
427 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000428 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000429 constant = PyList_GET_ITEM(consts, arg);
430 Py_INCREF(constant);
431 PyTuple_SET_ITEM(newconst, i, constant);
432 }
433
434 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000435 if (PyList_Append(consts, newconst)) {
436 Py_DECREF(newconst);
437 return 0;
438 }
439 Py_DECREF(newconst);
440
441 /* Write NOPs over old LOAD_CONSTS and
442 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
443 memset(codestr, NOP, n*3);
444 codestr[n*3] = LOAD_CONST;
445 SETARG(codestr, (n*3), len_consts);
446 return 1;
447}
448
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000449/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000451 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000452 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000453 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000454 Abandons the transformation if the folding fails (i.e. 1+'a').
455 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456 is below a threshold value. That keeps pyc files from
457 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000458*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000459static int
460fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
461{
462 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000463 Py_ssize_t len_consts, size;
464 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000465
466 /* Pre-conditions */
467 assert(PyList_CheckExact(consts));
468 assert(codestr[0] == LOAD_CONST);
469 assert(codestr[3] == LOAD_CONST);
470
471 /* Create new constant */
472 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
473 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
474 opcode = codestr[6];
475 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000476 case BINARY_POWER:
477 newconst = PyNumber_Power(v, w, Py_None);
478 break;
479 case BINARY_MULTIPLY:
480 newconst = PyNumber_Multiply(v, w);
481 break;
482 case BINARY_DIVIDE:
483 /* Cannot fold this operation statically since
484 the result can depend on the run-time presence
485 of the -Qnew flag */
486 return 0;
487 case BINARY_TRUE_DIVIDE:
488 newconst = PyNumber_TrueDivide(v, w);
489 break;
490 case BINARY_FLOOR_DIVIDE:
491 newconst = PyNumber_FloorDivide(v, w);
492 break;
493 case BINARY_MODULO:
494 newconst = PyNumber_Remainder(v, w);
495 break;
496 case BINARY_ADD:
497 newconst = PyNumber_Add(v, w);
498 break;
499 case BINARY_SUBTRACT:
500 newconst = PyNumber_Subtract(v, w);
501 break;
502 case BINARY_SUBSCR:
503 newconst = PyObject_GetItem(v, w);
504 break;
505 case BINARY_LSHIFT:
506 newconst = PyNumber_Lshift(v, w);
507 break;
508 case BINARY_RSHIFT:
509 newconst = PyNumber_Rshift(v, w);
510 break;
511 case BINARY_AND:
512 newconst = PyNumber_And(v, w);
513 break;
514 case BINARY_XOR:
515 newconst = PyNumber_Xor(v, w);
516 break;
517 case BINARY_OR:
518 newconst = PyNumber_Or(v, w);
519 break;
520 default:
521 /* Called with an unknown opcode */
522 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000523 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000524 opcode);
525 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000526 }
527 if (newconst == NULL) {
528 PyErr_Clear();
529 return 0;
530 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000531 size = PyObject_Size(newconst);
532 if (size == -1)
533 PyErr_Clear();
534 else if (size > 20) {
535 Py_DECREF(newconst);
536 return 0;
537 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000538
539 /* Append folded constant into consts table */
540 len_consts = PyList_GET_SIZE(consts);
541 if (PyList_Append(consts, newconst)) {
542 Py_DECREF(newconst);
543 return 0;
544 }
545 Py_DECREF(newconst);
546
547 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
548 memset(codestr, NOP, 4);
549 codestr[4] = LOAD_CONST;
550 SETARG(codestr, 4, len_consts);
551 return 1;
552}
553
Raymond Hettinger80121492005-02-20 12:41:32 +0000554static int
555fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
556{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000557 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558 Py_ssize_t len_consts;
559 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000560
561 /* Pre-conditions */
562 assert(PyList_CheckExact(consts));
563 assert(codestr[0] == LOAD_CONST);
564
565 /* Create new constant */
566 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
567 opcode = codestr[3];
568 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000569 case UNARY_NEGATIVE:
570 /* Preserve the sign of -0.0 */
571 if (PyObject_IsTrue(v) == 1)
572 newconst = PyNumber_Negative(v);
573 break;
574 case UNARY_CONVERT:
575 newconst = PyObject_Repr(v);
576 break;
577 case UNARY_INVERT:
578 newconst = PyNumber_Invert(v);
579 break;
580 default:
581 /* Called with an unknown opcode */
582 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000583 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000584 opcode);
585 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000586 }
587 if (newconst == NULL) {
588 PyErr_Clear();
589 return 0;
590 }
591
592 /* Append folded constant into consts table */
593 len_consts = PyList_GET_SIZE(consts);
594 if (PyList_Append(consts, newconst)) {
595 Py_DECREF(newconst);
596 return 0;
597 }
598 Py_DECREF(newconst);
599
600 /* Write NOP LOAD_CONST newconst */
601 codestr[0] = NOP;
602 codestr[1] = LOAD_CONST;
603 SETARG(codestr, 1, len_consts);
604 return 1;
605}
606
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000607static unsigned int *
608markblocks(unsigned char *code, int len)
609{
610 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000611 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612
613 if (blocks == NULL)
614 return NULL;
615 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616
617 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000618 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
619 opcode = code[i];
620 switch (opcode) {
621 case FOR_ITER:
622 case JUMP_FORWARD:
623 case JUMP_IF_FALSE:
624 case JUMP_IF_TRUE:
625 case JUMP_ABSOLUTE:
626 case CONTINUE_LOOP:
627 case SETUP_LOOP:
628 case SETUP_EXCEPT:
629 case SETUP_FINALLY:
630 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000631 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000633 }
634 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000635 /* Build block numbers in the second pass */
636 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000638 blocks[i] = blockcnt;
639 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000640 return blocks;
641}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000642
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000643/* Perform basic peephole optimizations to components of a code object.
644 The consts object should still be in list form to allow new constants
645 to be appended.
646
647 To keep the optimizer simple, it bails out (does nothing) for code
648 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000649 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000650 the lineno table has complex encoding for gaps >= 255.
651
652 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000653 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000654 smaller. For those that reduce size, the gaps are initially filled with
655 NOPs. Later those NOPs are removed and the jump addresses retargeted in
656 a single pass. Line numbering is adjusted accordingly. */
657
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000658static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000659optimize_code(PyObject *code, PyObject* consts, PyObject *names,
660 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000661{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000662 Py_ssize_t i, j, codelen;
663 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000664 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000665 unsigned char *codestr = NULL;
666 unsigned char *lineno;
667 int *addrmap = NULL;
668 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000669 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000670 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000671 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000672
Raymond Hettingereffb3932004-10-30 08:55:08 +0000673 /* Bail out if an exception is set */
674 if (PyErr_Occurred())
675 goto exitUnchanged;
676
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000677 /* Bypass optimization when the lineno table is too complex */
678 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000679 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000680 tabsiz = PyString_GET_SIZE(lineno_obj);
681 if (memchr(lineno, 255, tabsiz) != NULL)
682 goto exitUnchanged;
683
Raymond Hettingera12fa142004-08-24 04:34:16 +0000684 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000685 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000686 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000687 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000688 goto exitUnchanged;
689
690 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000692 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000693 goto exitUnchanged;
694 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000695
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000696 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000697 the various transformation patterns to look ahead several
698 instructions without additional checks to make sure they are not
699 looking beyond the end of the code string.
700 */
701 if (codestr[codelen-1] != RETURN_VALUE)
702 goto exitUnchanged;
703
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000704 /* Mapping to new jump targets after NOPs are removed */
705 addrmap = PyMem_Malloc(codelen * sizeof(int));
706 if (addrmap == NULL)
707 goto exitUnchanged;
708
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000709 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000710 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000711 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000712 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000713
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000714 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000715 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000716
717 lastlc = cumlc;
718 cumlc = 0;
719
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000720 switch (opcode) {
721
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000722 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
723 with JUMP_IF_TRUE POP_TOP */
724 case UNARY_NOT:
725 if (codestr[i+1] != JUMP_IF_FALSE ||
726 codestr[i+4] != POP_TOP ||
727 !ISBASICBLOCK(blocks,i,5))
728 continue;
729 tgt = GETJUMPTGT(codestr, (i+1));
730 if (codestr[tgt] != POP_TOP)
731 continue;
732 j = GETARG(codestr, i+1) + 1;
733 codestr[i] = JUMP_IF_TRUE;
734 SETARG(codestr, i, j);
735 codestr[i+3] = POP_TOP;
736 codestr[i+4] = NOP;
737 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000738
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000739 /* not a is b --> a is not b
740 not a in b --> a not in b
741 not a is not b --> a is b
742 not a not in b --> a in b
743 */
744 case COMPARE_OP:
745 j = GETARG(codestr, i);
746 if (j < 6 || j > 9 ||
747 codestr[i+3] != UNARY_NOT ||
748 !ISBASICBLOCK(blocks,i,4))
749 continue;
750 SETARG(codestr, i, (j^1));
751 codestr[i+3] = NOP;
752 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000753
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000754 /* Replace LOAD_GLOBAL/LOAD_NAME None
755 with LOAD_CONST None */
756 case LOAD_NAME:
757 case LOAD_GLOBAL:
758 j = GETARG(codestr, i);
759 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
760 if (name == NULL || strcmp(name, "None") != 0)
761 continue;
762 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
763 if (PyList_GET_ITEM(consts, j) == Py_None) {
764 codestr[i] = LOAD_CONST;
765 SETARG(codestr, i, j);
766 cumlc = lastlc + 1;
767 break;
768 }
769 }
770 break;
771
772 /* Skip over LOAD_CONST trueconst
773 JUMP_IF_FALSE xx POP_TOP */
774 case LOAD_CONST:
775 cumlc = lastlc + 1;
776 j = GETARG(codestr, i);
777 if (codestr[i+3] != JUMP_IF_FALSE ||
778 codestr[i+6] != POP_TOP ||
779 !ISBASICBLOCK(blocks,i,7) ||
780 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
781 continue;
782 memset(codestr+i, NOP, 7);
783 cumlc = 0;
784 break;
785
786 /* Try to fold tuples of constants (includes a case for lists
787 which are only used for "in" and "not in" tests).
788 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
789 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
790 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
791 case BUILD_TUPLE:
792 case BUILD_LIST:
793 j = GETARG(codestr, i);
794 h = i - 3 * j;
795 if (h >= 0 &&
796 j <= lastlc &&
797 ((opcode == BUILD_TUPLE &&
798 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
799 (opcode == BUILD_LIST &&
800 codestr[i+3]==COMPARE_OP &&
801 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
802 (GETARG(codestr,i+3)==6 ||
803 GETARG(codestr,i+3)==7))) &&
804 tuple_of_constants(&codestr[h], j, consts)) {
805 assert(codestr[i] == LOAD_CONST);
806 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000807 break;
808 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000809 if (codestr[i+3] != UNPACK_SEQUENCE ||
810 !ISBASICBLOCK(blocks,i,6) ||
811 j != GETARG(codestr, i+3))
812 continue;
813 if (j == 1) {
814 memset(codestr+i, NOP, 6);
815 } else if (j == 2) {
816 codestr[i] = ROT_TWO;
817 memset(codestr+i+1, NOP, 5);
818 } else if (j == 3) {
819 codestr[i] = ROT_THREE;
820 codestr[i+1] = ROT_TWO;
821 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000822 }
823 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000824
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000825 /* Fold binary ops on constants.
826 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
827 case BINARY_POWER:
828 case BINARY_MULTIPLY:
829 case BINARY_TRUE_DIVIDE:
830 case BINARY_FLOOR_DIVIDE:
831 case BINARY_MODULO:
832 case BINARY_ADD:
833 case BINARY_SUBTRACT:
834 case BINARY_SUBSCR:
835 case BINARY_LSHIFT:
836 case BINARY_RSHIFT:
837 case BINARY_AND:
838 case BINARY_XOR:
839 case BINARY_OR:
840 if (lastlc >= 2 &&
841 ISBASICBLOCK(blocks, i-6, 7) &&
842 fold_binops_on_constants(&codestr[i-6], consts)) {
843 i -= 2;
844 assert(codestr[i] == LOAD_CONST);
845 cumlc = 1;
846 }
847 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000848
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000849 /* Fold unary ops on constants.
850 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
851 case UNARY_NEGATIVE:
852 case UNARY_CONVERT:
853 case UNARY_INVERT:
854 if (lastlc >= 1 &&
855 ISBASICBLOCK(blocks, i-3, 4) &&
856 fold_unaryops_on_constants(&codestr[i-3], consts)) {
857 i -= 2;
858 assert(codestr[i] == LOAD_CONST);
859 cumlc = 1;
860 }
861 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000862
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000863 /* Simplify conditional jump to conditional jump where the
864 result of the first test implies the success of a similar
865 test or the failure of the opposite test.
866 Arises in code like:
867 "if a and b:"
868 "if a or b:"
869 "a and b or c"
870 "(a and b) and c"
871 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
872 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
873 where y+3 is the instruction following the second test.
874 */
875 case JUMP_IF_FALSE:
876 case JUMP_IF_TRUE:
877 tgt = GETJUMPTGT(codestr, i);
878 j = codestr[tgt];
879 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
880 if (j == opcode) {
881 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
882 SETARG(codestr, i, tgttgt);
883 } else {
884 tgt -= i;
885 SETARG(codestr, i, tgt);
886 }
887 break;
888 }
889 /* Intentional fallthrough */
890
891 /* Replace jumps to unconditional jumps */
892 case FOR_ITER:
893 case JUMP_FORWARD:
894 case JUMP_ABSOLUTE:
895 case CONTINUE_LOOP:
896 case SETUP_LOOP:
897 case SETUP_EXCEPT:
898 case SETUP_FINALLY:
899 tgt = GETJUMPTGT(codestr, i);
900 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
901 continue;
902 tgttgt = GETJUMPTGT(codestr, tgt);
903 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
904 opcode = JUMP_ABSOLUTE;
905 if (!ABSOLUTE_JUMP(opcode))
906 tgttgt -= i + 3; /* Calc relative jump addr */
907 if (tgttgt < 0) /* No backward relative jumps */
908 continue;
909 codestr[i] = opcode;
910 SETARG(codestr, i, tgttgt);
911 break;
912
913 case EXTENDED_ARG:
914 goto exitUnchanged;
915
916 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
917 case RETURN_VALUE:
918 if (i+4 >= codelen ||
919 codestr[i+4] != RETURN_VALUE ||
920 !ISBASICBLOCK(blocks,i,5))
921 continue;
922 memset(codestr+i+1, NOP, 4);
923 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000924 }
925 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000926
927 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000928 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
929 addrmap[i] = i - nops;
930 if (codestr[i] == NOP)
931 nops++;
932 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000933 cum_orig_line = 0;
934 last_line = 0;
935 for (i=0 ; i < tabsiz ; i+=2) {
936 cum_orig_line += lineno[i];
937 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000938 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000939 lineno[i] =((unsigned char)(new_line - last_line));
940 last_line = new_line;
941 }
942
943 /* Remove NOPs and fixup jump targets */
944 for (i=0, h=0 ; i<codelen ; ) {
945 opcode = codestr[i];
946 switch (opcode) {
947 case NOP:
948 i++;
949 continue;
950
951 case JUMP_ABSOLUTE:
952 case CONTINUE_LOOP:
953 j = addrmap[GETARG(codestr, i)];
954 SETARG(codestr, i, j);
955 break;
956
957 case FOR_ITER:
958 case JUMP_FORWARD:
959 case JUMP_IF_FALSE:
960 case JUMP_IF_TRUE:
961 case SETUP_LOOP:
962 case SETUP_EXCEPT:
963 case SETUP_FINALLY:
964 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
965 SETARG(codestr, i, j);
966 break;
967 }
968 adj = CODESIZE(opcode);
969 while (adj--)
970 codestr[h++] = codestr[i++];
971 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000972 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000973
974 code = PyString_FromStringAndSize((char *)codestr, h);
975 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000976 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000977 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000978 return code;
979
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000981 if (blocks != NULL)
982 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000983 if (addrmap != NULL)
984 PyMem_Free(addrmap);
985 if (codestr != NULL)
986 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000987 Py_INCREF(code);
988 return code;
989}
990
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000991/* End: Peephole optimizations ----------------------------------------- */
992
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993/*
994
995Leave this debugging code for just a little longer.
996
997static void
998compiler_display_symbols(PyObject *name, PyObject *symbols)
999{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000PyObject *key, *value;
1001int flags;
1002Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1005while (PyDict_Next(symbols, &pos, &key, &value)) {
1006flags = PyInt_AsLong(value);
1007fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1008if (flags & DEF_GLOBAL)
1009fprintf(stderr, " declared_global");
1010if (flags & DEF_LOCAL)
1011fprintf(stderr, " local");
1012if (flags & DEF_PARAM)
1013fprintf(stderr, " param");
1014if (flags & DEF_STAR)
1015fprintf(stderr, " stararg");
1016if (flags & DEF_DOUBLESTAR)
1017fprintf(stderr, " starstar");
1018if (flags & DEF_INTUPLE)
1019fprintf(stderr, " tuple");
1020if (flags & DEF_FREE)
1021fprintf(stderr, " free");
1022if (flags & DEF_FREE_GLOBAL)
1023fprintf(stderr, " global");
1024if (flags & DEF_FREE_CLASS)
1025fprintf(stderr, " free/class");
1026if (flags & DEF_IMPORT)
1027fprintf(stderr, " import");
1028fprintf(stderr, "\n");
1029}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030 fprintf(stderr, "\n");
1031}
1032*/
1033
1034static void
1035compiler_unit_check(struct compiler_unit *u)
1036{
1037 basicblock *block;
1038 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1039 assert(block != (void *)0xcbcbcbcb);
1040 assert(block != (void *)0xfbfbfbfb);
1041 assert(block != (void *)0xdbdbdbdb);
1042 if (block->b_instr != NULL) {
1043 assert(block->b_ialloc > 0);
1044 assert(block->b_iused > 0);
1045 assert(block->b_ialloc >= block->b_iused);
1046 }
1047 else {
1048 assert (block->b_iused == 0);
1049 assert (block->b_ialloc == 0);
1050 }
1051 }
1052}
1053
1054static void
1055compiler_unit_free(struct compiler_unit *u)
1056{
1057 basicblock *b, *next;
1058
1059 compiler_unit_check(u);
1060 b = u->u_blocks;
1061 while (b != NULL) {
1062 if (b->b_instr)
1063 PyObject_Free((void *)b->b_instr);
1064 next = b->b_list;
1065 PyObject_Free((void *)b);
1066 b = next;
1067 }
1068 Py_XDECREF(u->u_ste);
1069 Py_XDECREF(u->u_name);
1070 Py_XDECREF(u->u_consts);
1071 Py_XDECREF(u->u_names);
1072 Py_XDECREF(u->u_varnames);
1073 Py_XDECREF(u->u_freevars);
1074 Py_XDECREF(u->u_cellvars);
1075 Py_XDECREF(u->u_private);
1076 PyObject_Free(u);
1077}
1078
1079static int
1080compiler_enter_scope(struct compiler *c, identifier name, void *key,
1081 int lineno)
1082{
1083 struct compiler_unit *u;
1084
1085 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001086 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001087 PyErr_NoMemory();
1088 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001089 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001090 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091 u->u_argcount = 0;
1092 u->u_ste = PySymtable_Lookup(c->c_st, key);
1093 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001094 compiler_unit_free(u);
1095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096 }
1097 Py_INCREF(name);
1098 u->u_name = name;
1099 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1100 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1101 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001102 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
1104 u->u_blocks = NULL;
1105 u->u_tmpname = 0;
1106 u->u_nfblocks = 0;
1107 u->u_firstlineno = lineno;
1108 u->u_lineno = 0;
1109 u->u_lineno_set = false;
1110 u->u_consts = PyDict_New();
1111 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 return 0;
1114 }
1115 u->u_names = PyDict_New();
1116 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001117 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 return 0;
1119 }
1120
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001121 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122
1123 /* Push the old compiler_unit on the stack. */
1124 if (c->u) {
1125 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1126 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001127 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 return 0;
1129 }
1130 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001131 u->u_private = c->u->u_private;
1132 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 }
1134 c->u = u;
1135
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001136 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001137 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return 0;
1139
1140 return 1;
1141}
1142
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001143static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144compiler_exit_scope(struct compiler *c)
1145{
1146 int n;
1147 PyObject *wrapper;
1148
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001149 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 compiler_unit_free(c->u);
1151 /* Restore c->u to the parent unit. */
1152 n = PyList_GET_SIZE(c->c_stack) - 1;
1153 if (n >= 0) {
1154 wrapper = PyList_GET_ITEM(c->c_stack, n);
1155 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001156 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001158 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 compiler_unit_check(c->u);
1160 }
1161 else
1162 c->u = NULL;
1163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Guido van Rossumc2e20742006-02-27 22:32:47 +00001166/* Allocate a new "anonymous" local variable.
1167 Used by list comprehensions and with statements.
1168*/
1169
1170static PyObject *
1171compiler_new_tmpname(struct compiler *c)
1172{
1173 char tmpname[256];
1174 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1175 return PyString_FromString(tmpname);
1176}
1177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178/* Allocate a new block and return a pointer to it.
1179 Returns NULL on error.
1180*/
1181
1182static basicblock *
1183compiler_new_block(struct compiler *c)
1184{
1185 basicblock *b;
1186 struct compiler_unit *u;
1187
1188 u = c->u;
1189 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001190 if (b == NULL) {
1191 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001193 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 memset((void *)b, 0, sizeof(basicblock));
1195 assert (b->b_next == NULL);
1196 b->b_list = u->u_blocks;
1197 u->u_blocks = b;
1198 return b;
1199}
1200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201static basicblock *
1202compiler_use_new_block(struct compiler *c)
1203{
1204 basicblock *block = compiler_new_block(c);
1205 if (block == NULL)
1206 return NULL;
1207 c->u->u_curblock = block;
1208 return block;
1209}
1210
1211static basicblock *
1212compiler_next_block(struct compiler *c)
1213{
1214 basicblock *block = compiler_new_block(c);
1215 if (block == NULL)
1216 return NULL;
1217 c->u->u_curblock->b_next = block;
1218 c->u->u_curblock = block;
1219 return block;
1220}
1221
1222static basicblock *
1223compiler_use_next_block(struct compiler *c, basicblock *block)
1224{
1225 assert(block != NULL);
1226 c->u->u_curblock->b_next = block;
1227 c->u->u_curblock = block;
1228 return block;
1229}
1230
1231/* Returns the offset of the next instruction in the current block's
1232 b_instr array. Resizes the b_instr as necessary.
1233 Returns -1 on failure.
1234 */
1235
1236static int
1237compiler_next_instr(struct compiler *c, basicblock *b)
1238{
1239 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001240 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1242 DEFAULT_BLOCK_SIZE);
1243 if (b->b_instr == NULL) {
1244 PyErr_NoMemory();
1245 return -1;
1246 }
1247 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1248 memset((char *)b->b_instr, 0,
1249 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251 else if (b->b_iused == b->b_ialloc) {
1252 size_t oldsize, newsize;
1253 oldsize = b->b_ialloc * sizeof(struct instr);
1254 newsize = oldsize << 1;
1255 if (newsize == 0) {
1256 PyErr_NoMemory();
1257 return -1;
1258 }
1259 b->b_ialloc <<= 1;
1260 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1261 if (b->b_instr == NULL)
1262 return -1;
1263 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1264 }
1265 return b->b_iused++;
1266}
1267
1268static void
1269compiler_set_lineno(struct compiler *c, int off)
1270{
1271 basicblock *b;
1272 if (c->u->u_lineno_set)
1273 return;
1274 c->u->u_lineno_set = true;
1275 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001276 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279static int
1280opcode_stack_effect(int opcode, int oparg)
1281{
1282 switch (opcode) {
1283 case POP_TOP:
1284 return -1;
1285 case ROT_TWO:
1286 case ROT_THREE:
1287 return 0;
1288 case DUP_TOP:
1289 return 1;
1290 case ROT_FOUR:
1291 return 0;
1292
1293 case UNARY_POSITIVE:
1294 case UNARY_NEGATIVE:
1295 case UNARY_NOT:
1296 case UNARY_CONVERT:
1297 case UNARY_INVERT:
1298 return 0;
1299
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001300 case LIST_APPEND:
1301 return -2;
1302
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001303 case BINARY_POWER:
1304 case BINARY_MULTIPLY:
1305 case BINARY_DIVIDE:
1306 case BINARY_MODULO:
1307 case BINARY_ADD:
1308 case BINARY_SUBTRACT:
1309 case BINARY_SUBSCR:
1310 case BINARY_FLOOR_DIVIDE:
1311 case BINARY_TRUE_DIVIDE:
1312 return -1;
1313 case INPLACE_FLOOR_DIVIDE:
1314 case INPLACE_TRUE_DIVIDE:
1315 return -1;
1316
1317 case SLICE+0:
1318 return 1;
1319 case SLICE+1:
1320 return 0;
1321 case SLICE+2:
1322 return 0;
1323 case SLICE+3:
1324 return -1;
1325
1326 case STORE_SLICE+0:
1327 return -2;
1328 case STORE_SLICE+1:
1329 return -3;
1330 case STORE_SLICE+2:
1331 return -3;
1332 case STORE_SLICE+3:
1333 return -4;
1334
1335 case DELETE_SLICE+0:
1336 return -1;
1337 case DELETE_SLICE+1:
1338 return -2;
1339 case DELETE_SLICE+2:
1340 return -2;
1341 case DELETE_SLICE+3:
1342 return -3;
1343
1344 case INPLACE_ADD:
1345 case INPLACE_SUBTRACT:
1346 case INPLACE_MULTIPLY:
1347 case INPLACE_DIVIDE:
1348 case INPLACE_MODULO:
1349 return -1;
1350 case STORE_SUBSCR:
1351 return -3;
1352 case DELETE_SUBSCR:
1353 return -2;
1354
1355 case BINARY_LSHIFT:
1356 case BINARY_RSHIFT:
1357 case BINARY_AND:
1358 case BINARY_XOR:
1359 case BINARY_OR:
1360 return -1;
1361 case INPLACE_POWER:
1362 return -1;
1363 case GET_ITER:
1364 return 0;
1365
1366 case PRINT_EXPR:
1367 return -1;
1368 case PRINT_ITEM:
1369 return -1;
1370 case PRINT_NEWLINE:
1371 return 0;
1372 case PRINT_ITEM_TO:
1373 return -2;
1374 case PRINT_NEWLINE_TO:
1375 return -1;
1376 case INPLACE_LSHIFT:
1377 case INPLACE_RSHIFT:
1378 case INPLACE_AND:
1379 case INPLACE_XOR:
1380 case INPLACE_OR:
1381 return -1;
1382 case BREAK_LOOP:
1383 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001384 case WITH_CLEANUP:
1385 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 case LOAD_LOCALS:
1387 return 1;
1388 case RETURN_VALUE:
1389 return -1;
1390 case IMPORT_STAR:
1391 return -1;
1392 case EXEC_STMT:
1393 return -3;
1394 case YIELD_VALUE:
1395 return 0;
1396
1397 case POP_BLOCK:
1398 return 0;
1399 case END_FINALLY:
1400 return -1; /* or -2 or -3 if exception occurred */
1401 case BUILD_CLASS:
1402 return -2;
1403
1404 case STORE_NAME:
1405 return -1;
1406 case DELETE_NAME:
1407 return 0;
1408 case UNPACK_SEQUENCE:
1409 return oparg-1;
1410 case FOR_ITER:
1411 return 1;
1412
1413 case STORE_ATTR:
1414 return -2;
1415 case DELETE_ATTR:
1416 return -1;
1417 case STORE_GLOBAL:
1418 return -1;
1419 case DELETE_GLOBAL:
1420 return 0;
1421 case DUP_TOPX:
1422 return oparg;
1423 case LOAD_CONST:
1424 return 1;
1425 case LOAD_NAME:
1426 return 1;
1427 case BUILD_TUPLE:
1428 case BUILD_LIST:
1429 return 1-oparg;
1430 case BUILD_MAP:
1431 return 1;
1432 case LOAD_ATTR:
1433 return 0;
1434 case COMPARE_OP:
1435 return -1;
1436 case IMPORT_NAME:
1437 return 0;
1438 case IMPORT_FROM:
1439 return 1;
1440
1441 case JUMP_FORWARD:
1442 case JUMP_IF_FALSE:
1443 case JUMP_IF_TRUE:
1444 case JUMP_ABSOLUTE:
1445 return 0;
1446
1447 case LOAD_GLOBAL:
1448 return 1;
1449
1450 case CONTINUE_LOOP:
1451 return 0;
1452 case SETUP_LOOP:
1453 return 0;
1454 case SETUP_EXCEPT:
1455 case SETUP_FINALLY:
1456 return 3; /* actually pushed by an exception */
1457
1458 case LOAD_FAST:
1459 return 1;
1460 case STORE_FAST:
1461 return -1;
1462 case DELETE_FAST:
1463 return 0;
1464
1465 case RAISE_VARARGS:
1466 return -oparg;
1467#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1468 case CALL_FUNCTION:
1469 return -NARGS(oparg);
1470 case CALL_FUNCTION_VAR:
1471 case CALL_FUNCTION_KW:
1472 return -NARGS(oparg)-1;
1473 case CALL_FUNCTION_VAR_KW:
1474 return -NARGS(oparg)-2;
1475#undef NARGS
1476 case MAKE_FUNCTION:
1477 return -oparg;
1478 case BUILD_SLICE:
1479 if (oparg == 3)
1480 return -2;
1481 else
1482 return -1;
1483
1484 case MAKE_CLOSURE:
1485 return -oparg;
1486 case LOAD_CLOSURE:
1487 return 1;
1488 case LOAD_DEREF:
1489 return 1;
1490 case STORE_DEREF:
1491 return -1;
1492 default:
1493 fprintf(stderr, "opcode = %d\n", opcode);
1494 Py_FatalError("opcode_stack_effect()");
1495
1496 }
1497 return 0; /* not reachable */
1498}
1499
1500/* Add an opcode with no argument.
1501 Returns 0 on failure, 1 on success.
1502*/
1503
1504static int
1505compiler_addop(struct compiler *c, int opcode)
1506{
1507 basicblock *b;
1508 struct instr *i;
1509 int off;
1510 off = compiler_next_instr(c, c->u->u_curblock);
1511 if (off < 0)
1512 return 0;
1513 b = c->u->u_curblock;
1514 i = &b->b_instr[off];
1515 i->i_opcode = opcode;
1516 i->i_hasarg = 0;
1517 if (opcode == RETURN_VALUE)
1518 b->b_return = 1;
1519 compiler_set_lineno(c, off);
1520 return 1;
1521}
1522
1523static int
1524compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1525{
1526 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001529 /* necessary to make sure types aren't coerced (e.g., int and long) */
1530 t = PyTuple_Pack(2, o, o->ob_type);
1531 if (t == NULL)
1532 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533
1534 v = PyDict_GetItem(dict, t);
1535 if (!v) {
1536 arg = PyDict_Size(dict);
1537 v = PyInt_FromLong(arg);
1538 if (!v) {
1539 Py_DECREF(t);
1540 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001541 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542 if (PyDict_SetItem(dict, t, v) < 0) {
1543 Py_DECREF(t);
1544 Py_DECREF(v);
1545 return -1;
1546 }
1547 Py_DECREF(v);
1548 }
1549 else
1550 arg = PyInt_AsLong(v);
1551 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001552 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001553}
1554
1555static int
1556compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1557 PyObject *o)
1558{
1559 int arg = compiler_add_o(c, dict, o);
1560 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562 return compiler_addop_i(c, opcode, arg);
1563}
1564
1565static int
1566compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001567 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001568{
1569 int arg;
1570 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1571 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001572 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573 arg = compiler_add_o(c, dict, mangled);
1574 Py_DECREF(mangled);
1575 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001576 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577 return compiler_addop_i(c, opcode, arg);
1578}
1579
1580/* Add an opcode with an integer argument.
1581 Returns 0 on failure, 1 on success.
1582*/
1583
1584static int
1585compiler_addop_i(struct compiler *c, int opcode, int oparg)
1586{
1587 struct instr *i;
1588 int off;
1589 off = compiler_next_instr(c, c->u->u_curblock);
1590 if (off < 0)
1591 return 0;
1592 i = &c->u->u_curblock->b_instr[off];
1593 i->i_opcode = opcode;
1594 i->i_oparg = oparg;
1595 i->i_hasarg = 1;
1596 compiler_set_lineno(c, off);
1597 return 1;
1598}
1599
1600static int
1601compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1602{
1603 struct instr *i;
1604 int off;
1605
1606 assert(b != NULL);
1607 off = compiler_next_instr(c, c->u->u_curblock);
1608 if (off < 0)
1609 return 0;
1610 compiler_set_lineno(c, off);
1611 i = &c->u->u_curblock->b_instr[off];
1612 i->i_opcode = opcode;
1613 i->i_target = b;
1614 i->i_hasarg = 1;
1615 if (absolute)
1616 i->i_jabs = 1;
1617 else
1618 i->i_jrel = 1;
1619 return 1;
1620}
1621
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001622/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1623 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624 it as the current block. NEXT_BLOCK() also creates an implicit jump
1625 from the current block to the new block.
1626*/
1627
1628/* XXX The returns inside these macros make it impossible to decref
1629 objects created in the local function.
1630*/
1631
1632
1633#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001634 if (compiler_use_new_block((C)) == NULL) \
1635 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636}
1637
1638#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001639 if (compiler_next_block((C)) == NULL) \
1640 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641}
1642
1643#define ADDOP(C, OP) { \
1644 if (!compiler_addop((C), (OP))) \
1645 return 0; \
1646}
1647
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001648#define ADDOP_IN_SCOPE(C, OP) { \
1649 if (!compiler_addop((C), (OP))) { \
1650 compiler_exit_scope(c); \
1651 return 0; \
1652 } \
1653}
1654
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655#define ADDOP_O(C, OP, O, TYPE) { \
1656 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1657 return 0; \
1658}
1659
1660#define ADDOP_NAME(C, OP, O, TYPE) { \
1661 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1662 return 0; \
1663}
1664
1665#define ADDOP_I(C, OP, O) { \
1666 if (!compiler_addop_i((C), (OP), (O))) \
1667 return 0; \
1668}
1669
1670#define ADDOP_JABS(C, OP, O) { \
1671 if (!compiler_addop_j((C), (OP), (O), 1)) \
1672 return 0; \
1673}
1674
1675#define ADDOP_JREL(C, OP, O) { \
1676 if (!compiler_addop_j((C), (OP), (O), 0)) \
1677 return 0; \
1678}
1679
1680/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1681 the ASDL name to synthesize the name of the C type and the visit function.
1682*/
1683
1684#define VISIT(C, TYPE, V) {\
1685 if (!compiler_visit_ ## TYPE((C), (V))) \
1686 return 0; \
1687}
1688
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001689#define VISIT_IN_SCOPE(C, TYPE, V) {\
1690 if (!compiler_visit_ ## TYPE((C), (V))) { \
1691 compiler_exit_scope(c); \
1692 return 0; \
1693 } \
1694}
1695
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696#define VISIT_SLICE(C, V, CTX) {\
1697 if (!compiler_visit_slice((C), (V), (CTX))) \
1698 return 0; \
1699}
1700
1701#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001702 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001704 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1705 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 if (!compiler_visit_ ## TYPE((C), elt)) \
1707 return 0; \
1708 } \
1709}
1710
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001711#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001712 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001713 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001714 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1715 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001716 if (!compiler_visit_ ## TYPE((C), elt)) { \
1717 compiler_exit_scope(c); \
1718 return 0; \
1719 } \
1720 } \
1721}
1722
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723static int
1724compiler_isdocstring(stmt_ty s)
1725{
1726 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001727 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001728 return s->v.Expr.value->kind == Str_kind;
1729}
1730
1731/* Compile a sequence of statements, checking for a docstring. */
1732
1733static int
1734compiler_body(struct compiler *c, asdl_seq *stmts)
1735{
1736 int i = 0;
1737 stmt_ty st;
1738
1739 if (!asdl_seq_LEN(stmts))
1740 return 1;
1741 st = asdl_seq_GET(stmts, 0);
1742 if (compiler_isdocstring(st)) {
1743 i = 1;
1744 VISIT(c, expr, st->v.Expr.value);
1745 if (!compiler_nameop(c, __doc__, Store))
1746 return 0;
1747 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001748 for (; i < asdl_seq_LEN(stmts); i++)
1749 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750 return 1;
1751}
1752
1753static PyCodeObject *
1754compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001755{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001756 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001757 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001758 static PyObject *module;
1759 if (!module) {
1760 module = PyString_FromString("<module>");
1761 if (!module)
1762 return NULL;
1763 }
1764 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001765 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 switch (mod->kind) {
1767 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001768 if (!compiler_body(c, mod->v.Module.body)) {
1769 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001771 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 break;
1773 case Interactive_kind:
1774 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001775 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 break;
1777 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001778 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001779 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 break;
1781 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001782 PyErr_SetString(PyExc_SystemError,
1783 "suite should not be possible");
1784 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001785 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001786 PyErr_Format(PyExc_SystemError,
1787 "module kind %d should not be possible",
1788 mod->kind);
1789 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 co = assemble(c, addNone);
1792 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001793 return co;
1794}
1795
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001796/* The test for LOCAL must come before the test for FREE in order to
1797 handle classes where name is both local and free. The local var is
1798 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001799*/
1800
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801static int
1802get_ref_type(struct compiler *c, PyObject *name)
1803{
1804 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001805 if (scope == 0) {
1806 char buf[350];
1807 PyOS_snprintf(buf, sizeof(buf),
1808 "unknown scope for %.100s in %.100s(%s) in %s\n"
1809 "symbols: %s\nlocals: %s\nglobals: %s\n",
1810 PyString_AS_STRING(name),
1811 PyString_AS_STRING(c->u->u_name),
1812 PyObject_REPR(c->u->u_ste->ste_id),
1813 c->c_filename,
1814 PyObject_REPR(c->u->u_ste->ste_symbols),
1815 PyObject_REPR(c->u->u_varnames),
1816 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001818 Py_FatalError(buf);
1819 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001820
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001821 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822}
1823
1824static int
1825compiler_lookup_arg(PyObject *dict, PyObject *name)
1826{
1827 PyObject *k, *v;
1828 k = Py_BuildValue("(OO)", name, name->ob_type);
1829 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001830 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001832 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001834 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001835 return PyInt_AS_LONG(v);
1836}
1837
1838static int
1839compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1840{
1841 int i, free = PyCode_GetNumFree(co);
1842 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001843 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1844 ADDOP_I(c, MAKE_FUNCTION, args);
1845 return 1;
1846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001847 for (i = 0; i < free; ++i) {
1848 /* Bypass com_addop_varname because it will generate
1849 LOAD_DEREF but LOAD_CLOSURE is needed.
1850 */
1851 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1852 int arg, reftype;
1853
1854 /* Special case: If a class contains a method with a
1855 free variable that has the same name as a method,
1856 the name will be considered free *and* local in the
1857 class. It should be handled by the closure, as
1858 well as by the normal name loookup logic.
1859 */
1860 reftype = get_ref_type(c, name);
1861 if (reftype == CELL)
1862 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1863 else /* (reftype == FREE) */
1864 arg = compiler_lookup_arg(c->u->u_freevars, name);
1865 if (arg == -1) {
1866 printf("lookup %s in %s %d %d\n"
1867 "freevars of %s: %s\n",
1868 PyObject_REPR(name),
1869 PyString_AS_STRING(c->u->u_name),
1870 reftype, arg,
1871 PyString_AS_STRING(co->co_name),
1872 PyObject_REPR(co->co_freevars));
1873 Py_FatalError("compiler_make_closure()");
1874 }
1875 ADDOP_I(c, LOAD_CLOSURE, arg);
1876 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001877 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001879 ADDOP_I(c, MAKE_CLOSURE, args);
1880 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881}
1882
1883static int
1884compiler_decorators(struct compiler *c, asdl_seq* decos)
1885{
1886 int i;
1887
1888 if (!decos)
1889 return 1;
1890
1891 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1892 VISIT(c, expr, asdl_seq_GET(decos, i));
1893 }
1894 return 1;
1895}
1896
1897static int
1898compiler_arguments(struct compiler *c, arguments_ty args)
1899{
1900 int i;
1901 int n = asdl_seq_LEN(args->args);
1902 /* Correctly handle nested argument lists */
1903 for (i = 0; i < n; i++) {
1904 expr_ty arg = asdl_seq_GET(args->args, i);
1905 if (arg->kind == Tuple_kind) {
1906 PyObject *id = PyString_FromFormat(".%d", i);
1907 if (id == NULL) {
1908 return 0;
1909 }
1910 if (!compiler_nameop(c, id, Load)) {
1911 Py_DECREF(id);
1912 return 0;
1913 }
1914 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001915 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 }
1917 }
1918 return 1;
1919}
1920
1921static int
1922compiler_function(struct compiler *c, stmt_ty s)
1923{
1924 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001925 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 arguments_ty args = s->v.FunctionDef.args;
1927 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001928 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929 int i, n, docstring;
1930
1931 assert(s->kind == FunctionDef_kind);
1932
1933 if (!compiler_decorators(c, decos))
1934 return 0;
1935 if (args->defaults)
1936 VISIT_SEQ(c, expr, args->defaults);
1937 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1938 s->lineno))
1939 return 0;
1940
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001941 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1942 docstring = compiler_isdocstring(st);
1943 if (docstring)
1944 first_const = st->v.Expr.value->v.Str.s;
1945 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001946 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001947 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001948 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001950 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 compiler_arguments(c, args);
1952
1953 c->u->u_argcount = asdl_seq_LEN(args->args);
1954 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001955 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 for (i = docstring; i < n; i++) {
1957 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1958 if (i == 0 && s2->kind == Expr_kind &&
1959 s2->v.Expr.value->kind == Str_kind)
1960 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001961 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 }
1963 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001964 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001965 if (co == NULL)
1966 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001968 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001969 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970
1971 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1972 ADDOP_I(c, CALL_FUNCTION, 1);
1973 }
1974
1975 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1976}
1977
1978static int
1979compiler_class(struct compiler *c, stmt_ty s)
1980{
1981 int n;
1982 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001983 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984 /* push class name on stack, needed by BUILD_CLASS */
1985 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1986 /* push the tuple of base classes on the stack */
1987 n = asdl_seq_LEN(s->v.ClassDef.bases);
1988 if (n > 0)
1989 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1990 ADDOP_I(c, BUILD_TUPLE, n);
1991 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1992 s->lineno))
1993 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001994 c->u->u_private = s->v.ClassDef.name;
1995 Py_INCREF(c->u->u_private);
1996 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 if (!str || !compiler_nameop(c, str, Load)) {
1998 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001999 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002000 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002001 }
2002
2003 Py_DECREF(str);
2004 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 if (!str || !compiler_nameop(c, str, Store)) {
2006 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002007 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002009 }
2010 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002012 if (!compiler_body(c, s->v.ClassDef.body)) {
2013 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002015 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002017 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2018 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002019 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002020 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 if (co == NULL)
2022 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002024 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002025 Py_DECREF(co);
2026
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027 ADDOP_I(c, CALL_FUNCTION, 0);
2028 ADDOP(c, BUILD_CLASS);
2029 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2030 return 0;
2031 return 1;
2032}
2033
2034static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002035compiler_ifexp(struct compiler *c, expr_ty e)
2036{
2037 basicblock *end, *next;
2038
2039 assert(e->kind == IfExp_kind);
2040 end = compiler_new_block(c);
2041 if (end == NULL)
2042 return 0;
2043 next = compiler_new_block(c);
2044 if (next == NULL)
2045 return 0;
2046 VISIT(c, expr, e->v.IfExp.test);
2047 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2048 ADDOP(c, POP_TOP);
2049 VISIT(c, expr, e->v.IfExp.body);
2050 ADDOP_JREL(c, JUMP_FORWARD, end);
2051 compiler_use_next_block(c, next);
2052 ADDOP(c, POP_TOP);
2053 VISIT(c, expr, e->v.IfExp.orelse);
2054 compiler_use_next_block(c, end);
2055 return 1;
2056}
2057
2058static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002059compiler_lambda(struct compiler *c, expr_ty e)
2060{
2061 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002062 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063 arguments_ty args = e->v.Lambda.args;
2064 assert(e->kind == Lambda_kind);
2065
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002066 if (!name) {
2067 name = PyString_InternFromString("<lambda>");
2068 if (!name)
2069 return 0;
2070 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071
2072 if (args->defaults)
2073 VISIT_SEQ(c, expr, args->defaults);
2074 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2075 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002076
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002077 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 compiler_arguments(c, args);
2079
2080 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002081 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2082 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002084 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 if (co == NULL)
2086 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002088 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002089 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090
2091 return 1;
2092}
2093
2094static int
2095compiler_print(struct compiler *c, stmt_ty s)
2096{
2097 int i, n;
2098 bool dest;
2099
2100 assert(s->kind == Print_kind);
2101 n = asdl_seq_LEN(s->v.Print.values);
2102 dest = false;
2103 if (s->v.Print.dest) {
2104 VISIT(c, expr, s->v.Print.dest);
2105 dest = true;
2106 }
2107 for (i = 0; i < n; i++) {
2108 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2109 if (dest) {
2110 ADDOP(c, DUP_TOP);
2111 VISIT(c, expr, e);
2112 ADDOP(c, ROT_TWO);
2113 ADDOP(c, PRINT_ITEM_TO);
2114 }
2115 else {
2116 VISIT(c, expr, e);
2117 ADDOP(c, PRINT_ITEM);
2118 }
2119 }
2120 if (s->v.Print.nl) {
2121 if (dest)
2122 ADDOP(c, PRINT_NEWLINE_TO)
2123 else
2124 ADDOP(c, PRINT_NEWLINE)
2125 }
2126 else if (dest)
2127 ADDOP(c, POP_TOP);
2128 return 1;
2129}
2130
2131static int
2132compiler_if(struct compiler *c, stmt_ty s)
2133{
2134 basicblock *end, *next;
2135
2136 assert(s->kind == If_kind);
2137 end = compiler_new_block(c);
2138 if (end == NULL)
2139 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002140 next = compiler_new_block(c);
2141 if (next == NULL)
2142 return 0;
2143 VISIT(c, expr, s->v.If.test);
2144 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2145 ADDOP(c, POP_TOP);
2146 VISIT_SEQ(c, stmt, s->v.If.body);
2147 ADDOP_JREL(c, JUMP_FORWARD, end);
2148 compiler_use_next_block(c, next);
2149 ADDOP(c, POP_TOP);
2150 if (s->v.If.orelse)
2151 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152 compiler_use_next_block(c, end);
2153 return 1;
2154}
2155
2156static int
2157compiler_for(struct compiler *c, stmt_ty s)
2158{
2159 basicblock *start, *cleanup, *end;
2160
2161 start = compiler_new_block(c);
2162 cleanup = compiler_new_block(c);
2163 end = compiler_new_block(c);
2164 if (start == NULL || end == NULL || cleanup == NULL)
2165 return 0;
2166 ADDOP_JREL(c, SETUP_LOOP, end);
2167 if (!compiler_push_fblock(c, LOOP, start))
2168 return 0;
2169 VISIT(c, expr, s->v.For.iter);
2170 ADDOP(c, GET_ITER);
2171 compiler_use_next_block(c, start);
2172 ADDOP_JREL(c, FOR_ITER, cleanup);
2173 VISIT(c, expr, s->v.For.target);
2174 VISIT_SEQ(c, stmt, s->v.For.body);
2175 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2176 compiler_use_next_block(c, cleanup);
2177 ADDOP(c, POP_BLOCK);
2178 compiler_pop_fblock(c, LOOP, start);
2179 VISIT_SEQ(c, stmt, s->v.For.orelse);
2180 compiler_use_next_block(c, end);
2181 return 1;
2182}
2183
2184static int
2185compiler_while(struct compiler *c, stmt_ty s)
2186{
2187 basicblock *loop, *orelse, *end, *anchor = NULL;
2188 int constant = expr_constant(s->v.While.test);
2189
2190 if (constant == 0)
2191 return 1;
2192 loop = compiler_new_block(c);
2193 end = compiler_new_block(c);
2194 if (constant == -1) {
2195 anchor = compiler_new_block(c);
2196 if (anchor == NULL)
2197 return 0;
2198 }
2199 if (loop == NULL || end == NULL)
2200 return 0;
2201 if (s->v.While.orelse) {
2202 orelse = compiler_new_block(c);
2203 if (orelse == NULL)
2204 return 0;
2205 }
2206 else
2207 orelse = NULL;
2208
2209 ADDOP_JREL(c, SETUP_LOOP, end);
2210 compiler_use_next_block(c, loop);
2211 if (!compiler_push_fblock(c, LOOP, loop))
2212 return 0;
2213 if (constant == -1) {
2214 VISIT(c, expr, s->v.While.test);
2215 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2216 ADDOP(c, POP_TOP);
2217 }
2218 VISIT_SEQ(c, stmt, s->v.While.body);
2219 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2220
2221 /* XXX should the two POP instructions be in a separate block
2222 if there is no else clause ?
2223 */
2224
2225 if (constant == -1) {
2226 compiler_use_next_block(c, anchor);
2227 ADDOP(c, POP_TOP);
2228 ADDOP(c, POP_BLOCK);
2229 }
2230 compiler_pop_fblock(c, LOOP, loop);
2231 if (orelse != NULL)
2232 VISIT_SEQ(c, stmt, s->v.While.orelse);
2233 compiler_use_next_block(c, end);
2234
2235 return 1;
2236}
2237
2238static int
2239compiler_continue(struct compiler *c)
2240{
2241 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2242 int i;
2243
2244 if (!c->u->u_nfblocks)
2245 return compiler_error(c, LOOP_ERROR_MSG);
2246 i = c->u->u_nfblocks - 1;
2247 switch (c->u->u_fblock[i].fb_type) {
2248 case LOOP:
2249 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2250 break;
2251 case EXCEPT:
2252 case FINALLY_TRY:
2253 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2254 ;
2255 if (i == -1)
2256 return compiler_error(c, LOOP_ERROR_MSG);
2257 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2258 break;
2259 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002260 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 "'continue' not supported inside 'finally' clause");
2262 }
2263
2264 return 1;
2265}
2266
2267/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2268
2269 SETUP_FINALLY L
2270 <code for body>
2271 POP_BLOCK
2272 LOAD_CONST <None>
2273 L: <code for finalbody>
2274 END_FINALLY
2275
2276 The special instructions use the block stack. Each block
2277 stack entry contains the instruction that created it (here
2278 SETUP_FINALLY), the level of the value stack at the time the
2279 block stack entry was created, and a label (here L).
2280
2281 SETUP_FINALLY:
2282 Pushes the current value stack level and the label
2283 onto the block stack.
2284 POP_BLOCK:
2285 Pops en entry from the block stack, and pops the value
2286 stack until its level is the same as indicated on the
2287 block stack. (The label is ignored.)
2288 END_FINALLY:
2289 Pops a variable number of entries from the *value* stack
2290 and re-raises the exception they specify. The number of
2291 entries popped depends on the (pseudo) exception type.
2292
2293 The block stack is unwound when an exception is raised:
2294 when a SETUP_FINALLY entry is found, the exception is pushed
2295 onto the value stack (and the exception condition is cleared),
2296 and the interpreter jumps to the label gotten from the block
2297 stack.
2298*/
2299
2300static int
2301compiler_try_finally(struct compiler *c, stmt_ty s)
2302{
2303 basicblock *body, *end;
2304 body = compiler_new_block(c);
2305 end = compiler_new_block(c);
2306 if (body == NULL || end == NULL)
2307 return 0;
2308
2309 ADDOP_JREL(c, SETUP_FINALLY, end);
2310 compiler_use_next_block(c, body);
2311 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2312 return 0;
2313 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2314 ADDOP(c, POP_BLOCK);
2315 compiler_pop_fblock(c, FINALLY_TRY, body);
2316
2317 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2318 compiler_use_next_block(c, end);
2319 if (!compiler_push_fblock(c, FINALLY_END, end))
2320 return 0;
2321 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2322 ADDOP(c, END_FINALLY);
2323 compiler_pop_fblock(c, FINALLY_END, end);
2324
2325 return 1;
2326}
2327
2328/*
2329 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2330 (The contents of the value stack is shown in [], with the top
2331 at the right; 'tb' is trace-back info, 'val' the exception's
2332 associated value, and 'exc' the exception.)
2333
2334 Value stack Label Instruction Argument
2335 [] SETUP_EXCEPT L1
2336 [] <code for S>
2337 [] POP_BLOCK
2338 [] JUMP_FORWARD L0
2339
2340 [tb, val, exc] L1: DUP )
2341 [tb, val, exc, exc] <evaluate E1> )
2342 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2343 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2344 [tb, val, exc, 1] POP )
2345 [tb, val, exc] POP
2346 [tb, val] <assign to V1> (or POP if no V1)
2347 [tb] POP
2348 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002349 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350
2351 [tb, val, exc, 0] L2: POP
2352 [tb, val, exc] DUP
2353 .............................etc.......................
2354
2355 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002356 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357
2358 [] L0: <next statement>
2359
2360 Of course, parts are not generated if Vi or Ei is not present.
2361*/
2362static int
2363compiler_try_except(struct compiler *c, stmt_ty s)
2364{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002365 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366 int i, n;
2367
2368 body = compiler_new_block(c);
2369 except = compiler_new_block(c);
2370 orelse = compiler_new_block(c);
2371 end = compiler_new_block(c);
2372 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2373 return 0;
2374 ADDOP_JREL(c, SETUP_EXCEPT, except);
2375 compiler_use_next_block(c, body);
2376 if (!compiler_push_fblock(c, EXCEPT, body))
2377 return 0;
2378 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2379 ADDOP(c, POP_BLOCK);
2380 compiler_pop_fblock(c, EXCEPT, body);
2381 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2382 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2383 compiler_use_next_block(c, except);
2384 for (i = 0; i < n; i++) {
2385 excepthandler_ty handler = asdl_seq_GET(
2386 s->v.TryExcept.handlers, i);
2387 if (!handler->type && i < n-1)
2388 return compiler_error(c, "default 'except:' must be last");
2389 except = compiler_new_block(c);
2390 if (except == NULL)
2391 return 0;
2392 if (handler->type) {
2393 ADDOP(c, DUP_TOP);
2394 VISIT(c, expr, handler->type);
2395 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2396 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2397 ADDOP(c, POP_TOP);
2398 }
2399 ADDOP(c, POP_TOP);
2400 if (handler->name) {
2401 VISIT(c, expr, handler->name);
2402 }
2403 else {
2404 ADDOP(c, POP_TOP);
2405 }
2406 ADDOP(c, POP_TOP);
2407 VISIT_SEQ(c, stmt, handler->body);
2408 ADDOP_JREL(c, JUMP_FORWARD, end);
2409 compiler_use_next_block(c, except);
2410 if (handler->type)
2411 ADDOP(c, POP_TOP);
2412 }
2413 ADDOP(c, END_FINALLY);
2414 compiler_use_next_block(c, orelse);
2415 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2416 compiler_use_next_block(c, end);
2417 return 1;
2418}
2419
2420static int
2421compiler_import_as(struct compiler *c, identifier name, identifier asname)
2422{
2423 /* The IMPORT_NAME opcode was already generated. This function
2424 merely needs to bind the result to a name.
2425
2426 If there is a dot in name, we need to split it and emit a
2427 LOAD_ATTR for each name.
2428 */
2429 const char *src = PyString_AS_STRING(name);
2430 const char *dot = strchr(src, '.');
2431 if (dot) {
2432 /* Consume the base module name to get the first attribute */
2433 src = dot + 1;
2434 while (dot) {
2435 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002436 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002438 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002440 if (!attr)
2441 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002442 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002443 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002444 src = dot + 1;
2445 }
2446 }
2447 return compiler_nameop(c, asname, Store);
2448}
2449
2450static int
2451compiler_import(struct compiler *c, stmt_ty s)
2452{
2453 /* The Import node stores a module name like a.b.c as a single
2454 string. This is convenient for all cases except
2455 import a.b.c as d
2456 where we need to parse that string to extract the individual
2457 module names.
2458 XXX Perhaps change the representation to make this case simpler?
2459 */
2460 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002461
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002462 for (i = 0; i < n; i++) {
2463 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2464 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002465 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002467 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2468 level = PyInt_FromLong(0);
2469 else
2470 level = PyInt_FromLong(-1);
2471
2472 if (level == NULL)
2473 return 0;
2474
2475 ADDOP_O(c, LOAD_CONST, level, consts);
2476 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2478 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2479
2480 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002481 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002482 if (!r)
2483 return r;
2484 }
2485 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486 identifier tmp = alias->name;
2487 const char *base = PyString_AS_STRING(alias->name);
2488 char *dot = strchr(base, '.');
2489 if (dot)
2490 tmp = PyString_FromStringAndSize(base,
2491 dot - base);
2492 r = compiler_nameop(c, tmp, Store);
2493 if (dot) {
2494 Py_DECREF(tmp);
2495 }
2496 if (!r)
2497 return r;
2498 }
2499 }
2500 return 1;
2501}
2502
2503static int
2504compiler_from_import(struct compiler *c, stmt_ty s)
2505{
2506 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002507
2508 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002509 PyObject *level;
2510
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002511 if (!names)
2512 return 0;
2513
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002514 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2515 !(c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2516 level = PyInt_FromLong(-1);
2517 else
2518 level = PyInt_FromLong(s->v.ImportFrom.level);
2519
2520 if (!level) {
2521 Py_DECREF(names);
2522 return 0;
2523 }
2524
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525 /* build up the names */
2526 for (i = 0; i < n; i++) {
2527 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2528 Py_INCREF(alias->name);
2529 PyTuple_SET_ITEM(names, i, alias->name);
2530 }
2531
2532 if (s->lineno > c->c_future->ff_lineno) {
2533 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2534 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002535 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536 Py_DECREF(names);
2537 return compiler_error(c,
2538 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002539 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002540
2541 }
2542 }
2543
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002544 ADDOP_O(c, LOAD_CONST, level, consts);
2545 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002547 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002548 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2549 for (i = 0; i < n; i++) {
2550 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2551 identifier store_name;
2552
2553 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2554 assert(n == 1);
2555 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002556 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002557 }
2558
2559 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2560 store_name = alias->name;
2561 if (alias->asname)
2562 store_name = alias->asname;
2563
2564 if (!compiler_nameop(c, store_name, Store)) {
2565 Py_DECREF(names);
2566 return 0;
2567 }
2568 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002569 /* remove imported module */
2570 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002571 return 1;
2572}
2573
2574static int
2575compiler_assert(struct compiler *c, stmt_ty s)
2576{
2577 static PyObject *assertion_error = NULL;
2578 basicblock *end;
2579
2580 if (Py_OptimizeFlag)
2581 return 1;
2582 if (assertion_error == NULL) {
2583 assertion_error = PyString_FromString("AssertionError");
2584 if (assertion_error == NULL)
2585 return 0;
2586 }
2587 VISIT(c, expr, s->v.Assert.test);
2588 end = compiler_new_block(c);
2589 if (end == NULL)
2590 return 0;
2591 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2592 ADDOP(c, POP_TOP);
2593 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2594 if (s->v.Assert.msg) {
2595 VISIT(c, expr, s->v.Assert.msg);
2596 ADDOP_I(c, RAISE_VARARGS, 2);
2597 }
2598 else {
2599 ADDOP_I(c, RAISE_VARARGS, 1);
2600 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002601 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 ADDOP(c, POP_TOP);
2603 return 1;
2604}
2605
2606static int
2607compiler_visit_stmt(struct compiler *c, stmt_ty s)
2608{
2609 int i, n;
2610
2611 c->u->u_lineno = s->lineno;
2612 c->u->u_lineno_set = false;
2613 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002616 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002618 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002619 if (c->u->u_ste->ste_type != FunctionBlock)
2620 return compiler_error(c, "'return' outside function");
2621 if (s->v.Return.value) {
2622 if (c->u->u_ste->ste_generator) {
2623 return compiler_error(c,
2624 "'return' with argument inside generator");
2625 }
2626 VISIT(c, expr, s->v.Return.value);
2627 }
2628 else
2629 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2630 ADDOP(c, RETURN_VALUE);
2631 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 VISIT_SEQ(c, expr, s->v.Delete.targets)
2634 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002635 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 n = asdl_seq_LEN(s->v.Assign.targets);
2637 VISIT(c, expr, s->v.Assign.value);
2638 for (i = 0; i < n; i++) {
2639 if (i < n - 1)
2640 ADDOP(c, DUP_TOP);
2641 VISIT(c, expr,
2642 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2643 }
2644 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002645 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002653 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002654 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 n = 0;
2657 if (s->v.Raise.type) {
2658 VISIT(c, expr, s->v.Raise.type);
2659 n++;
2660 if (s->v.Raise.inst) {
2661 VISIT(c, expr, s->v.Raise.inst);
2662 n++;
2663 if (s->v.Raise.tback) {
2664 VISIT(c, expr, s->v.Raise.tback);
2665 n++;
2666 }
2667 }
2668 }
2669 ADDOP_I(c, RAISE_VARARGS, n);
2670 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002671 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002679 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002681 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 VISIT(c, expr, s->v.Exec.body);
2683 if (s->v.Exec.globals) {
2684 VISIT(c, expr, s->v.Exec.globals);
2685 if (s->v.Exec.locals) {
2686 VISIT(c, expr, s->v.Exec.locals);
2687 } else {
2688 ADDOP(c, DUP_TOP);
2689 }
2690 } else {
2691 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2692 ADDOP(c, DUP_TOP);
2693 }
2694 ADDOP(c, EXEC_STMT);
2695 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002696 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002698 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 VISIT(c, expr, s->v.Expr.value);
2700 if (c->c_interactive && c->c_nestlevel <= 1) {
2701 ADDOP(c, PRINT_EXPR);
2702 }
2703 else {
2704 ADDOP(c, POP_TOP);
2705 }
2706 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002707 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002708 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002709 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710 if (!c->u->u_nfblocks)
2711 return compiler_error(c, "'break' outside loop");
2712 ADDOP(c, BREAK_LOOP);
2713 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002714 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 case With_kind:
2717 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002718 }
2719 return 1;
2720}
2721
2722static int
2723unaryop(unaryop_ty op)
2724{
2725 switch (op) {
2726 case Invert:
2727 return UNARY_INVERT;
2728 case Not:
2729 return UNARY_NOT;
2730 case UAdd:
2731 return UNARY_POSITIVE;
2732 case USub:
2733 return UNARY_NEGATIVE;
2734 }
2735 return 0;
2736}
2737
2738static int
2739binop(struct compiler *c, operator_ty op)
2740{
2741 switch (op) {
2742 case Add:
2743 return BINARY_ADD;
2744 case Sub:
2745 return BINARY_SUBTRACT;
2746 case Mult:
2747 return BINARY_MULTIPLY;
2748 case Div:
2749 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2750 return BINARY_TRUE_DIVIDE;
2751 else
2752 return BINARY_DIVIDE;
2753 case Mod:
2754 return BINARY_MODULO;
2755 case Pow:
2756 return BINARY_POWER;
2757 case LShift:
2758 return BINARY_LSHIFT;
2759 case RShift:
2760 return BINARY_RSHIFT;
2761 case BitOr:
2762 return BINARY_OR;
2763 case BitXor:
2764 return BINARY_XOR;
2765 case BitAnd:
2766 return BINARY_AND;
2767 case FloorDiv:
2768 return BINARY_FLOOR_DIVIDE;
2769 }
2770 return 0;
2771}
2772
2773static int
2774cmpop(cmpop_ty op)
2775{
2776 switch (op) {
2777 case Eq:
2778 return PyCmp_EQ;
2779 case NotEq:
2780 return PyCmp_NE;
2781 case Lt:
2782 return PyCmp_LT;
2783 case LtE:
2784 return PyCmp_LE;
2785 case Gt:
2786 return PyCmp_GT;
2787 case GtE:
2788 return PyCmp_GE;
2789 case Is:
2790 return PyCmp_IS;
2791 case IsNot:
2792 return PyCmp_IS_NOT;
2793 case In:
2794 return PyCmp_IN;
2795 case NotIn:
2796 return PyCmp_NOT_IN;
2797 }
2798 return PyCmp_BAD;
2799}
2800
2801static int
2802inplace_binop(struct compiler *c, operator_ty op)
2803{
2804 switch (op) {
2805 case Add:
2806 return INPLACE_ADD;
2807 case Sub:
2808 return INPLACE_SUBTRACT;
2809 case Mult:
2810 return INPLACE_MULTIPLY;
2811 case Div:
2812 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2813 return INPLACE_TRUE_DIVIDE;
2814 else
2815 return INPLACE_DIVIDE;
2816 case Mod:
2817 return INPLACE_MODULO;
2818 case Pow:
2819 return INPLACE_POWER;
2820 case LShift:
2821 return INPLACE_LSHIFT;
2822 case RShift:
2823 return INPLACE_RSHIFT;
2824 case BitOr:
2825 return INPLACE_OR;
2826 case BitXor:
2827 return INPLACE_XOR;
2828 case BitAnd:
2829 return INPLACE_AND;
2830 case FloorDiv:
2831 return INPLACE_FLOOR_DIVIDE;
2832 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002833 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002834 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002835 return 0;
2836}
2837
2838static int
2839compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2840{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002841 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2843
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002844 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002845 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 /* XXX AugStore isn't used anywhere! */
2847
2848 /* First check for assignment to __debug__. Param? */
2849 if ((ctx == Store || ctx == AugStore || ctx == Del)
2850 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2851 return compiler_error(c, "can not assign to __debug__");
2852 }
2853
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002854 mangled = _Py_Mangle(c->u->u_private, name);
2855 if (!mangled)
2856 return 0;
2857
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858 op = 0;
2859 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002860 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 switch (scope) {
2862 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 optype = OP_DEREF;
2865 break;
2866 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002867 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868 optype = OP_DEREF;
2869 break;
2870 case LOCAL:
2871 if (c->u->u_ste->ste_type == FunctionBlock)
2872 optype = OP_FAST;
2873 break;
2874 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002875 if (c->u->u_ste->ste_type == FunctionBlock &&
2876 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002877 optype = OP_GLOBAL;
2878 break;
2879 case GLOBAL_EXPLICIT:
2880 optype = OP_GLOBAL;
2881 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002882 default:
2883 /* scope can be 0 */
2884 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002885 }
2886
2887 /* XXX Leave assert here, but handle __doc__ and the like better */
2888 assert(scope || PyString_AS_STRING(name)[0] == '_');
2889
2890 switch (optype) {
2891 case OP_DEREF:
2892 switch (ctx) {
2893 case Load: op = LOAD_DEREF; break;
2894 case Store: op = STORE_DEREF; break;
2895 case AugLoad:
2896 case AugStore:
2897 break;
2898 case Del:
2899 PyErr_Format(PyExc_SyntaxError,
2900 "can not delete variable '%s' referenced "
2901 "in nested scope",
2902 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002903 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002905 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002906 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002907 PyErr_SetString(PyExc_SystemError,
2908 "param invalid for deref variable");
2909 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910 }
2911 break;
2912 case OP_FAST:
2913 switch (ctx) {
2914 case Load: op = LOAD_FAST; break;
2915 case Store: op = STORE_FAST; break;
2916 case Del: op = DELETE_FAST; break;
2917 case AugLoad:
2918 case AugStore:
2919 break;
2920 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002921 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002922 PyErr_SetString(PyExc_SystemError,
2923 "param invalid for local variable");
2924 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002926 ADDOP_O(c, op, mangled, varnames);
2927 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 return 1;
2929 case OP_GLOBAL:
2930 switch (ctx) {
2931 case Load: op = LOAD_GLOBAL; break;
2932 case Store: op = STORE_GLOBAL; break;
2933 case Del: op = DELETE_GLOBAL; break;
2934 case AugLoad:
2935 case AugStore:
2936 break;
2937 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002938 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002939 PyErr_SetString(PyExc_SystemError,
2940 "param invalid for global variable");
2941 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 }
2943 break;
2944 case OP_NAME:
2945 switch (ctx) {
2946 case Load: op = LOAD_NAME; break;
2947 case Store: op = STORE_NAME; break;
2948 case Del: op = DELETE_NAME; break;
2949 case AugLoad:
2950 case AugStore:
2951 break;
2952 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002953 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002954 PyErr_SetString(PyExc_SystemError,
2955 "param invalid for name variable");
2956 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957 }
2958 break;
2959 }
2960
2961 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002962 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002963 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002964 if (arg < 0)
2965 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002966 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967}
2968
2969static int
2970compiler_boolop(struct compiler *c, expr_ty e)
2971{
2972 basicblock *end;
2973 int jumpi, i, n;
2974 asdl_seq *s;
2975
2976 assert(e->kind == BoolOp_kind);
2977 if (e->v.BoolOp.op == And)
2978 jumpi = JUMP_IF_FALSE;
2979 else
2980 jumpi = JUMP_IF_TRUE;
2981 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002982 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002983 return 0;
2984 s = e->v.BoolOp.values;
2985 n = asdl_seq_LEN(s) - 1;
2986 for (i = 0; i < n; ++i) {
2987 VISIT(c, expr, asdl_seq_GET(s, i));
2988 ADDOP_JREL(c, jumpi, end);
2989 ADDOP(c, POP_TOP)
2990 }
2991 VISIT(c, expr, asdl_seq_GET(s, n));
2992 compiler_use_next_block(c, end);
2993 return 1;
2994}
2995
2996static int
2997compiler_list(struct compiler *c, expr_ty e)
2998{
2999 int n = asdl_seq_LEN(e->v.List.elts);
3000 if (e->v.List.ctx == Store) {
3001 ADDOP_I(c, UNPACK_SEQUENCE, n);
3002 }
3003 VISIT_SEQ(c, expr, e->v.List.elts);
3004 if (e->v.List.ctx == Load) {
3005 ADDOP_I(c, BUILD_LIST, n);
3006 }
3007 return 1;
3008}
3009
3010static int
3011compiler_tuple(struct compiler *c, expr_ty e)
3012{
3013 int n = asdl_seq_LEN(e->v.Tuple.elts);
3014 if (e->v.Tuple.ctx == Store) {
3015 ADDOP_I(c, UNPACK_SEQUENCE, n);
3016 }
3017 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3018 if (e->v.Tuple.ctx == Load) {
3019 ADDOP_I(c, BUILD_TUPLE, n);
3020 }
3021 return 1;
3022}
3023
3024static int
3025compiler_compare(struct compiler *c, expr_ty e)
3026{
3027 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003028 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029
3030 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3031 VISIT(c, expr, e->v.Compare.left);
3032 n = asdl_seq_LEN(e->v.Compare.ops);
3033 assert(n > 0);
3034 if (n > 1) {
3035 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003036 if (cleanup == NULL)
3037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3039 }
3040 for (i = 1; i < n; i++) {
3041 ADDOP(c, DUP_TOP);
3042 ADDOP(c, ROT_THREE);
3043 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3044 ADDOP_I(c, COMPARE_OP,
3045 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3046 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3047 NEXT_BLOCK(c);
3048 ADDOP(c, POP_TOP);
3049 if (i < (n - 1))
3050 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3051 }
3052 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3053 ADDOP_I(c, COMPARE_OP,
3054 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3055 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3056 if (n > 1) {
3057 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003058 if (end == NULL)
3059 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060 ADDOP_JREL(c, JUMP_FORWARD, end);
3061 compiler_use_next_block(c, cleanup);
3062 ADDOP(c, ROT_TWO);
3063 ADDOP(c, POP_TOP);
3064 compiler_use_next_block(c, end);
3065 }
3066 return 1;
3067}
3068
3069static int
3070compiler_call(struct compiler *c, expr_ty e)
3071{
3072 int n, code = 0;
3073
3074 VISIT(c, expr, e->v.Call.func);
3075 n = asdl_seq_LEN(e->v.Call.args);
3076 VISIT_SEQ(c, expr, e->v.Call.args);
3077 if (e->v.Call.keywords) {
3078 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3079 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3080 }
3081 if (e->v.Call.starargs) {
3082 VISIT(c, expr, e->v.Call.starargs);
3083 code |= 1;
3084 }
3085 if (e->v.Call.kwargs) {
3086 VISIT(c, expr, e->v.Call.kwargs);
3087 code |= 2;
3088 }
3089 switch (code) {
3090 case 0:
3091 ADDOP_I(c, CALL_FUNCTION, n);
3092 break;
3093 case 1:
3094 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3095 break;
3096 case 2:
3097 ADDOP_I(c, CALL_FUNCTION_KW, n);
3098 break;
3099 case 3:
3100 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3101 break;
3102 }
3103 return 1;
3104}
3105
3106static int
3107compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003108 asdl_seq *generators, int gen_index,
3109 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003110{
3111 /* generate code for the iterator, then each of the ifs,
3112 and then write to the element */
3113
3114 comprehension_ty l;
3115 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003116 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003117
3118 start = compiler_new_block(c);
3119 skip = compiler_new_block(c);
3120 if_cleanup = compiler_new_block(c);
3121 anchor = compiler_new_block(c);
3122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3124 anchor == NULL)
3125 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126
3127 l = asdl_seq_GET(generators, gen_index);
3128 VISIT(c, expr, l->iter);
3129 ADDOP(c, GET_ITER);
3130 compiler_use_next_block(c, start);
3131 ADDOP_JREL(c, FOR_ITER, anchor);
3132 NEXT_BLOCK(c);
3133 VISIT(c, expr, l->target);
3134
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003135 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003136 n = asdl_seq_LEN(l->ifs);
3137 for (i = 0; i < n; i++) {
3138 expr_ty e = asdl_seq_GET(l->ifs, i);
3139 VISIT(c, expr, e);
3140 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3141 NEXT_BLOCK(c);
3142 ADDOP(c, POP_TOP);
3143 }
3144
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 if (++gen_index < asdl_seq_LEN(generators))
3146 if (!compiler_listcomp_generator(c, tmpname,
3147 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003150 /* only append after the last for generator */
3151 if (gen_index >= asdl_seq_LEN(generators)) {
3152 if (!compiler_nameop(c, tmpname, Load))
3153 return 0;
3154 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003155 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003156
3157 compiler_use_next_block(c, skip);
3158 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 for (i = 0; i < n; i++) {
3160 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003161 if (i == 0)
3162 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003163 ADDOP(c, POP_TOP);
3164 }
3165 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3166 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003169 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003170 return 0;
3171
3172 return 1;
3173}
3174
3175static int
3176compiler_listcomp(struct compiler *c, expr_ty e)
3177{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003179 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 static identifier append;
3181 asdl_seq *generators = e->v.ListComp.generators;
3182
3183 assert(e->kind == ListComp_kind);
3184 if (!append) {
3185 append = PyString_InternFromString("append");
3186 if (!append)
3187 return 0;
3188 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003189 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190 if (!tmp)
3191 return 0;
3192 ADDOP_I(c, BUILD_LIST, 0);
3193 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003195 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3196 e->v.ListComp.elt);
3197 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 return rc;
3199}
3200
3201static int
3202compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003203 asdl_seq *generators, int gen_index,
3204 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003205{
3206 /* generate code for the iterator, then each of the ifs,
3207 and then write to the element */
3208
3209 comprehension_ty ge;
3210 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
3213 start = compiler_new_block(c);
3214 skip = compiler_new_block(c);
3215 if_cleanup = compiler_new_block(c);
3216 anchor = compiler_new_block(c);
3217 end = compiler_new_block(c);
3218
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220 anchor == NULL || end == NULL)
3221 return 0;
3222
3223 ge = asdl_seq_GET(generators, gen_index);
3224 ADDOP_JREL(c, SETUP_LOOP, end);
3225 if (!compiler_push_fblock(c, LOOP, start))
3226 return 0;
3227
3228 if (gen_index == 0) {
3229 /* Receive outermost iter as an implicit argument */
3230 c->u->u_argcount = 1;
3231 ADDOP_I(c, LOAD_FAST, 0);
3232 }
3233 else {
3234 /* Sub-iter - calculate on the fly */
3235 VISIT(c, expr, ge->iter);
3236 ADDOP(c, GET_ITER);
3237 }
3238 compiler_use_next_block(c, start);
3239 ADDOP_JREL(c, FOR_ITER, anchor);
3240 NEXT_BLOCK(c);
3241 VISIT(c, expr, ge->target);
3242
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003243 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 n = asdl_seq_LEN(ge->ifs);
3245 for (i = 0; i < n; i++) {
3246 expr_ty e = asdl_seq_GET(ge->ifs, i);
3247 VISIT(c, expr, e);
3248 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3249 NEXT_BLOCK(c);
3250 ADDOP(c, POP_TOP);
3251 }
3252
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003253 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3255 return 0;
3256
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003257 /* only append after the last 'for' generator */
3258 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003259 VISIT(c, expr, elt);
3260 ADDOP(c, YIELD_VALUE);
3261 ADDOP(c, POP_TOP);
3262
3263 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265 for (i = 0; i < n; i++) {
3266 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003267 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268 compiler_use_next_block(c, if_cleanup);
3269
3270 ADDOP(c, POP_TOP);
3271 }
3272 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3273 compiler_use_next_block(c, anchor);
3274 ADDOP(c, POP_BLOCK);
3275 compiler_pop_fblock(c, LOOP, start);
3276 compiler_use_next_block(c, end);
3277
3278 return 1;
3279}
3280
3281static int
3282compiler_genexp(struct compiler *c, expr_ty e)
3283{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003284 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285 PyCodeObject *co;
3286 expr_ty outermost_iter = ((comprehension_ty)
3287 (asdl_seq_GET(e->v.GeneratorExp.generators,
3288 0)))->iter;
3289
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003290 if (!name) {
3291 name = PyString_FromString("<genexpr>");
3292 if (!name)
3293 return 0;
3294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295
3296 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3297 return 0;
3298 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3299 e->v.GeneratorExp.elt);
3300 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003301 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 if (co == NULL)
3303 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003305 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003306 Py_DECREF(co);
3307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308 VISIT(c, expr, outermost_iter);
3309 ADDOP(c, GET_ITER);
3310 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311
3312 return 1;
3313}
3314
3315static int
3316compiler_visit_keyword(struct compiler *c, keyword_ty k)
3317{
3318 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3319 VISIT(c, expr, k->value);
3320 return 1;
3321}
3322
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003323/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324 whether they are true or false.
3325
3326 Return values: 1 for true, 0 for false, -1 for non-constant.
3327 */
3328
3329static int
3330expr_constant(expr_ty e)
3331{
3332 switch (e->kind) {
3333 case Num_kind:
3334 return PyObject_IsTrue(e->v.Num.n);
3335 case Str_kind:
3336 return PyObject_IsTrue(e->v.Str.s);
3337 default:
3338 return -1;
3339 }
3340}
3341
Guido van Rossumc2e20742006-02-27 22:32:47 +00003342/*
3343 Implements the with statement from PEP 343.
3344
3345 The semantics outlined in that PEP are as follows:
3346
3347 with EXPR as VAR:
3348 BLOCK
3349
3350 It is implemented roughly as:
3351
3352 context = (EXPR).__context__()
3353 exit = context.__exit__ # not calling it
3354 value = context.__enter__()
3355 try:
3356 VAR = value # if VAR present in the syntax
3357 BLOCK
3358 finally:
3359 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003360 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003362 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003363 exit(*exc)
3364 */
3365static int
3366compiler_with(struct compiler *c, stmt_ty s)
3367{
3368 static identifier context_attr, enter_attr, exit_attr;
3369 basicblock *block, *finally;
3370 identifier tmpexit, tmpvalue = NULL;
3371
3372 assert(s->kind == With_kind);
3373
3374 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003375 context_attr = PyString_InternFromString("__context__");
3376 if (!context_attr)
3377 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003378 }
3379 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003380 enter_attr = PyString_InternFromString("__enter__");
3381 if (!enter_attr)
3382 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003383 }
3384 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003385 exit_attr = PyString_InternFromString("__exit__");
3386 if (!exit_attr)
3387 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003388 }
3389
3390 block = compiler_new_block(c);
3391 finally = compiler_new_block(c);
3392 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003393 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003394
3395 /* Create a temporary variable to hold context.__exit__ */
3396 tmpexit = compiler_new_tmpname(c);
3397 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003398 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003399 PyArena_AddPyObject(c->c_arena, tmpexit);
3400
3401 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003402 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003403 We need to do this rather than preserving it on the stack
3404 because SETUP_FINALLY remembers the stack level.
3405 We need to do the assignment *inside* the try/finally
3406 so that context.__exit__() is called when the assignment
3407 fails. But we need to call context.__enter__() *before*
3408 the try/finally so that if it fails we won't call
3409 context.__exit__().
3410 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003411 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003412 if (tmpvalue == NULL)
3413 return 0;
3414 PyArena_AddPyObject(c->c_arena, tmpvalue);
3415 }
3416
3417 /* Evaluate (EXPR).__context__() */
3418 VISIT(c, expr, s->v.With.context_expr);
3419 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3420 ADDOP_I(c, CALL_FUNCTION, 0);
3421
3422 /* Squirrel away context.__exit__ */
3423 ADDOP(c, DUP_TOP);
3424 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3425 if (!compiler_nameop(c, tmpexit, Store))
3426 return 0;
3427
3428 /* Call context.__enter__() */
3429 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3430 ADDOP_I(c, CALL_FUNCTION, 0);
3431
3432 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 /* Store it in tmpvalue */
3434 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003435 return 0;
3436 }
3437 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003438 /* Discard result from context.__enter__() */
3439 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003440 }
3441
3442 /* Start the try block */
3443 ADDOP_JREL(c, SETUP_FINALLY, finally);
3444
3445 compiler_use_next_block(c, block);
3446 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003448 }
3449
3450 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003451 /* Bind saved result of context.__enter__() to VAR */
3452 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003453 !compiler_nameop(c, tmpvalue, Del))
3454 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003455 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003456 }
3457
3458 /* BLOCK code */
3459 VISIT_SEQ(c, stmt, s->v.With.body);
3460
3461 /* End of try block; start the finally block */
3462 ADDOP(c, POP_BLOCK);
3463 compiler_pop_fblock(c, FINALLY_TRY, block);
3464
3465 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3466 compiler_use_next_block(c, finally);
3467 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003468 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003469
3470 /* Finally block starts; push tmpexit and issue our magic opcode. */
3471 if (!compiler_nameop(c, tmpexit, Load) ||
3472 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003474 ADDOP(c, WITH_CLEANUP);
3475 ADDOP_I(c, CALL_FUNCTION, 3);
3476 ADDOP(c, POP_TOP);
3477
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{
3858 switch (s->kind) {
3859 case Ellipsis_kind:
3860 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3861 break;
3862 case Slice_kind:
3863 if (!s->v.Slice.step)
3864 return compiler_simple_slice(c, s, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003865 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003866 return 0;
3867 if (ctx == AugLoad) {
3868 ADDOP_I(c, DUP_TOPX, 2);
3869 }
3870 else if (ctx == AugStore) {
3871 ADDOP(c, ROT_THREE);
3872 }
3873 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874 case ExtSlice_kind: {
3875 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3876 for (i = 0; i < n; i++) {
3877 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3878 if (!compiler_visit_nested_slice(c, sub, ctx))
3879 return 0;
3880 }
3881 ADDOP_I(c, BUILD_TUPLE, n);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003882 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003883 }
3884 case Index_kind:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003885 if (ctx != AugStore)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 VISIT(c, expr, s->v.Index.value);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003887 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003888 default:
3889 PyErr_Format(PyExc_SystemError,
3890 "invalid slice %d", s->kind);
3891 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003892 }
3893 return 1;
3894}
3895
3896/* do depth-first search of basic block graph, starting with block.
3897 post records the block indices in post-order.
3898
3899 XXX must handle implicit jumps from one block to next
3900*/
3901
3902static void
3903dfs(struct compiler *c, basicblock *b, struct assembler *a)
3904{
3905 int i;
3906 struct instr *instr = NULL;
3907
3908 if (b->b_seen)
3909 return;
3910 b->b_seen = 1;
3911 if (b->b_next != NULL)
3912 dfs(c, b->b_next, a);
3913 for (i = 0; i < b->b_iused; i++) {
3914 instr = &b->b_instr[i];
3915 if (instr->i_jrel || instr->i_jabs)
3916 dfs(c, instr->i_target, a);
3917 }
3918 a->a_postorder[a->a_nblocks++] = b;
3919}
3920
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003921static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003922stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3923{
3924 int i;
3925 struct instr *instr;
3926 if (b->b_seen || b->b_startdepth >= depth)
3927 return maxdepth;
3928 b->b_seen = 1;
3929 b->b_startdepth = depth;
3930 for (i = 0; i < b->b_iused; i++) {
3931 instr = &b->b_instr[i];
3932 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3933 if (depth > maxdepth)
3934 maxdepth = depth;
3935 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3936 if (instr->i_jrel || instr->i_jabs) {
3937 maxdepth = stackdepth_walk(c, instr->i_target,
3938 depth, maxdepth);
3939 if (instr->i_opcode == JUMP_ABSOLUTE ||
3940 instr->i_opcode == JUMP_FORWARD) {
3941 goto out; /* remaining code is dead */
3942 }
3943 }
3944 }
3945 if (b->b_next)
3946 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3947out:
3948 b->b_seen = 0;
3949 return maxdepth;
3950}
3951
3952/* Find the flow path that needs the largest stack. We assume that
3953 * cycles in the flow graph have no net effect on the stack depth.
3954 */
3955static int
3956stackdepth(struct compiler *c)
3957{
3958 basicblock *b, *entryblock;
3959 entryblock = NULL;
3960 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3961 b->b_seen = 0;
3962 b->b_startdepth = INT_MIN;
3963 entryblock = b;
3964 }
3965 return stackdepth_walk(c, entryblock, 0, 0);
3966}
3967
3968static int
3969assemble_init(struct assembler *a, int nblocks, int firstlineno)
3970{
3971 memset(a, 0, sizeof(struct assembler));
3972 a->a_lineno = firstlineno;
3973 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3974 if (!a->a_bytecode)
3975 return 0;
3976 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3977 if (!a->a_lnotab)
3978 return 0;
3979 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003980 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003981 if (!a->a_postorder) {
3982 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003983 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003984 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003985 return 1;
3986}
3987
3988static void
3989assemble_free(struct assembler *a)
3990{
3991 Py_XDECREF(a->a_bytecode);
3992 Py_XDECREF(a->a_lnotab);
3993 if (a->a_postorder)
3994 PyObject_Free(a->a_postorder);
3995}
3996
3997/* Return the size of a basic block in bytes. */
3998
3999static int
4000instrsize(struct instr *instr)
4001{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004002 if (!instr->i_hasarg)
4003 return 1;
4004 if (instr->i_oparg > 0xffff)
4005 return 6;
4006 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004007}
4008
4009static int
4010blocksize(basicblock *b)
4011{
4012 int i;
4013 int size = 0;
4014
4015 for (i = 0; i < b->b_iused; i++)
4016 size += instrsize(&b->b_instr[i]);
4017 return size;
4018}
4019
4020/* All about a_lnotab.
4021
4022c_lnotab is an array of unsigned bytes disguised as a Python string.
4023It is used to map bytecode offsets to source code line #s (when needed
4024for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004025
Tim Peters2a7f3842001-06-09 09:26:21 +00004026The array is conceptually a list of
4027 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004028pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004029
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004030 byte code offset source code line number
4031 0 1
4032 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004033 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004034 350 307
4035 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004036
4037The first trick is that these numbers aren't stored, only the increments
4038from one row to the next (this doesn't really work, but it's a start):
4039
4040 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4041
4042The second trick is that an unsigned byte can't hold negative values, or
4043values larger than 255, so (a) there's a deep assumption that byte code
4044offsets and their corresponding line #s both increase monotonically, and (b)
4045if at least one column jumps by more than 255 from one row to the next, more
4046than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004047from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004048part. A user of c_lnotab desiring to find the source line number
4049corresponding to a bytecode address A should do something like this
4050
4051 lineno = addr = 0
4052 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004053 addr += addr_incr
4054 if addr > A:
4055 return lineno
4056 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004057
4058In order for this to work, when the addr field increments by more than 255,
4059the line # increment in each pair generated must be 0 until the remaining addr
4060increment is < 256. So, in the example above, com_set_lineno should not (as
4061was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004062255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004063*/
4064
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004065static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004067{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068 int d_bytecode, d_lineno;
4069 int len;
4070 char *lnotab;
4071
4072 d_bytecode = a->a_offset - a->a_lineno_off;
4073 d_lineno = i->i_lineno - a->a_lineno;
4074
4075 assert(d_bytecode >= 0);
4076 assert(d_lineno >= 0);
4077
4078 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004079 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004080
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004082 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083 nbytes = a->a_lnotab_off + 2 * ncodes;
4084 len = PyString_GET_SIZE(a->a_lnotab);
4085 if (nbytes >= len) {
4086 if (len * 2 < nbytes)
4087 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004088 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004089 len *= 2;
4090 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4091 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004092 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004094 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095 *lnotab++ = 255;
4096 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004097 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004098 d_bytecode -= ncodes * 255;
4099 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004100 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101 assert(d_bytecode <= 255);
4102 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004103 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004104 nbytes = a->a_lnotab_off + 2 * ncodes;
4105 len = PyString_GET_SIZE(a->a_lnotab);
4106 if (nbytes >= len) {
4107 if (len * 2 < nbytes)
4108 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004109 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110 len *= 2;
4111 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4112 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004113 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4115 *lnotab++ = 255;
4116 *lnotab++ = d_bytecode;
4117 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004118 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119 *lnotab++ = 255;
4120 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004121 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122 d_lineno -= ncodes * 255;
4123 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004124 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004125
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126 len = PyString_GET_SIZE(a->a_lnotab);
4127 if (a->a_lnotab_off + 2 >= len) {
4128 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004129 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004130 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004132
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004133 a->a_lnotab_off += 2;
4134 if (d_bytecode) {
4135 *lnotab++ = d_bytecode;
4136 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004137 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004138 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139 *lnotab++ = 0;
4140 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004141 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142 a->a_lineno = i->i_lineno;
4143 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004144 return 1;
4145}
4146
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147/* assemble_emit()
4148 Extend the bytecode with a new instruction.
4149 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004150*/
4151
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004152static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004153assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004154{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004155 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156 int len = PyString_GET_SIZE(a->a_bytecode);
4157 char *code;
4158
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004159 size = instrsize(i);
4160 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004162 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004163 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004165 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 if (a->a_offset + size >= len) {
4167 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004168 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004169 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4171 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004172 if (size == 6) {
4173 assert(i->i_hasarg);
4174 *code++ = (char)EXTENDED_ARG;
4175 *code++ = ext & 0xff;
4176 *code++ = ext >> 8;
4177 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004178 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004179 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004180 if (i->i_hasarg) {
4181 assert(size == 3 || size == 6);
4182 *code++ = arg & 0xff;
4183 *code++ = arg >> 8;
4184 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004185 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004186}
4187
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004188static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004189assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004190{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004191 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004192 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004193 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004194
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004195 /* Compute the size of each block and fixup jump args.
4196 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004197start:
4198 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004200 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201 bsize = blocksize(b);
4202 b->b_offset = totsize;
4203 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004204 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004205 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004206 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4207 bsize = b->b_offset;
4208 for (i = 0; i < b->b_iused; i++) {
4209 struct instr *instr = &b->b_instr[i];
4210 /* Relative jumps are computed relative to
4211 the instruction pointer after fetching
4212 the jump instruction.
4213 */
4214 bsize += instrsize(instr);
4215 if (instr->i_jabs)
4216 instr->i_oparg = instr->i_target->b_offset;
4217 else if (instr->i_jrel) {
4218 int delta = instr->i_target->b_offset - bsize;
4219 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004220 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004221 else
4222 continue;
4223 if (instr->i_oparg > 0xffff)
4224 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004225 }
4226 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004227
4228 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004229 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004230 with a better solution.
4231
4232 In the meantime, should the goto be dropped in favor
4233 of a loop?
4234
4235 The issue is that in the first loop blocksize() is called
4236 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004237 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004238 i_oparg is calculated in the second loop above.
4239
4240 So we loop until we stop seeing new EXTENDED_ARGs.
4241 The only EXTENDED_ARGs that could be popping up are
4242 ones in jump instructions. So this should converge
4243 fairly quickly.
4244 */
4245 if (last_extended_arg_count != extended_arg_count) {
4246 last_extended_arg_count = extended_arg_count;
4247 goto start;
4248 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004249}
4250
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004251static PyObject *
4252dict_keys_inorder(PyObject *dict, int offset)
4253{
4254 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004256
4257 tuple = PyTuple_New(size);
4258 if (tuple == NULL)
4259 return NULL;
4260 while (PyDict_Next(dict, &pos, &k, &v)) {
4261 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004262 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004263 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004264 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004265 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004266 PyTuple_SET_ITEM(tuple, i - offset, k);
4267 }
4268 return tuple;
4269}
4270
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004271static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004273{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004274 PySTEntryObject *ste = c->u->u_ste;
4275 int flags = 0, n;
4276 if (ste->ste_type != ModuleBlock)
4277 flags |= CO_NEWLOCALS;
4278 if (ste->ste_type == FunctionBlock) {
4279 if (!ste->ste_unoptimized)
4280 flags |= CO_OPTIMIZED;
4281 if (ste->ste_nested)
4282 flags |= CO_NESTED;
4283 if (ste->ste_generator)
4284 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004285 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004286 if (ste->ste_varargs)
4287 flags |= CO_VARARGS;
4288 if (ste->ste_varkeywords)
4289 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004290 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004292
4293 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004294 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296 n = PyDict_Size(c->u->u_freevars);
4297 if (n < 0)
4298 return -1;
4299 if (n == 0) {
4300 n = PyDict_Size(c->u->u_cellvars);
4301 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004302 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004303 if (n == 0) {
4304 flags |= CO_NOFREE;
4305 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004306 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004307
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004308 return flags;
4309}
4310
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004311static PyCodeObject *
4312makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004313{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004314 PyObject *tmp;
4315 PyCodeObject *co = NULL;
4316 PyObject *consts = NULL;
4317 PyObject *names = NULL;
4318 PyObject *varnames = NULL;
4319 PyObject *filename = NULL;
4320 PyObject *name = NULL;
4321 PyObject *freevars = NULL;
4322 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004323 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004325
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004326 tmp = dict_keys_inorder(c->u->u_consts, 0);
4327 if (!tmp)
4328 goto error;
4329 consts = PySequence_List(tmp); /* optimize_code requires a list */
4330 Py_DECREF(tmp);
4331
4332 names = dict_keys_inorder(c->u->u_names, 0);
4333 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4334 if (!consts || !names || !varnames)
4335 goto error;
4336
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004337 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4338 if (!cellvars)
4339 goto error;
4340 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4341 if (!freevars)
4342 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343 filename = PyString_FromString(c->c_filename);
4344 if (!filename)
4345 goto error;
4346
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004347 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004348 flags = compute_code_flags(c);
4349 if (flags < 0)
4350 goto error;
4351
4352 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4353 if (!bytecode)
4354 goto error;
4355
4356 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4357 if (!tmp)
4358 goto error;
4359 Py_DECREF(consts);
4360 consts = tmp;
4361
4362 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4363 bytecode, consts, names, varnames,
4364 freevars, cellvars,
4365 filename, c->u->u_name,
4366 c->u->u_firstlineno,
4367 a->a_lnotab);
4368 error:
4369 Py_XDECREF(consts);
4370 Py_XDECREF(names);
4371 Py_XDECREF(varnames);
4372 Py_XDECREF(filename);
4373 Py_XDECREF(name);
4374 Py_XDECREF(freevars);
4375 Py_XDECREF(cellvars);
4376 Py_XDECREF(bytecode);
4377 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004378}
4379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380static PyCodeObject *
4381assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004382{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004383 basicblock *b, *entryblock;
4384 struct assembler a;
4385 int i, j, nblocks;
4386 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004387
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004388 /* Make sure every block that falls off the end returns None.
4389 XXX NEXT_BLOCK() isn't quite right, because if the last
4390 block ends with a jump or return b_next shouldn't set.
4391 */
4392 if (!c->u->u_curblock->b_return) {
4393 NEXT_BLOCK(c);
4394 if (addNone)
4395 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4396 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004397 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004398
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004399 nblocks = 0;
4400 entryblock = NULL;
4401 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4402 nblocks++;
4403 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004404 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004405
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4407 goto error;
4408 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004409
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004410 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004411 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004412
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004413 /* Emit code in reverse postorder from dfs. */
4414 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004415 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416 for (j = 0; j < b->b_iused; j++)
4417 if (!assemble_emit(&a, &b->b_instr[j]))
4418 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004419 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004420
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004421 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4422 goto error;
4423 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4424 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004426 co = makecode(c, &a);
4427 error:
4428 assemble_free(&a);
4429 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004430}