blob: b92fb6254148cb69723ee764bc6501aba9febde8 [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;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000482 case BINARY_TRUE_DIVIDE:
483 newconst = PyNumber_TrueDivide(v, w);
484 break;
485 case BINARY_FLOOR_DIVIDE:
486 newconst = PyNumber_FloorDivide(v, w);
487 break;
488 case BINARY_MODULO:
489 newconst = PyNumber_Remainder(v, w);
490 break;
491 case BINARY_ADD:
492 newconst = PyNumber_Add(v, w);
493 break;
494 case BINARY_SUBTRACT:
495 newconst = PyNumber_Subtract(v, w);
496 break;
497 case BINARY_SUBSCR:
498 newconst = PyObject_GetItem(v, w);
499 break;
500 case BINARY_LSHIFT:
501 newconst = PyNumber_Lshift(v, w);
502 break;
503 case BINARY_RSHIFT:
504 newconst = PyNumber_Rshift(v, w);
505 break;
506 case BINARY_AND:
507 newconst = PyNumber_And(v, w);
508 break;
509 case BINARY_XOR:
510 newconst = PyNumber_Xor(v, w);
511 break;
512 case BINARY_OR:
513 newconst = PyNumber_Or(v, w);
514 break;
515 default:
516 /* Called with an unknown opcode */
517 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000518 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000519 opcode);
520 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000521 }
522 if (newconst == NULL) {
523 PyErr_Clear();
524 return 0;
525 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000526 size = PyObject_Size(newconst);
527 if (size == -1)
528 PyErr_Clear();
529 else if (size > 20) {
530 Py_DECREF(newconst);
531 return 0;
532 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000533
534 /* Append folded constant into consts table */
535 len_consts = PyList_GET_SIZE(consts);
536 if (PyList_Append(consts, newconst)) {
537 Py_DECREF(newconst);
538 return 0;
539 }
540 Py_DECREF(newconst);
541
542 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
543 memset(codestr, NOP, 4);
544 codestr[4] = LOAD_CONST;
545 SETARG(codestr, 4, len_consts);
546 return 1;
547}
548
Raymond Hettinger80121492005-02-20 12:41:32 +0000549static int
550fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
551{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000552 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000553 Py_ssize_t len_consts;
554 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000555
556 /* Pre-conditions */
557 assert(PyList_CheckExact(consts));
558 assert(codestr[0] == LOAD_CONST);
559
560 /* Create new constant */
561 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
562 opcode = codestr[3];
563 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000564 case UNARY_NEGATIVE:
565 /* Preserve the sign of -0.0 */
566 if (PyObject_IsTrue(v) == 1)
567 newconst = PyNumber_Negative(v);
568 break;
569 case UNARY_CONVERT:
570 newconst = PyObject_Repr(v);
571 break;
572 case UNARY_INVERT:
573 newconst = PyNumber_Invert(v);
574 break;
575 default:
576 /* Called with an unknown opcode */
577 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000578 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000579 opcode);
580 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000581 }
582 if (newconst == NULL) {
583 PyErr_Clear();
584 return 0;
585 }
586
587 /* Append folded constant into consts table */
588 len_consts = PyList_GET_SIZE(consts);
589 if (PyList_Append(consts, newconst)) {
590 Py_DECREF(newconst);
591 return 0;
592 }
593 Py_DECREF(newconst);
594
595 /* Write NOP LOAD_CONST newconst */
596 codestr[0] = NOP;
597 codestr[1] = LOAD_CONST;
598 SETARG(codestr, 1, len_consts);
599 return 1;
600}
601
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000602static unsigned int *
603markblocks(unsigned char *code, int len)
604{
605 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000606 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000607
608 if (blocks == NULL)
609 return NULL;
610 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000611
612 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000613 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
614 opcode = code[i];
615 switch (opcode) {
616 case FOR_ITER:
617 case JUMP_FORWARD:
618 case JUMP_IF_FALSE:
619 case JUMP_IF_TRUE:
620 case JUMP_ABSOLUTE:
621 case CONTINUE_LOOP:
622 case SETUP_LOOP:
623 case SETUP_EXCEPT:
624 case SETUP_FINALLY:
625 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000626 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000627 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000628 }
629 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000630 /* Build block numbers in the second pass */
631 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000633 blocks[i] = blockcnt;
634 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000635 return blocks;
636}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000637
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000638/* Perform basic peephole optimizations to components of a code object.
639 The consts object should still be in list form to allow new constants
640 to be appended.
641
642 To keep the optimizer simple, it bails out (does nothing) for code
643 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000644 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000645 the lineno table has complex encoding for gaps >= 255.
646
647 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000648 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000649 smaller. For those that reduce size, the gaps are initially filled with
650 NOPs. Later those NOPs are removed and the jump addresses retargeted in
651 a single pass. Line numbering is adjusted accordingly. */
652
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000653static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000654optimize_code(PyObject *code, PyObject* consts, PyObject *names,
655 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000656{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000657 Py_ssize_t i, j, codelen;
658 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000659 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000660 unsigned char *codestr = NULL;
661 unsigned char *lineno;
662 int *addrmap = NULL;
663 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000664 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000665 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000666 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000667
Raymond Hettingereffb3932004-10-30 08:55:08 +0000668 /* Bail out if an exception is set */
669 if (PyErr_Occurred())
670 goto exitUnchanged;
671
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000672 /* Bypass optimization when the lineno table is too complex */
673 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000674 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000675 tabsiz = PyString_GET_SIZE(lineno_obj);
676 if (memchr(lineno, 255, tabsiz) != NULL)
677 goto exitUnchanged;
678
Raymond Hettingera12fa142004-08-24 04:34:16 +0000679 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000680 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000681 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000682 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000683 goto exitUnchanged;
684
685 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000686 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000687 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000688 goto exitUnchanged;
689 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000690
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000691 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000692 the various transformation patterns to look ahead several
693 instructions without additional checks to make sure they are not
694 looking beyond the end of the code string.
695 */
696 if (codestr[codelen-1] != RETURN_VALUE)
697 goto exitUnchanged;
698
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000699 /* Mapping to new jump targets after NOPs are removed */
700 addrmap = PyMem_Malloc(codelen * sizeof(int));
701 if (addrmap == NULL)
702 goto exitUnchanged;
703
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000704 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000705 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000706 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000707 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000708
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000709 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000710 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000711
712 lastlc = cumlc;
713 cumlc = 0;
714
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000715 switch (opcode) {
716
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000717 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
718 with JUMP_IF_TRUE POP_TOP */
719 case UNARY_NOT:
720 if (codestr[i+1] != JUMP_IF_FALSE ||
721 codestr[i+4] != POP_TOP ||
722 !ISBASICBLOCK(blocks,i,5))
723 continue;
724 tgt = GETJUMPTGT(codestr, (i+1));
725 if (codestr[tgt] != POP_TOP)
726 continue;
727 j = GETARG(codestr, i+1) + 1;
728 codestr[i] = JUMP_IF_TRUE;
729 SETARG(codestr, i, j);
730 codestr[i+3] = POP_TOP;
731 codestr[i+4] = NOP;
732 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000733
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000734 /* not a is b --> a is not b
735 not a in b --> a not in b
736 not a is not b --> a is b
737 not a not in b --> a in b
738 */
739 case COMPARE_OP:
740 j = GETARG(codestr, i);
741 if (j < 6 || j > 9 ||
742 codestr[i+3] != UNARY_NOT ||
743 !ISBASICBLOCK(blocks,i,4))
744 continue;
745 SETARG(codestr, i, (j^1));
746 codestr[i+3] = NOP;
747 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000748
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000749 /* Replace LOAD_GLOBAL/LOAD_NAME None
750 with LOAD_CONST None */
751 case LOAD_NAME:
752 case LOAD_GLOBAL:
753 j = GETARG(codestr, i);
754 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
755 if (name == NULL || strcmp(name, "None") != 0)
756 continue;
757 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
758 if (PyList_GET_ITEM(consts, j) == Py_None) {
759 codestr[i] = LOAD_CONST;
760 SETARG(codestr, i, j);
761 cumlc = lastlc + 1;
762 break;
763 }
764 }
765 break;
766
767 /* Skip over LOAD_CONST trueconst
768 JUMP_IF_FALSE xx POP_TOP */
769 case LOAD_CONST:
770 cumlc = lastlc + 1;
771 j = GETARG(codestr, i);
772 if (codestr[i+3] != JUMP_IF_FALSE ||
773 codestr[i+6] != POP_TOP ||
774 !ISBASICBLOCK(blocks,i,7) ||
775 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
776 continue;
777 memset(codestr+i, NOP, 7);
778 cumlc = 0;
779 break;
780
781 /* Try to fold tuples of constants (includes a case for lists
782 which are only used for "in" and "not in" tests).
783 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
784 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
785 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
786 case BUILD_TUPLE:
787 case BUILD_LIST:
788 j = GETARG(codestr, i);
789 h = i - 3 * j;
790 if (h >= 0 &&
791 j <= lastlc &&
792 ((opcode == BUILD_TUPLE &&
793 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
794 (opcode == BUILD_LIST &&
795 codestr[i+3]==COMPARE_OP &&
796 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
797 (GETARG(codestr,i+3)==6 ||
798 GETARG(codestr,i+3)==7))) &&
799 tuple_of_constants(&codestr[h], j, consts)) {
800 assert(codestr[i] == LOAD_CONST);
801 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000802 break;
803 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000804 if (codestr[i+3] != UNPACK_SEQUENCE ||
805 !ISBASICBLOCK(blocks,i,6) ||
806 j != GETARG(codestr, i+3))
807 continue;
808 if (j == 1) {
809 memset(codestr+i, NOP, 6);
810 } else if (j == 2) {
811 codestr[i] = ROT_TWO;
812 memset(codestr+i+1, NOP, 5);
813 } else if (j == 3) {
814 codestr[i] = ROT_THREE;
815 codestr[i+1] = ROT_TWO;
816 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000817 }
818 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000819
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000820 /* Fold binary ops on constants.
821 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
822 case BINARY_POWER:
823 case BINARY_MULTIPLY:
824 case BINARY_TRUE_DIVIDE:
825 case BINARY_FLOOR_DIVIDE:
826 case BINARY_MODULO:
827 case BINARY_ADD:
828 case BINARY_SUBTRACT:
829 case BINARY_SUBSCR:
830 case BINARY_LSHIFT:
831 case BINARY_RSHIFT:
832 case BINARY_AND:
833 case BINARY_XOR:
834 case BINARY_OR:
835 if (lastlc >= 2 &&
836 ISBASICBLOCK(blocks, i-6, 7) &&
837 fold_binops_on_constants(&codestr[i-6], consts)) {
838 i -= 2;
839 assert(codestr[i] == LOAD_CONST);
840 cumlc = 1;
841 }
842 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000843
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000844 /* Fold unary ops on constants.
845 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
846 case UNARY_NEGATIVE:
847 case UNARY_CONVERT:
848 case UNARY_INVERT:
849 if (lastlc >= 1 &&
850 ISBASICBLOCK(blocks, i-3, 4) &&
851 fold_unaryops_on_constants(&codestr[i-3], consts)) {
852 i -= 2;
853 assert(codestr[i] == LOAD_CONST);
854 cumlc = 1;
855 }
856 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000857
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000858 /* Simplify conditional jump to conditional jump where the
859 result of the first test implies the success of a similar
860 test or the failure of the opposite test.
861 Arises in code like:
862 "if a and b:"
863 "if a or b:"
864 "a and b or c"
865 "(a and b) and c"
866 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
867 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
868 where y+3 is the instruction following the second test.
869 */
870 case JUMP_IF_FALSE:
871 case JUMP_IF_TRUE:
872 tgt = GETJUMPTGT(codestr, i);
873 j = codestr[tgt];
874 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
875 if (j == opcode) {
876 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
877 SETARG(codestr, i, tgttgt);
878 } else {
879 tgt -= i;
880 SETARG(codestr, i, tgt);
881 }
882 break;
883 }
884 /* Intentional fallthrough */
885
886 /* Replace jumps to unconditional jumps */
887 case FOR_ITER:
888 case JUMP_FORWARD:
889 case JUMP_ABSOLUTE:
890 case CONTINUE_LOOP:
891 case SETUP_LOOP:
892 case SETUP_EXCEPT:
893 case SETUP_FINALLY:
894 tgt = GETJUMPTGT(codestr, i);
895 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
896 continue;
897 tgttgt = GETJUMPTGT(codestr, tgt);
898 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
899 opcode = JUMP_ABSOLUTE;
900 if (!ABSOLUTE_JUMP(opcode))
901 tgttgt -= i + 3; /* Calc relative jump addr */
902 if (tgttgt < 0) /* No backward relative jumps */
903 continue;
904 codestr[i] = opcode;
905 SETARG(codestr, i, tgttgt);
906 break;
907
908 case EXTENDED_ARG:
909 goto exitUnchanged;
910
911 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
912 case RETURN_VALUE:
913 if (i+4 >= codelen ||
914 codestr[i+4] != RETURN_VALUE ||
915 !ISBASICBLOCK(blocks,i,5))
916 continue;
917 memset(codestr+i+1, NOP, 4);
918 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000919 }
920 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000921
922 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000923 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
924 addrmap[i] = i - nops;
925 if (codestr[i] == NOP)
926 nops++;
927 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000928 cum_orig_line = 0;
929 last_line = 0;
930 for (i=0 ; i < tabsiz ; i+=2) {
931 cum_orig_line += lineno[i];
932 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000933 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000934 lineno[i] =((unsigned char)(new_line - last_line));
935 last_line = new_line;
936 }
937
938 /* Remove NOPs and fixup jump targets */
939 for (i=0, h=0 ; i<codelen ; ) {
940 opcode = codestr[i];
941 switch (opcode) {
942 case NOP:
943 i++;
944 continue;
945
946 case JUMP_ABSOLUTE:
947 case CONTINUE_LOOP:
948 j = addrmap[GETARG(codestr, i)];
949 SETARG(codestr, i, j);
950 break;
951
952 case FOR_ITER:
953 case JUMP_FORWARD:
954 case JUMP_IF_FALSE:
955 case JUMP_IF_TRUE:
956 case SETUP_LOOP:
957 case SETUP_EXCEPT:
958 case SETUP_FINALLY:
959 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
960 SETARG(codestr, i, j);
961 break;
962 }
963 adj = CODESIZE(opcode);
964 while (adj--)
965 codestr[h++] = codestr[i++];
966 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000967 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000968
969 code = PyString_FromStringAndSize((char *)codestr, h);
970 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000971 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000972 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000973 return code;
974
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000975 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000976 if (blocks != NULL)
977 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000978 if (addrmap != NULL)
979 PyMem_Free(addrmap);
980 if (codestr != NULL)
981 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000982 Py_INCREF(code);
983 return code;
984}
985
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000986/* End: Peephole optimizations ----------------------------------------- */
987
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988/*
989
990Leave this debugging code for just a little longer.
991
992static void
993compiler_display_symbols(PyObject *name, PyObject *symbols)
994{
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000995PyObject *key, *value;
996int flags;
997Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000999fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1000while (PyDict_Next(symbols, &pos, &key, &value)) {
1001flags = PyInt_AsLong(value);
1002fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1003if (flags & DEF_GLOBAL)
1004fprintf(stderr, " declared_global");
1005if (flags & DEF_LOCAL)
1006fprintf(stderr, " local");
1007if (flags & DEF_PARAM)
1008fprintf(stderr, " param");
1009if (flags & DEF_STAR)
1010fprintf(stderr, " stararg");
1011if (flags & DEF_DOUBLESTAR)
1012fprintf(stderr, " starstar");
1013if (flags & DEF_INTUPLE)
1014fprintf(stderr, " tuple");
1015if (flags & DEF_FREE)
1016fprintf(stderr, " free");
1017if (flags & DEF_FREE_GLOBAL)
1018fprintf(stderr, " global");
1019if (flags & DEF_FREE_CLASS)
1020fprintf(stderr, " free/class");
1021if (flags & DEF_IMPORT)
1022fprintf(stderr, " import");
1023fprintf(stderr, "\n");
1024}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025 fprintf(stderr, "\n");
1026}
1027*/
1028
1029static void
1030compiler_unit_check(struct compiler_unit *u)
1031{
1032 basicblock *block;
1033 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1034 assert(block != (void *)0xcbcbcbcb);
1035 assert(block != (void *)0xfbfbfbfb);
1036 assert(block != (void *)0xdbdbdbdb);
1037 if (block->b_instr != NULL) {
1038 assert(block->b_ialloc > 0);
1039 assert(block->b_iused > 0);
1040 assert(block->b_ialloc >= block->b_iused);
1041 }
1042 else {
1043 assert (block->b_iused == 0);
1044 assert (block->b_ialloc == 0);
1045 }
1046 }
1047}
1048
1049static void
1050compiler_unit_free(struct compiler_unit *u)
1051{
1052 basicblock *b, *next;
1053
1054 compiler_unit_check(u);
1055 b = u->u_blocks;
1056 while (b != NULL) {
1057 if (b->b_instr)
1058 PyObject_Free((void *)b->b_instr);
1059 next = b->b_list;
1060 PyObject_Free((void *)b);
1061 b = next;
1062 }
1063 Py_XDECREF(u->u_ste);
1064 Py_XDECREF(u->u_name);
1065 Py_XDECREF(u->u_consts);
1066 Py_XDECREF(u->u_names);
1067 Py_XDECREF(u->u_varnames);
1068 Py_XDECREF(u->u_freevars);
1069 Py_XDECREF(u->u_cellvars);
1070 Py_XDECREF(u->u_private);
1071 PyObject_Free(u);
1072}
1073
1074static int
1075compiler_enter_scope(struct compiler *c, identifier name, void *key,
1076 int lineno)
1077{
1078 struct compiler_unit *u;
1079
1080 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001081 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001082 PyErr_NoMemory();
1083 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001084 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001085 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086 u->u_argcount = 0;
1087 u->u_ste = PySymtable_Lookup(c->c_st, key);
1088 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001089 compiler_unit_free(u);
1090 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091 }
1092 Py_INCREF(name);
1093 u->u_name = name;
1094 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1095 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1096 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001097 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001098
1099 u->u_blocks = NULL;
1100 u->u_tmpname = 0;
1101 u->u_nfblocks = 0;
1102 u->u_firstlineno = lineno;
1103 u->u_lineno = 0;
1104 u->u_lineno_set = false;
1105 u->u_consts = PyDict_New();
1106 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001107 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001108 return 0;
1109 }
1110 u->u_names = PyDict_New();
1111 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 return 0;
1114 }
1115
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001116 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001117
1118 /* Push the old compiler_unit on the stack. */
1119 if (c->u) {
1120 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1121 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001122 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001123 return 0;
1124 }
1125 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001126 u->u_private = c->u->u_private;
1127 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 }
1129 c->u = u;
1130
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001131 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001132 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 return 0;
1134
1135 return 1;
1136}
1137
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001138static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001139compiler_exit_scope(struct compiler *c)
1140{
1141 int n;
1142 PyObject *wrapper;
1143
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001144 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001145 compiler_unit_free(c->u);
1146 /* Restore c->u to the parent unit. */
1147 n = PyList_GET_SIZE(c->c_stack) - 1;
1148 if (n >= 0) {
1149 wrapper = PyList_GET_ITEM(c->c_stack, n);
1150 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001151 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001152 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001153 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001154 compiler_unit_check(c->u);
1155 }
1156 else
1157 c->u = NULL;
1158
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
Guido van Rossumc2e20742006-02-27 22:32:47 +00001161/* Allocate a new "anonymous" local variable.
1162 Used by list comprehensions and with statements.
1163*/
1164
1165static PyObject *
1166compiler_new_tmpname(struct compiler *c)
1167{
1168 char tmpname[256];
1169 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1170 return PyString_FromString(tmpname);
1171}
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173/* Allocate a new block and return a pointer to it.
1174 Returns NULL on error.
1175*/
1176
1177static basicblock *
1178compiler_new_block(struct compiler *c)
1179{
1180 basicblock *b;
1181 struct compiler_unit *u;
1182
1183 u = c->u;
1184 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001185 if (b == NULL) {
1186 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001187 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001188 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189 memset((void *)b, 0, sizeof(basicblock));
1190 assert (b->b_next == NULL);
1191 b->b_list = u->u_blocks;
1192 u->u_blocks = b;
1193 return b;
1194}
1195
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196static basicblock *
1197compiler_use_new_block(struct compiler *c)
1198{
1199 basicblock *block = compiler_new_block(c);
1200 if (block == NULL)
1201 return NULL;
1202 c->u->u_curblock = block;
1203 return block;
1204}
1205
1206static basicblock *
1207compiler_next_block(struct compiler *c)
1208{
1209 basicblock *block = compiler_new_block(c);
1210 if (block == NULL)
1211 return NULL;
1212 c->u->u_curblock->b_next = block;
1213 c->u->u_curblock = block;
1214 return block;
1215}
1216
1217static basicblock *
1218compiler_use_next_block(struct compiler *c, basicblock *block)
1219{
1220 assert(block != NULL);
1221 c->u->u_curblock->b_next = block;
1222 c->u->u_curblock = block;
1223 return block;
1224}
1225
1226/* Returns the offset of the next instruction in the current block's
1227 b_instr array. Resizes the b_instr as necessary.
1228 Returns -1 on failure.
1229 */
1230
1231static int
1232compiler_next_instr(struct compiler *c, basicblock *b)
1233{
1234 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001235 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001236 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1237 DEFAULT_BLOCK_SIZE);
1238 if (b->b_instr == NULL) {
1239 PyErr_NoMemory();
1240 return -1;
1241 }
1242 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1243 memset((char *)b->b_instr, 0,
1244 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001245 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001246 else if (b->b_iused == b->b_ialloc) {
1247 size_t oldsize, newsize;
1248 oldsize = b->b_ialloc * sizeof(struct instr);
1249 newsize = oldsize << 1;
1250 if (newsize == 0) {
1251 PyErr_NoMemory();
1252 return -1;
1253 }
1254 b->b_ialloc <<= 1;
1255 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1256 if (b->b_instr == NULL)
1257 return -1;
1258 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1259 }
1260 return b->b_iused++;
1261}
1262
1263static void
1264compiler_set_lineno(struct compiler *c, int off)
1265{
1266 basicblock *b;
1267 if (c->u->u_lineno_set)
1268 return;
1269 c->u->u_lineno_set = true;
1270 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001271 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001272}
1273
1274static int
1275opcode_stack_effect(int opcode, int oparg)
1276{
1277 switch (opcode) {
1278 case POP_TOP:
1279 return -1;
1280 case ROT_TWO:
1281 case ROT_THREE:
1282 return 0;
1283 case DUP_TOP:
1284 return 1;
1285 case ROT_FOUR:
1286 return 0;
1287
1288 case UNARY_POSITIVE:
1289 case UNARY_NEGATIVE:
1290 case UNARY_NOT:
1291 case UNARY_CONVERT:
1292 case UNARY_INVERT:
1293 return 0;
1294
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001295 case LIST_APPEND:
1296 return -2;
1297
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001298 case BINARY_POWER:
1299 case BINARY_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001300 case BINARY_MODULO:
1301 case BINARY_ADD:
1302 case BINARY_SUBTRACT:
1303 case BINARY_SUBSCR:
1304 case BINARY_FLOOR_DIVIDE:
1305 case BINARY_TRUE_DIVIDE:
1306 return -1;
1307 case INPLACE_FLOOR_DIVIDE:
1308 case INPLACE_TRUE_DIVIDE:
1309 return -1;
1310
1311 case SLICE+0:
1312 return 1;
1313 case SLICE+1:
1314 return 0;
1315 case SLICE+2:
1316 return 0;
1317 case SLICE+3:
1318 return -1;
1319
1320 case STORE_SLICE+0:
1321 return -2;
1322 case STORE_SLICE+1:
1323 return -3;
1324 case STORE_SLICE+2:
1325 return -3;
1326 case STORE_SLICE+3:
1327 return -4;
1328
1329 case DELETE_SLICE+0:
1330 return -1;
1331 case DELETE_SLICE+1:
1332 return -2;
1333 case DELETE_SLICE+2:
1334 return -2;
1335 case DELETE_SLICE+3:
1336 return -3;
1337
1338 case INPLACE_ADD:
1339 case INPLACE_SUBTRACT:
1340 case INPLACE_MULTIPLY:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001341 case INPLACE_MODULO:
1342 return -1;
1343 case STORE_SUBSCR:
1344 return -3;
1345 case DELETE_SUBSCR:
1346 return -2;
1347
1348 case BINARY_LSHIFT:
1349 case BINARY_RSHIFT:
1350 case BINARY_AND:
1351 case BINARY_XOR:
1352 case BINARY_OR:
1353 return -1;
1354 case INPLACE_POWER:
1355 return -1;
1356 case GET_ITER:
1357 return 0;
1358
1359 case PRINT_EXPR:
1360 return -1;
1361 case PRINT_ITEM:
1362 return -1;
1363 case PRINT_NEWLINE:
1364 return 0;
1365 case PRINT_ITEM_TO:
1366 return -2;
1367 case PRINT_NEWLINE_TO:
1368 return -1;
1369 case INPLACE_LSHIFT:
1370 case INPLACE_RSHIFT:
1371 case INPLACE_AND:
1372 case INPLACE_XOR:
1373 case INPLACE_OR:
1374 return -1;
1375 case BREAK_LOOP:
1376 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001377 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001378 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 case LOAD_LOCALS:
1380 return 1;
1381 case RETURN_VALUE:
1382 return -1;
1383 case IMPORT_STAR:
1384 return -1;
1385 case EXEC_STMT:
1386 return -3;
1387 case YIELD_VALUE:
1388 return 0;
1389
1390 case POP_BLOCK:
1391 return 0;
1392 case END_FINALLY:
1393 return -1; /* or -2 or -3 if exception occurred */
1394 case BUILD_CLASS:
1395 return -2;
1396
1397 case STORE_NAME:
1398 return -1;
1399 case DELETE_NAME:
1400 return 0;
1401 case UNPACK_SEQUENCE:
1402 return oparg-1;
1403 case FOR_ITER:
1404 return 1;
1405
1406 case STORE_ATTR:
1407 return -2;
1408 case DELETE_ATTR:
1409 return -1;
1410 case STORE_GLOBAL:
1411 return -1;
1412 case DELETE_GLOBAL:
1413 return 0;
1414 case DUP_TOPX:
1415 return oparg;
1416 case LOAD_CONST:
1417 return 1;
1418 case LOAD_NAME:
1419 return 1;
1420 case BUILD_TUPLE:
1421 case BUILD_LIST:
1422 return 1-oparg;
1423 case BUILD_MAP:
1424 return 1;
1425 case LOAD_ATTR:
1426 return 0;
1427 case COMPARE_OP:
1428 return -1;
1429 case IMPORT_NAME:
1430 return 0;
1431 case IMPORT_FROM:
1432 return 1;
1433
1434 case JUMP_FORWARD:
1435 case JUMP_IF_FALSE:
1436 case JUMP_IF_TRUE:
1437 case JUMP_ABSOLUTE:
1438 return 0;
1439
1440 case LOAD_GLOBAL:
1441 return 1;
1442
1443 case CONTINUE_LOOP:
1444 return 0;
1445 case SETUP_LOOP:
1446 return 0;
1447 case SETUP_EXCEPT:
1448 case SETUP_FINALLY:
1449 return 3; /* actually pushed by an exception */
1450
1451 case LOAD_FAST:
1452 return 1;
1453 case STORE_FAST:
1454 return -1;
1455 case DELETE_FAST:
1456 return 0;
1457
1458 case RAISE_VARARGS:
1459 return -oparg;
1460#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1461 case CALL_FUNCTION:
1462 return -NARGS(oparg);
1463 case CALL_FUNCTION_VAR:
1464 case CALL_FUNCTION_KW:
1465 return -NARGS(oparg)-1;
1466 case CALL_FUNCTION_VAR_KW:
1467 return -NARGS(oparg)-2;
1468#undef NARGS
1469 case MAKE_FUNCTION:
1470 return -oparg;
1471 case BUILD_SLICE:
1472 if (oparg == 3)
1473 return -2;
1474 else
1475 return -1;
1476
1477 case MAKE_CLOSURE:
1478 return -oparg;
1479 case LOAD_CLOSURE:
1480 return 1;
1481 case LOAD_DEREF:
1482 return 1;
1483 case STORE_DEREF:
1484 return -1;
1485 default:
1486 fprintf(stderr, "opcode = %d\n", opcode);
1487 Py_FatalError("opcode_stack_effect()");
1488
1489 }
1490 return 0; /* not reachable */
1491}
1492
1493/* Add an opcode with no argument.
1494 Returns 0 on failure, 1 on success.
1495*/
1496
1497static int
1498compiler_addop(struct compiler *c, int opcode)
1499{
1500 basicblock *b;
1501 struct instr *i;
1502 int off;
1503 off = compiler_next_instr(c, c->u->u_curblock);
1504 if (off < 0)
1505 return 0;
1506 b = c->u->u_curblock;
1507 i = &b->b_instr[off];
1508 i->i_opcode = opcode;
1509 i->i_hasarg = 0;
1510 if (opcode == RETURN_VALUE)
1511 b->b_return = 1;
1512 compiler_set_lineno(c, off);
1513 return 1;
1514}
1515
1516static int
1517compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1518{
1519 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001520 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001522 /* necessary to make sure types aren't coerced (e.g., int and long) */
1523 t = PyTuple_Pack(2, o, o->ob_type);
1524 if (t == NULL)
1525 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526
1527 v = PyDict_GetItem(dict, t);
1528 if (!v) {
1529 arg = PyDict_Size(dict);
1530 v = PyInt_FromLong(arg);
1531 if (!v) {
1532 Py_DECREF(t);
1533 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001535 if (PyDict_SetItem(dict, t, v) < 0) {
1536 Py_DECREF(t);
1537 Py_DECREF(v);
1538 return -1;
1539 }
1540 Py_DECREF(v);
1541 }
1542 else
1543 arg = PyInt_AsLong(v);
1544 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001545 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001546}
1547
1548static int
1549compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1550 PyObject *o)
1551{
1552 int arg = compiler_add_o(c, dict, o);
1553 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001554 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555 return compiler_addop_i(c, opcode, arg);
1556}
1557
1558static int
1559compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001560 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561{
1562 int arg;
1563 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1564 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001565 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566 arg = compiler_add_o(c, dict, mangled);
1567 Py_DECREF(mangled);
1568 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001569 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570 return compiler_addop_i(c, opcode, arg);
1571}
1572
1573/* Add an opcode with an integer argument.
1574 Returns 0 on failure, 1 on success.
1575*/
1576
1577static int
1578compiler_addop_i(struct compiler *c, int opcode, int oparg)
1579{
1580 struct instr *i;
1581 int off;
1582 off = compiler_next_instr(c, c->u->u_curblock);
1583 if (off < 0)
1584 return 0;
1585 i = &c->u->u_curblock->b_instr[off];
1586 i->i_opcode = opcode;
1587 i->i_oparg = oparg;
1588 i->i_hasarg = 1;
1589 compiler_set_lineno(c, off);
1590 return 1;
1591}
1592
1593static int
1594compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1595{
1596 struct instr *i;
1597 int off;
1598
1599 assert(b != NULL);
1600 off = compiler_next_instr(c, c->u->u_curblock);
1601 if (off < 0)
1602 return 0;
1603 compiler_set_lineno(c, off);
1604 i = &c->u->u_curblock->b_instr[off];
1605 i->i_opcode = opcode;
1606 i->i_target = b;
1607 i->i_hasarg = 1;
1608 if (absolute)
1609 i->i_jabs = 1;
1610 else
1611 i->i_jrel = 1;
1612 return 1;
1613}
1614
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001615/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1616 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 it as the current block. NEXT_BLOCK() also creates an implicit jump
1618 from the current block to the new block.
1619*/
1620
1621/* XXX The returns inside these macros make it impossible to decref
1622 objects created in the local function.
1623*/
1624
1625
1626#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001627 if (compiler_use_new_block((C)) == NULL) \
1628 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629}
1630
1631#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001632 if (compiler_next_block((C)) == NULL) \
1633 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001634}
1635
1636#define ADDOP(C, OP) { \
1637 if (!compiler_addop((C), (OP))) \
1638 return 0; \
1639}
1640
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001641#define ADDOP_IN_SCOPE(C, OP) { \
1642 if (!compiler_addop((C), (OP))) { \
1643 compiler_exit_scope(c); \
1644 return 0; \
1645 } \
1646}
1647
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648#define ADDOP_O(C, OP, O, TYPE) { \
1649 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1650 return 0; \
1651}
1652
1653#define ADDOP_NAME(C, OP, O, TYPE) { \
1654 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1655 return 0; \
1656}
1657
1658#define ADDOP_I(C, OP, O) { \
1659 if (!compiler_addop_i((C), (OP), (O))) \
1660 return 0; \
1661}
1662
1663#define ADDOP_JABS(C, OP, O) { \
1664 if (!compiler_addop_j((C), (OP), (O), 1)) \
1665 return 0; \
1666}
1667
1668#define ADDOP_JREL(C, OP, O) { \
1669 if (!compiler_addop_j((C), (OP), (O), 0)) \
1670 return 0; \
1671}
1672
1673/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1674 the ASDL name to synthesize the name of the C type and the visit function.
1675*/
1676
1677#define VISIT(C, TYPE, V) {\
1678 if (!compiler_visit_ ## TYPE((C), (V))) \
1679 return 0; \
1680}
1681
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001682#define VISIT_IN_SCOPE(C, TYPE, V) {\
1683 if (!compiler_visit_ ## TYPE((C), (V))) { \
1684 compiler_exit_scope(c); \
1685 return 0; \
1686 } \
1687}
1688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689#define VISIT_SLICE(C, V, CTX) {\
1690 if (!compiler_visit_slice((C), (V), (CTX))) \
1691 return 0; \
1692}
1693
1694#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001695 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001697 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1698 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699 if (!compiler_visit_ ## TYPE((C), elt)) \
1700 return 0; \
1701 } \
1702}
1703
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001704#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001705 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001706 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001707 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1708 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001709 if (!compiler_visit_ ## TYPE((C), elt)) { \
1710 compiler_exit_scope(c); \
1711 return 0; \
1712 } \
1713 } \
1714}
1715
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001716static int
1717compiler_isdocstring(stmt_ty s)
1718{
1719 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001720 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721 return s->v.Expr.value->kind == Str_kind;
1722}
1723
1724/* Compile a sequence of statements, checking for a docstring. */
1725
1726static int
1727compiler_body(struct compiler *c, asdl_seq *stmts)
1728{
1729 int i = 0;
1730 stmt_ty st;
1731
1732 if (!asdl_seq_LEN(stmts))
1733 return 1;
1734 st = asdl_seq_GET(stmts, 0);
1735 if (compiler_isdocstring(st)) {
1736 i = 1;
1737 VISIT(c, expr, st->v.Expr.value);
1738 if (!compiler_nameop(c, __doc__, Store))
1739 return 0;
1740 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001741 for (; i < asdl_seq_LEN(stmts); i++)
1742 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001743 return 1;
1744}
1745
1746static PyCodeObject *
1747compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001748{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001749 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001750 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751 static PyObject *module;
1752 if (!module) {
1753 module = PyString_FromString("<module>");
1754 if (!module)
1755 return NULL;
1756 }
1757 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001758 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759 switch (mod->kind) {
1760 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001761 if (!compiler_body(c, mod->v.Module.body)) {
1762 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001764 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001765 break;
1766 case Interactive_kind:
1767 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001768 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769 break;
1770 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001771 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001772 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 break;
1774 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001775 PyErr_SetString(PyExc_SystemError,
1776 "suite should not be possible");
1777 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001778 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001779 PyErr_Format(PyExc_SystemError,
1780 "module kind %d should not be possible",
1781 mod->kind);
1782 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001783 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 co = assemble(c, addNone);
1785 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001786 return co;
1787}
1788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789/* The test for LOCAL must come before the test for FREE in order to
1790 handle classes where name is both local and free. The local var is
1791 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001792*/
1793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794static int
1795get_ref_type(struct compiler *c, PyObject *name)
1796{
1797 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001798 if (scope == 0) {
1799 char buf[350];
1800 PyOS_snprintf(buf, sizeof(buf),
1801 "unknown scope for %.100s in %.100s(%s) in %s\n"
1802 "symbols: %s\nlocals: %s\nglobals: %s\n",
1803 PyString_AS_STRING(name),
1804 PyString_AS_STRING(c->u->u_name),
1805 PyObject_REPR(c->u->u_ste->ste_id),
1806 c->c_filename,
1807 PyObject_REPR(c->u->u_ste->ste_symbols),
1808 PyObject_REPR(c->u->u_varnames),
1809 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001811 Py_FatalError(buf);
1812 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001813
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001814 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815}
1816
1817static int
1818compiler_lookup_arg(PyObject *dict, PyObject *name)
1819{
1820 PyObject *k, *v;
1821 k = Py_BuildValue("(OO)", name, name->ob_type);
1822 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001823 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001825 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001827 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 return PyInt_AS_LONG(v);
1829}
1830
1831static int
1832compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1833{
1834 int i, free = PyCode_GetNumFree(co);
1835 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001836 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1837 ADDOP_I(c, MAKE_FUNCTION, args);
1838 return 1;
1839 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001840 for (i = 0; i < free; ++i) {
1841 /* Bypass com_addop_varname because it will generate
1842 LOAD_DEREF but LOAD_CLOSURE is needed.
1843 */
1844 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1845 int arg, reftype;
1846
1847 /* Special case: If a class contains a method with a
1848 free variable that has the same name as a method,
1849 the name will be considered free *and* local in the
1850 class. It should be handled by the closure, as
1851 well as by the normal name loookup logic.
1852 */
1853 reftype = get_ref_type(c, name);
1854 if (reftype == CELL)
1855 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1856 else /* (reftype == FREE) */
1857 arg = compiler_lookup_arg(c->u->u_freevars, name);
1858 if (arg == -1) {
1859 printf("lookup %s in %s %d %d\n"
1860 "freevars of %s: %s\n",
1861 PyObject_REPR(name),
1862 PyString_AS_STRING(c->u->u_name),
1863 reftype, arg,
1864 PyString_AS_STRING(co->co_name),
1865 PyObject_REPR(co->co_freevars));
1866 Py_FatalError("compiler_make_closure()");
1867 }
1868 ADDOP_I(c, LOAD_CLOSURE, arg);
1869 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001870 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001872 ADDOP_I(c, MAKE_CLOSURE, args);
1873 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874}
1875
1876static int
1877compiler_decorators(struct compiler *c, asdl_seq* decos)
1878{
1879 int i;
1880
1881 if (!decos)
1882 return 1;
1883
1884 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1885 VISIT(c, expr, asdl_seq_GET(decos, i));
1886 }
1887 return 1;
1888}
1889
1890static int
1891compiler_arguments(struct compiler *c, arguments_ty args)
1892{
1893 int i;
1894 int n = asdl_seq_LEN(args->args);
1895 /* Correctly handle nested argument lists */
1896 for (i = 0; i < n; i++) {
1897 expr_ty arg = asdl_seq_GET(args->args, i);
1898 if (arg->kind == Tuple_kind) {
1899 PyObject *id = PyString_FromFormat(".%d", i);
1900 if (id == NULL) {
1901 return 0;
1902 }
1903 if (!compiler_nameop(c, id, Load)) {
1904 Py_DECREF(id);
1905 return 0;
1906 }
1907 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001908 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909 }
1910 }
1911 return 1;
1912}
1913
1914static int
1915compiler_function(struct compiler *c, stmt_ty s)
1916{
1917 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001918 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919 arguments_ty args = s->v.FunctionDef.args;
1920 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001921 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922 int i, n, docstring;
1923
1924 assert(s->kind == FunctionDef_kind);
1925
1926 if (!compiler_decorators(c, decos))
1927 return 0;
1928 if (args->defaults)
1929 VISIT_SEQ(c, expr, args->defaults);
1930 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1931 s->lineno))
1932 return 0;
1933
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001934 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1935 docstring = compiler_isdocstring(st);
1936 if (docstring)
1937 first_const = st->v.Expr.value->v.Str.s;
1938 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001939 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001940 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001941 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001942
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001943 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001944 compiler_arguments(c, args);
1945
1946 c->u->u_argcount = asdl_seq_LEN(args->args);
1947 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001948 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949 for (i = docstring; i < n; i++) {
1950 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1951 if (i == 0 && s2->kind == Expr_kind &&
1952 s2->v.Expr.value->kind == Str_kind)
1953 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001954 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001955 }
1956 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001957 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001958 if (co == NULL)
1959 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001961 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001962 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001963
1964 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1965 ADDOP_I(c, CALL_FUNCTION, 1);
1966 }
1967
1968 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1969}
1970
1971static int
1972compiler_class(struct compiler *c, stmt_ty s)
1973{
1974 int n;
1975 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001976 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001977 /* push class name on stack, needed by BUILD_CLASS */
1978 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1979 /* push the tuple of base classes on the stack */
1980 n = asdl_seq_LEN(s->v.ClassDef.bases);
1981 if (n > 0)
1982 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1983 ADDOP_I(c, BUILD_TUPLE, n);
1984 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1985 s->lineno))
1986 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001987 c->u->u_private = s->v.ClassDef.name;
1988 Py_INCREF(c->u->u_private);
1989 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990 if (!str || !compiler_nameop(c, str, Load)) {
1991 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001992 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001994 }
1995
1996 Py_DECREF(str);
1997 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998 if (!str || !compiler_nameop(c, str, Store)) {
1999 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002000 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002002 }
2003 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002005 if (!compiler_body(c, s->v.ClassDef.body)) {
2006 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002007 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002008 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002010 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2011 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002012 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002013 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014 if (co == NULL)
2015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002017 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002018 Py_DECREF(co);
2019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020 ADDOP_I(c, CALL_FUNCTION, 0);
2021 ADDOP(c, BUILD_CLASS);
2022 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2023 return 0;
2024 return 1;
2025}
2026
2027static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002028compiler_ifexp(struct compiler *c, expr_ty e)
2029{
2030 basicblock *end, *next;
2031
2032 assert(e->kind == IfExp_kind);
2033 end = compiler_new_block(c);
2034 if (end == NULL)
2035 return 0;
2036 next = compiler_new_block(c);
2037 if (next == NULL)
2038 return 0;
2039 VISIT(c, expr, e->v.IfExp.test);
2040 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2041 ADDOP(c, POP_TOP);
2042 VISIT(c, expr, e->v.IfExp.body);
2043 ADDOP_JREL(c, JUMP_FORWARD, end);
2044 compiler_use_next_block(c, next);
2045 ADDOP(c, POP_TOP);
2046 VISIT(c, expr, e->v.IfExp.orelse);
2047 compiler_use_next_block(c, end);
2048 return 1;
2049}
2050
2051static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002052compiler_lambda(struct compiler *c, expr_ty e)
2053{
2054 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002055 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056 arguments_ty args = e->v.Lambda.args;
2057 assert(e->kind == Lambda_kind);
2058
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002059 if (!name) {
2060 name = PyString_InternFromString("<lambda>");
2061 if (!name)
2062 return 0;
2063 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002064
2065 if (args->defaults)
2066 VISIT_SEQ(c, expr, args->defaults);
2067 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2068 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002069
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002070 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 compiler_arguments(c, args);
2072
2073 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002074 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2075 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002077 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078 if (co == NULL)
2079 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002081 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002082 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002083
2084 return 1;
2085}
2086
2087static int
2088compiler_print(struct compiler *c, stmt_ty s)
2089{
2090 int i, n;
2091 bool dest;
2092
2093 assert(s->kind == Print_kind);
2094 n = asdl_seq_LEN(s->v.Print.values);
2095 dest = false;
2096 if (s->v.Print.dest) {
2097 VISIT(c, expr, s->v.Print.dest);
2098 dest = true;
2099 }
2100 for (i = 0; i < n; i++) {
2101 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2102 if (dest) {
2103 ADDOP(c, DUP_TOP);
2104 VISIT(c, expr, e);
2105 ADDOP(c, ROT_TWO);
2106 ADDOP(c, PRINT_ITEM_TO);
2107 }
2108 else {
2109 VISIT(c, expr, e);
2110 ADDOP(c, PRINT_ITEM);
2111 }
2112 }
2113 if (s->v.Print.nl) {
2114 if (dest)
2115 ADDOP(c, PRINT_NEWLINE_TO)
2116 else
2117 ADDOP(c, PRINT_NEWLINE)
2118 }
2119 else if (dest)
2120 ADDOP(c, POP_TOP);
2121 return 1;
2122}
2123
2124static int
2125compiler_if(struct compiler *c, stmt_ty s)
2126{
2127 basicblock *end, *next;
2128
2129 assert(s->kind == If_kind);
2130 end = compiler_new_block(c);
2131 if (end == NULL)
2132 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002133 next = compiler_new_block(c);
2134 if (next == NULL)
2135 return 0;
2136 VISIT(c, expr, s->v.If.test);
2137 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2138 ADDOP(c, POP_TOP);
2139 VISIT_SEQ(c, stmt, s->v.If.body);
2140 ADDOP_JREL(c, JUMP_FORWARD, end);
2141 compiler_use_next_block(c, next);
2142 ADDOP(c, POP_TOP);
2143 if (s->v.If.orelse)
2144 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 compiler_use_next_block(c, end);
2146 return 1;
2147}
2148
2149static int
2150compiler_for(struct compiler *c, stmt_ty s)
2151{
2152 basicblock *start, *cleanup, *end;
2153
2154 start = compiler_new_block(c);
2155 cleanup = compiler_new_block(c);
2156 end = compiler_new_block(c);
2157 if (start == NULL || end == NULL || cleanup == NULL)
2158 return 0;
2159 ADDOP_JREL(c, SETUP_LOOP, end);
2160 if (!compiler_push_fblock(c, LOOP, start))
2161 return 0;
2162 VISIT(c, expr, s->v.For.iter);
2163 ADDOP(c, GET_ITER);
2164 compiler_use_next_block(c, start);
2165 ADDOP_JREL(c, FOR_ITER, cleanup);
2166 VISIT(c, expr, s->v.For.target);
2167 VISIT_SEQ(c, stmt, s->v.For.body);
2168 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2169 compiler_use_next_block(c, cleanup);
2170 ADDOP(c, POP_BLOCK);
2171 compiler_pop_fblock(c, LOOP, start);
2172 VISIT_SEQ(c, stmt, s->v.For.orelse);
2173 compiler_use_next_block(c, end);
2174 return 1;
2175}
2176
2177static int
2178compiler_while(struct compiler *c, stmt_ty s)
2179{
2180 basicblock *loop, *orelse, *end, *anchor = NULL;
2181 int constant = expr_constant(s->v.While.test);
2182
2183 if (constant == 0)
2184 return 1;
2185 loop = compiler_new_block(c);
2186 end = compiler_new_block(c);
2187 if (constant == -1) {
2188 anchor = compiler_new_block(c);
2189 if (anchor == NULL)
2190 return 0;
2191 }
2192 if (loop == NULL || end == NULL)
2193 return 0;
2194 if (s->v.While.orelse) {
2195 orelse = compiler_new_block(c);
2196 if (orelse == NULL)
2197 return 0;
2198 }
2199 else
2200 orelse = NULL;
2201
2202 ADDOP_JREL(c, SETUP_LOOP, end);
2203 compiler_use_next_block(c, loop);
2204 if (!compiler_push_fblock(c, LOOP, loop))
2205 return 0;
2206 if (constant == -1) {
2207 VISIT(c, expr, s->v.While.test);
2208 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2209 ADDOP(c, POP_TOP);
2210 }
2211 VISIT_SEQ(c, stmt, s->v.While.body);
2212 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2213
2214 /* XXX should the two POP instructions be in a separate block
2215 if there is no else clause ?
2216 */
2217
2218 if (constant == -1) {
2219 compiler_use_next_block(c, anchor);
2220 ADDOP(c, POP_TOP);
2221 ADDOP(c, POP_BLOCK);
2222 }
2223 compiler_pop_fblock(c, LOOP, loop);
2224 if (orelse != NULL)
2225 VISIT_SEQ(c, stmt, s->v.While.orelse);
2226 compiler_use_next_block(c, end);
2227
2228 return 1;
2229}
2230
2231static int
2232compiler_continue(struct compiler *c)
2233{
2234 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2235 int i;
2236
2237 if (!c->u->u_nfblocks)
2238 return compiler_error(c, LOOP_ERROR_MSG);
2239 i = c->u->u_nfblocks - 1;
2240 switch (c->u->u_fblock[i].fb_type) {
2241 case LOOP:
2242 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2243 break;
2244 case EXCEPT:
2245 case FINALLY_TRY:
2246 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2247 ;
2248 if (i == -1)
2249 return compiler_error(c, LOOP_ERROR_MSG);
2250 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2251 break;
2252 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002253 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254 "'continue' not supported inside 'finally' clause");
2255 }
2256
2257 return 1;
2258}
2259
2260/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2261
2262 SETUP_FINALLY L
2263 <code for body>
2264 POP_BLOCK
2265 LOAD_CONST <None>
2266 L: <code for finalbody>
2267 END_FINALLY
2268
2269 The special instructions use the block stack. Each block
2270 stack entry contains the instruction that created it (here
2271 SETUP_FINALLY), the level of the value stack at the time the
2272 block stack entry was created, and a label (here L).
2273
2274 SETUP_FINALLY:
2275 Pushes the current value stack level and the label
2276 onto the block stack.
2277 POP_BLOCK:
2278 Pops en entry from the block stack, and pops the value
2279 stack until its level is the same as indicated on the
2280 block stack. (The label is ignored.)
2281 END_FINALLY:
2282 Pops a variable number of entries from the *value* stack
2283 and re-raises the exception they specify. The number of
2284 entries popped depends on the (pseudo) exception type.
2285
2286 The block stack is unwound when an exception is raised:
2287 when a SETUP_FINALLY entry is found, the exception is pushed
2288 onto the value stack (and the exception condition is cleared),
2289 and the interpreter jumps to the label gotten from the block
2290 stack.
2291*/
2292
2293static int
2294compiler_try_finally(struct compiler *c, stmt_ty s)
2295{
2296 basicblock *body, *end;
2297 body = compiler_new_block(c);
2298 end = compiler_new_block(c);
2299 if (body == NULL || end == NULL)
2300 return 0;
2301
2302 ADDOP_JREL(c, SETUP_FINALLY, end);
2303 compiler_use_next_block(c, body);
2304 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2305 return 0;
2306 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2307 ADDOP(c, POP_BLOCK);
2308 compiler_pop_fblock(c, FINALLY_TRY, body);
2309
2310 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2311 compiler_use_next_block(c, end);
2312 if (!compiler_push_fblock(c, FINALLY_END, end))
2313 return 0;
2314 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2315 ADDOP(c, END_FINALLY);
2316 compiler_pop_fblock(c, FINALLY_END, end);
2317
2318 return 1;
2319}
2320
2321/*
2322 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2323 (The contents of the value stack is shown in [], with the top
2324 at the right; 'tb' is trace-back info, 'val' the exception's
2325 associated value, and 'exc' the exception.)
2326
2327 Value stack Label Instruction Argument
2328 [] SETUP_EXCEPT L1
2329 [] <code for S>
2330 [] POP_BLOCK
2331 [] JUMP_FORWARD L0
2332
2333 [tb, val, exc] L1: DUP )
2334 [tb, val, exc, exc] <evaluate E1> )
2335 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2336 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2337 [tb, val, exc, 1] POP )
2338 [tb, val, exc] POP
2339 [tb, val] <assign to V1> (or POP if no V1)
2340 [tb] POP
2341 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002342 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002343
2344 [tb, val, exc, 0] L2: POP
2345 [tb, val, exc] DUP
2346 .............................etc.......................
2347
2348 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002349 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350
2351 [] L0: <next statement>
2352
2353 Of course, parts are not generated if Vi or Ei is not present.
2354*/
2355static int
2356compiler_try_except(struct compiler *c, stmt_ty s)
2357{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002358 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359 int i, n;
2360
2361 body = compiler_new_block(c);
2362 except = compiler_new_block(c);
2363 orelse = compiler_new_block(c);
2364 end = compiler_new_block(c);
2365 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2366 return 0;
2367 ADDOP_JREL(c, SETUP_EXCEPT, except);
2368 compiler_use_next_block(c, body);
2369 if (!compiler_push_fblock(c, EXCEPT, body))
2370 return 0;
2371 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2372 ADDOP(c, POP_BLOCK);
2373 compiler_pop_fblock(c, EXCEPT, body);
2374 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2375 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2376 compiler_use_next_block(c, except);
2377 for (i = 0; i < n; i++) {
2378 excepthandler_ty handler = asdl_seq_GET(
2379 s->v.TryExcept.handlers, i);
2380 if (!handler->type && i < n-1)
2381 return compiler_error(c, "default 'except:' must be last");
2382 except = compiler_new_block(c);
2383 if (except == NULL)
2384 return 0;
2385 if (handler->type) {
2386 ADDOP(c, DUP_TOP);
2387 VISIT(c, expr, handler->type);
2388 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2389 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2390 ADDOP(c, POP_TOP);
2391 }
2392 ADDOP(c, POP_TOP);
2393 if (handler->name) {
2394 VISIT(c, expr, handler->name);
2395 }
2396 else {
2397 ADDOP(c, POP_TOP);
2398 }
2399 ADDOP(c, POP_TOP);
2400 VISIT_SEQ(c, stmt, handler->body);
2401 ADDOP_JREL(c, JUMP_FORWARD, end);
2402 compiler_use_next_block(c, except);
2403 if (handler->type)
2404 ADDOP(c, POP_TOP);
2405 }
2406 ADDOP(c, END_FINALLY);
2407 compiler_use_next_block(c, orelse);
2408 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2409 compiler_use_next_block(c, end);
2410 return 1;
2411}
2412
2413static int
2414compiler_import_as(struct compiler *c, identifier name, identifier asname)
2415{
2416 /* The IMPORT_NAME opcode was already generated. This function
2417 merely needs to bind the result to a name.
2418
2419 If there is a dot in name, we need to split it and emit a
2420 LOAD_ATTR for each name.
2421 */
2422 const char *src = PyString_AS_STRING(name);
2423 const char *dot = strchr(src, '.');
2424 if (dot) {
2425 /* Consume the base module name to get the first attribute */
2426 src = dot + 1;
2427 while (dot) {
2428 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002429 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002430 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002431 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002433 if (!attr)
2434 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002435 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002436 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437 src = dot + 1;
2438 }
2439 }
2440 return compiler_nameop(c, asname, Store);
2441}
2442
2443static int
2444compiler_import(struct compiler *c, stmt_ty s)
2445{
2446 /* The Import node stores a module name like a.b.c as a single
2447 string. This is convenient for all cases except
2448 import a.b.c as d
2449 where we need to parse that string to extract the individual
2450 module names.
2451 XXX Perhaps change the representation to make this case simpler?
2452 */
2453 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002454
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455 for (i = 0; i < n; i++) {
2456 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2457 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002458 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459
Guido van Rossum45aecf42006-03-15 04:58:47 +00002460 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002461 if (level == NULL)
2462 return 0;
2463
2464 ADDOP_O(c, LOAD_CONST, level, consts);
2465 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002466 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2467 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2468
2469 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002470 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002471 if (!r)
2472 return r;
2473 }
2474 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475 identifier tmp = alias->name;
2476 const char *base = PyString_AS_STRING(alias->name);
2477 char *dot = strchr(base, '.');
2478 if (dot)
2479 tmp = PyString_FromStringAndSize(base,
2480 dot - base);
2481 r = compiler_nameop(c, tmp, Store);
2482 if (dot) {
2483 Py_DECREF(tmp);
2484 }
2485 if (!r)
2486 return r;
2487 }
2488 }
2489 return 1;
2490}
2491
2492static int
2493compiler_from_import(struct compiler *c, stmt_ty s)
2494{
2495 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002496
2497 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002498 PyObject *level;
2499
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002500 if (!names)
2501 return 0;
2502
Guido van Rossum45aecf42006-03-15 04:58:47 +00002503 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002504 if (!level) {
2505 Py_DECREF(names);
2506 return 0;
2507 }
2508
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002509 /* build up the names */
2510 for (i = 0; i < n; i++) {
2511 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2512 Py_INCREF(alias->name);
2513 PyTuple_SET_ITEM(names, i, alias->name);
2514 }
2515
2516 if (s->lineno > c->c_future->ff_lineno) {
2517 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2518 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002519 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002520 Py_DECREF(names);
2521 return compiler_error(c,
2522 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002523 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002524
2525 }
2526 }
2527
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002528 ADDOP_O(c, LOAD_CONST, level, consts);
2529 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002531 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002532 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2533 for (i = 0; i < n; i++) {
2534 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2535 identifier store_name;
2536
2537 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2538 assert(n == 1);
2539 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002540 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002541 }
2542
2543 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2544 store_name = alias->name;
2545 if (alias->asname)
2546 store_name = alias->asname;
2547
2548 if (!compiler_nameop(c, store_name, Store)) {
2549 Py_DECREF(names);
2550 return 0;
2551 }
2552 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002553 /* remove imported module */
2554 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002555 return 1;
2556}
2557
2558static int
2559compiler_assert(struct compiler *c, stmt_ty s)
2560{
2561 static PyObject *assertion_error = NULL;
2562 basicblock *end;
2563
2564 if (Py_OptimizeFlag)
2565 return 1;
2566 if (assertion_error == NULL) {
2567 assertion_error = PyString_FromString("AssertionError");
2568 if (assertion_error == NULL)
2569 return 0;
2570 }
2571 VISIT(c, expr, s->v.Assert.test);
2572 end = compiler_new_block(c);
2573 if (end == NULL)
2574 return 0;
2575 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2576 ADDOP(c, POP_TOP);
2577 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2578 if (s->v.Assert.msg) {
2579 VISIT(c, expr, s->v.Assert.msg);
2580 ADDOP_I(c, RAISE_VARARGS, 2);
2581 }
2582 else {
2583 ADDOP_I(c, RAISE_VARARGS, 1);
2584 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002585 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 ADDOP(c, POP_TOP);
2587 return 1;
2588}
2589
2590static int
2591compiler_visit_stmt(struct compiler *c, stmt_ty s)
2592{
2593 int i, n;
2594
2595 c->u->u_lineno = s->lineno;
2596 c->u->u_lineno_set = false;
2597 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002598 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002600 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002601 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002602 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002603 if (c->u->u_ste->ste_type != FunctionBlock)
2604 return compiler_error(c, "'return' outside function");
2605 if (s->v.Return.value) {
2606 if (c->u->u_ste->ste_generator) {
2607 return compiler_error(c,
2608 "'return' with argument inside generator");
2609 }
2610 VISIT(c, expr, s->v.Return.value);
2611 }
2612 else
2613 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2614 ADDOP(c, RETURN_VALUE);
2615 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002616 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617 VISIT_SEQ(c, expr, s->v.Delete.targets)
2618 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002619 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002620 n = asdl_seq_LEN(s->v.Assign.targets);
2621 VISIT(c, expr, s->v.Assign.value);
2622 for (i = 0; i < n; i++) {
2623 if (i < n - 1)
2624 ADDOP(c, DUP_TOP);
2625 VISIT(c, expr,
2626 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2627 }
2628 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002629 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002631 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002633 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002635 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002637 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002639 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640 n = 0;
2641 if (s->v.Raise.type) {
2642 VISIT(c, expr, s->v.Raise.type);
2643 n++;
2644 if (s->v.Raise.inst) {
2645 VISIT(c, expr, s->v.Raise.inst);
2646 n++;
2647 if (s->v.Raise.tback) {
2648 VISIT(c, expr, s->v.Raise.tback);
2649 n++;
2650 }
2651 }
2652 }
2653 ADDOP_I(c, RAISE_VARARGS, n);
2654 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002655 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002657 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002659 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002661 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002663 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002665 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666 VISIT(c, expr, s->v.Exec.body);
2667 if (s->v.Exec.globals) {
2668 VISIT(c, expr, s->v.Exec.globals);
2669 if (s->v.Exec.locals) {
2670 VISIT(c, expr, s->v.Exec.locals);
2671 } else {
2672 ADDOP(c, DUP_TOP);
2673 }
2674 } else {
2675 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2676 ADDOP(c, DUP_TOP);
2677 }
2678 ADDOP(c, EXEC_STMT);
2679 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002680 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002682 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683 VISIT(c, expr, s->v.Expr.value);
2684 if (c->c_interactive && c->c_nestlevel <= 1) {
2685 ADDOP(c, PRINT_EXPR);
2686 }
2687 else {
2688 ADDOP(c, POP_TOP);
2689 }
2690 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002691 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 if (!c->u->u_nfblocks)
2695 return compiler_error(c, "'break' outside loop");
2696 ADDOP(c, BREAK_LOOP);
2697 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002698 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002700 case With_kind:
2701 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 }
2703 return 1;
2704}
2705
2706static int
2707unaryop(unaryop_ty op)
2708{
2709 switch (op) {
2710 case Invert:
2711 return UNARY_INVERT;
2712 case Not:
2713 return UNARY_NOT;
2714 case UAdd:
2715 return UNARY_POSITIVE;
2716 case USub:
2717 return UNARY_NEGATIVE;
2718 }
2719 return 0;
2720}
2721
2722static int
2723binop(struct compiler *c, operator_ty op)
2724{
2725 switch (op) {
2726 case Add:
2727 return BINARY_ADD;
2728 case Sub:
2729 return BINARY_SUBTRACT;
2730 case Mult:
2731 return BINARY_MULTIPLY;
2732 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002733 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 case Mod:
2735 return BINARY_MODULO;
2736 case Pow:
2737 return BINARY_POWER;
2738 case LShift:
2739 return BINARY_LSHIFT;
2740 case RShift:
2741 return BINARY_RSHIFT;
2742 case BitOr:
2743 return BINARY_OR;
2744 case BitXor:
2745 return BINARY_XOR;
2746 case BitAnd:
2747 return BINARY_AND;
2748 case FloorDiv:
2749 return BINARY_FLOOR_DIVIDE;
2750 }
2751 return 0;
2752}
2753
2754static int
2755cmpop(cmpop_ty op)
2756{
2757 switch (op) {
2758 case Eq:
2759 return PyCmp_EQ;
2760 case NotEq:
2761 return PyCmp_NE;
2762 case Lt:
2763 return PyCmp_LT;
2764 case LtE:
2765 return PyCmp_LE;
2766 case Gt:
2767 return PyCmp_GT;
2768 case GtE:
2769 return PyCmp_GE;
2770 case Is:
2771 return PyCmp_IS;
2772 case IsNot:
2773 return PyCmp_IS_NOT;
2774 case In:
2775 return PyCmp_IN;
2776 case NotIn:
2777 return PyCmp_NOT_IN;
2778 }
2779 return PyCmp_BAD;
2780}
2781
2782static int
2783inplace_binop(struct compiler *c, operator_ty op)
2784{
2785 switch (op) {
2786 case Add:
2787 return INPLACE_ADD;
2788 case Sub:
2789 return INPLACE_SUBTRACT;
2790 case Mult:
2791 return INPLACE_MULTIPLY;
2792 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002793 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002794 case Mod:
2795 return INPLACE_MODULO;
2796 case Pow:
2797 return INPLACE_POWER;
2798 case LShift:
2799 return INPLACE_LSHIFT;
2800 case RShift:
2801 return INPLACE_RSHIFT;
2802 case BitOr:
2803 return INPLACE_OR;
2804 case BitXor:
2805 return INPLACE_XOR;
2806 case BitAnd:
2807 return INPLACE_AND;
2808 case FloorDiv:
2809 return INPLACE_FLOOR_DIVIDE;
2810 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002811 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002812 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813 return 0;
2814}
2815
2816static int
2817compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2818{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002819 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2821
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002822 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002823 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824 /* XXX AugStore isn't used anywhere! */
2825
2826 /* First check for assignment to __debug__. Param? */
2827 if ((ctx == Store || ctx == AugStore || ctx == Del)
2828 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2829 return compiler_error(c, "can not assign to __debug__");
2830 }
2831
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002832 mangled = _Py_Mangle(c->u->u_private, name);
2833 if (!mangled)
2834 return 0;
2835
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836 op = 0;
2837 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002838 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839 switch (scope) {
2840 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002841 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842 optype = OP_DEREF;
2843 break;
2844 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002845 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846 optype = OP_DEREF;
2847 break;
2848 case LOCAL:
2849 if (c->u->u_ste->ste_type == FunctionBlock)
2850 optype = OP_FAST;
2851 break;
2852 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002853 if (c->u->u_ste->ste_type == FunctionBlock &&
2854 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855 optype = OP_GLOBAL;
2856 break;
2857 case GLOBAL_EXPLICIT:
2858 optype = OP_GLOBAL;
2859 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002860 default:
2861 /* scope can be 0 */
2862 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002863 }
2864
2865 /* XXX Leave assert here, but handle __doc__ and the like better */
2866 assert(scope || PyString_AS_STRING(name)[0] == '_');
2867
2868 switch (optype) {
2869 case OP_DEREF:
2870 switch (ctx) {
2871 case Load: op = LOAD_DEREF; break;
2872 case Store: op = STORE_DEREF; break;
2873 case AugLoad:
2874 case AugStore:
2875 break;
2876 case Del:
2877 PyErr_Format(PyExc_SyntaxError,
2878 "can not delete variable '%s' referenced "
2879 "in nested scope",
2880 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002881 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002884 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002885 PyErr_SetString(PyExc_SystemError,
2886 "param invalid for deref variable");
2887 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888 }
2889 break;
2890 case OP_FAST:
2891 switch (ctx) {
2892 case Load: op = LOAD_FAST; break;
2893 case Store: op = STORE_FAST; break;
2894 case Del: op = DELETE_FAST; break;
2895 case AugLoad:
2896 case AugStore:
2897 break;
2898 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002899 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002900 PyErr_SetString(PyExc_SystemError,
2901 "param invalid for local variable");
2902 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002903 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002904 ADDOP_O(c, op, mangled, varnames);
2905 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 return 1;
2907 case OP_GLOBAL:
2908 switch (ctx) {
2909 case Load: op = LOAD_GLOBAL; break;
2910 case Store: op = STORE_GLOBAL; break;
2911 case Del: op = DELETE_GLOBAL; break;
2912 case AugLoad:
2913 case AugStore:
2914 break;
2915 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002916 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002917 PyErr_SetString(PyExc_SystemError,
2918 "param invalid for global variable");
2919 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920 }
2921 break;
2922 case OP_NAME:
2923 switch (ctx) {
2924 case Load: op = LOAD_NAME; break;
2925 case Store: op = STORE_NAME; break;
2926 case Del: op = DELETE_NAME; break;
2927 case AugLoad:
2928 case AugStore:
2929 break;
2930 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002931 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002932 PyErr_SetString(PyExc_SystemError,
2933 "param invalid for name variable");
2934 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 }
2936 break;
2937 }
2938
2939 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002940 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002941 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002942 if (arg < 0)
2943 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002944 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945}
2946
2947static int
2948compiler_boolop(struct compiler *c, expr_ty e)
2949{
2950 basicblock *end;
2951 int jumpi, i, n;
2952 asdl_seq *s;
2953
2954 assert(e->kind == BoolOp_kind);
2955 if (e->v.BoolOp.op == And)
2956 jumpi = JUMP_IF_FALSE;
2957 else
2958 jumpi = JUMP_IF_TRUE;
2959 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002960 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 return 0;
2962 s = e->v.BoolOp.values;
2963 n = asdl_seq_LEN(s) - 1;
2964 for (i = 0; i < n; ++i) {
2965 VISIT(c, expr, asdl_seq_GET(s, i));
2966 ADDOP_JREL(c, jumpi, end);
2967 ADDOP(c, POP_TOP)
2968 }
2969 VISIT(c, expr, asdl_seq_GET(s, n));
2970 compiler_use_next_block(c, end);
2971 return 1;
2972}
2973
2974static int
2975compiler_list(struct compiler *c, expr_ty e)
2976{
2977 int n = asdl_seq_LEN(e->v.List.elts);
2978 if (e->v.List.ctx == Store) {
2979 ADDOP_I(c, UNPACK_SEQUENCE, n);
2980 }
2981 VISIT_SEQ(c, expr, e->v.List.elts);
2982 if (e->v.List.ctx == Load) {
2983 ADDOP_I(c, BUILD_LIST, n);
2984 }
2985 return 1;
2986}
2987
2988static int
2989compiler_tuple(struct compiler *c, expr_ty e)
2990{
2991 int n = asdl_seq_LEN(e->v.Tuple.elts);
2992 if (e->v.Tuple.ctx == Store) {
2993 ADDOP_I(c, UNPACK_SEQUENCE, n);
2994 }
2995 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2996 if (e->v.Tuple.ctx == Load) {
2997 ADDOP_I(c, BUILD_TUPLE, n);
2998 }
2999 return 1;
3000}
3001
3002static int
3003compiler_compare(struct compiler *c, expr_ty e)
3004{
3005 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003006 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003007
3008 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3009 VISIT(c, expr, e->v.Compare.left);
3010 n = asdl_seq_LEN(e->v.Compare.ops);
3011 assert(n > 0);
3012 if (n > 1) {
3013 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003014 if (cleanup == NULL)
3015 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003016 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3017 }
3018 for (i = 1; i < n; i++) {
3019 ADDOP(c, DUP_TOP);
3020 ADDOP(c, ROT_THREE);
3021 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3022 ADDOP_I(c, COMPARE_OP,
3023 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3024 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3025 NEXT_BLOCK(c);
3026 ADDOP(c, POP_TOP);
3027 if (i < (n - 1))
3028 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3029 }
3030 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3031 ADDOP_I(c, COMPARE_OP,
3032 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3033 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3034 if (n > 1) {
3035 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003036 if (end == NULL)
3037 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003038 ADDOP_JREL(c, JUMP_FORWARD, end);
3039 compiler_use_next_block(c, cleanup);
3040 ADDOP(c, ROT_TWO);
3041 ADDOP(c, POP_TOP);
3042 compiler_use_next_block(c, end);
3043 }
3044 return 1;
3045}
3046
3047static int
3048compiler_call(struct compiler *c, expr_ty e)
3049{
3050 int n, code = 0;
3051
3052 VISIT(c, expr, e->v.Call.func);
3053 n = asdl_seq_LEN(e->v.Call.args);
3054 VISIT_SEQ(c, expr, e->v.Call.args);
3055 if (e->v.Call.keywords) {
3056 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3057 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3058 }
3059 if (e->v.Call.starargs) {
3060 VISIT(c, expr, e->v.Call.starargs);
3061 code |= 1;
3062 }
3063 if (e->v.Call.kwargs) {
3064 VISIT(c, expr, e->v.Call.kwargs);
3065 code |= 2;
3066 }
3067 switch (code) {
3068 case 0:
3069 ADDOP_I(c, CALL_FUNCTION, n);
3070 break;
3071 case 1:
3072 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3073 break;
3074 case 2:
3075 ADDOP_I(c, CALL_FUNCTION_KW, n);
3076 break;
3077 case 3:
3078 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3079 break;
3080 }
3081 return 1;
3082}
3083
3084static int
3085compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003086 asdl_seq *generators, int gen_index,
3087 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003088{
3089 /* generate code for the iterator, then each of the ifs,
3090 and then write to the element */
3091
3092 comprehension_ty l;
3093 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003094 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003095
3096 start = compiler_new_block(c);
3097 skip = compiler_new_block(c);
3098 if_cleanup = compiler_new_block(c);
3099 anchor = compiler_new_block(c);
3100
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003101 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3102 anchor == NULL)
3103 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003104
3105 l = asdl_seq_GET(generators, gen_index);
3106 VISIT(c, expr, l->iter);
3107 ADDOP(c, GET_ITER);
3108 compiler_use_next_block(c, start);
3109 ADDOP_JREL(c, FOR_ITER, anchor);
3110 NEXT_BLOCK(c);
3111 VISIT(c, expr, l->target);
3112
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003113 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114 n = asdl_seq_LEN(l->ifs);
3115 for (i = 0; i < n; i++) {
3116 expr_ty e = asdl_seq_GET(l->ifs, i);
3117 VISIT(c, expr, e);
3118 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3119 NEXT_BLOCK(c);
3120 ADDOP(c, POP_TOP);
3121 }
3122
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003123 if (++gen_index < asdl_seq_LEN(generators))
3124 if (!compiler_listcomp_generator(c, tmpname,
3125 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003126 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003128 /* only append after the last for generator */
3129 if (gen_index >= asdl_seq_LEN(generators)) {
3130 if (!compiler_nameop(c, tmpname, Load))
3131 return 0;
3132 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003133 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003134
3135 compiler_use_next_block(c, skip);
3136 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003137 for (i = 0; i < n; i++) {
3138 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003139 if (i == 0)
3140 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 ADDOP(c, POP_TOP);
3142 }
3143 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3144 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003145 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 return 0;
3149
3150 return 1;
3151}
3152
3153static int
3154compiler_listcomp(struct compiler *c, expr_ty e)
3155{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003157 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 static identifier append;
3159 asdl_seq *generators = e->v.ListComp.generators;
3160
3161 assert(e->kind == ListComp_kind);
3162 if (!append) {
3163 append = PyString_InternFromString("append");
3164 if (!append)
3165 return 0;
3166 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003167 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 if (!tmp)
3169 return 0;
3170 ADDOP_I(c, BUILD_LIST, 0);
3171 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003172 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003173 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3174 e->v.ListComp.elt);
3175 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 return rc;
3177}
3178
3179static int
3180compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003181 asdl_seq *generators, int gen_index,
3182 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183{
3184 /* generate code for the iterator, then each of the ifs,
3185 and then write to the element */
3186
3187 comprehension_ty ge;
3188 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003189 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003190
3191 start = compiler_new_block(c);
3192 skip = compiler_new_block(c);
3193 if_cleanup = compiler_new_block(c);
3194 anchor = compiler_new_block(c);
3195 end = compiler_new_block(c);
3196
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003197 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198 anchor == NULL || end == NULL)
3199 return 0;
3200
3201 ge = asdl_seq_GET(generators, gen_index);
3202 ADDOP_JREL(c, SETUP_LOOP, end);
3203 if (!compiler_push_fblock(c, LOOP, start))
3204 return 0;
3205
3206 if (gen_index == 0) {
3207 /* Receive outermost iter as an implicit argument */
3208 c->u->u_argcount = 1;
3209 ADDOP_I(c, LOAD_FAST, 0);
3210 }
3211 else {
3212 /* Sub-iter - calculate on the fly */
3213 VISIT(c, expr, ge->iter);
3214 ADDOP(c, GET_ITER);
3215 }
3216 compiler_use_next_block(c, start);
3217 ADDOP_JREL(c, FOR_ITER, anchor);
3218 NEXT_BLOCK(c);
3219 VISIT(c, expr, ge->target);
3220
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003221 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222 n = asdl_seq_LEN(ge->ifs);
3223 for (i = 0; i < n; i++) {
3224 expr_ty e = asdl_seq_GET(ge->ifs, i);
3225 VISIT(c, expr, e);
3226 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3227 NEXT_BLOCK(c);
3228 ADDOP(c, POP_TOP);
3229 }
3230
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003231 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3233 return 0;
3234
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003235 /* only append after the last 'for' generator */
3236 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003237 VISIT(c, expr, elt);
3238 ADDOP(c, YIELD_VALUE);
3239 ADDOP(c, POP_TOP);
3240
3241 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003243 for (i = 0; i < n; i++) {
3244 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003245 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246 compiler_use_next_block(c, if_cleanup);
3247
3248 ADDOP(c, POP_TOP);
3249 }
3250 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3251 compiler_use_next_block(c, anchor);
3252 ADDOP(c, POP_BLOCK);
3253 compiler_pop_fblock(c, LOOP, start);
3254 compiler_use_next_block(c, end);
3255
3256 return 1;
3257}
3258
3259static int
3260compiler_genexp(struct compiler *c, expr_ty e)
3261{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003262 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 PyCodeObject *co;
3264 expr_ty outermost_iter = ((comprehension_ty)
3265 (asdl_seq_GET(e->v.GeneratorExp.generators,
3266 0)))->iter;
3267
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003268 if (!name) {
3269 name = PyString_FromString("<genexpr>");
3270 if (!name)
3271 return 0;
3272 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273
3274 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3275 return 0;
3276 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3277 e->v.GeneratorExp.elt);
3278 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003279 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280 if (co == NULL)
3281 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003283 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003284 Py_DECREF(co);
3285
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286 VISIT(c, expr, outermost_iter);
3287 ADDOP(c, GET_ITER);
3288 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289
3290 return 1;
3291}
3292
3293static int
3294compiler_visit_keyword(struct compiler *c, keyword_ty k)
3295{
3296 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3297 VISIT(c, expr, k->value);
3298 return 1;
3299}
3300
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003301/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302 whether they are true or false.
3303
3304 Return values: 1 for true, 0 for false, -1 for non-constant.
3305 */
3306
3307static int
3308expr_constant(expr_ty e)
3309{
3310 switch (e->kind) {
3311 case Num_kind:
3312 return PyObject_IsTrue(e->v.Num.n);
3313 case Str_kind:
3314 return PyObject_IsTrue(e->v.Str.s);
3315 default:
3316 return -1;
3317 }
3318}
3319
Guido van Rossumc2e20742006-02-27 22:32:47 +00003320/*
3321 Implements the with statement from PEP 343.
3322
3323 The semantics outlined in that PEP are as follows:
3324
3325 with EXPR as VAR:
3326 BLOCK
3327
3328 It is implemented roughly as:
3329
3330 context = (EXPR).__context__()
3331 exit = context.__exit__ # not calling it
3332 value = context.__enter__()
3333 try:
3334 VAR = value # if VAR present in the syntax
3335 BLOCK
3336 finally:
3337 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003338 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003339 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003340 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003341 exit(*exc)
3342 */
3343static int
3344compiler_with(struct compiler *c, stmt_ty s)
3345{
3346 static identifier context_attr, enter_attr, exit_attr;
3347 basicblock *block, *finally;
3348 identifier tmpexit, tmpvalue = NULL;
3349
3350 assert(s->kind == With_kind);
3351
3352 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003353 context_attr = PyString_InternFromString("__context__");
3354 if (!context_attr)
3355 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003356 }
3357 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003358 enter_attr = PyString_InternFromString("__enter__");
3359 if (!enter_attr)
3360 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361 }
3362 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003363 exit_attr = PyString_InternFromString("__exit__");
3364 if (!exit_attr)
3365 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003366 }
3367
3368 block = compiler_new_block(c);
3369 finally = compiler_new_block(c);
3370 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003371 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003372
3373 /* Create a temporary variable to hold context.__exit__ */
3374 tmpexit = compiler_new_tmpname(c);
3375 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003376 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003377 PyArena_AddPyObject(c->c_arena, tmpexit);
3378
3379 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003380 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003381 We need to do this rather than preserving it on the stack
3382 because SETUP_FINALLY remembers the stack level.
3383 We need to do the assignment *inside* the try/finally
3384 so that context.__exit__() is called when the assignment
3385 fails. But we need to call context.__enter__() *before*
3386 the try/finally so that if it fails we won't call
3387 context.__exit__().
3388 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003389 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003390 if (tmpvalue == NULL)
3391 return 0;
3392 PyArena_AddPyObject(c->c_arena, tmpvalue);
3393 }
3394
3395 /* Evaluate (EXPR).__context__() */
3396 VISIT(c, expr, s->v.With.context_expr);
3397 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3398 ADDOP_I(c, CALL_FUNCTION, 0);
3399
3400 /* Squirrel away context.__exit__ */
3401 ADDOP(c, DUP_TOP);
3402 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3403 if (!compiler_nameop(c, tmpexit, Store))
3404 return 0;
3405
3406 /* Call context.__enter__() */
3407 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3408 ADDOP_I(c, CALL_FUNCTION, 0);
3409
3410 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003411 /* Store it in tmpvalue */
3412 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003413 return 0;
3414 }
3415 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003416 /* Discard result from context.__enter__() */
3417 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003418 }
3419
3420 /* Start the try block */
3421 ADDOP_JREL(c, SETUP_FINALLY, finally);
3422
3423 compiler_use_next_block(c, block);
3424 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003425 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003426 }
3427
3428 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003429 /* Bind saved result of context.__enter__() to VAR */
3430 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003431 !compiler_nameop(c, tmpvalue, Del))
3432 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003433 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003434 }
3435
3436 /* BLOCK code */
3437 VISIT_SEQ(c, stmt, s->v.With.body);
3438
3439 /* End of try block; start the finally block */
3440 ADDOP(c, POP_BLOCK);
3441 compiler_pop_fblock(c, FINALLY_TRY, block);
3442
3443 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3444 compiler_use_next_block(c, finally);
3445 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003446 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003447
3448 /* Finally block starts; push tmpexit and issue our magic opcode. */
3449 if (!compiler_nameop(c, tmpexit, Load) ||
3450 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003451 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003452 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003453
3454 /* Finally block ends. */
3455 ADDOP(c, END_FINALLY);
3456 compiler_pop_fblock(c, FINALLY_END, finally);
3457 return 1;
3458}
3459
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460static int
3461compiler_visit_expr(struct compiler *c, expr_ty e)
3462{
3463 int i, n;
3464
3465 if (e->lineno > c->u->u_lineno) {
3466 c->u->u_lineno = e->lineno;
3467 c->u->u_lineno_set = false;
3468 }
3469 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003471 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003472 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003473 VISIT(c, expr, e->v.BinOp.left);
3474 VISIT(c, expr, e->v.BinOp.right);
3475 ADDOP(c, binop(c, e->v.BinOp.op));
3476 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003477 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478 VISIT(c, expr, e->v.UnaryOp.operand);
3479 ADDOP(c, unaryop(e->v.UnaryOp.op));
3480 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003481 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003483 case IfExp_kind:
3484 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003485 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003486 /* XXX get rid of arg? */
3487 ADDOP_I(c, BUILD_MAP, 0);
3488 n = asdl_seq_LEN(e->v.Dict.values);
3489 /* We must arrange things just right for STORE_SUBSCR.
3490 It wants the stack to look like (value) (dict) (key) */
3491 for (i = 0; i < n; i++) {
3492 ADDOP(c, DUP_TOP);
3493 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3494 ADDOP(c, ROT_TWO);
3495 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3496 ADDOP(c, STORE_SUBSCR);
3497 }
3498 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003501 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502 return compiler_genexp(c, e);
3503 case Yield_kind:
3504 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003505 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506 /*
3507 for (i = 0; i < c->u->u_nfblocks; i++) {
3508 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3509 return compiler_error(
3510 c, "'yield' not allowed in a 'try' "
3511 "block with a 'finally' clause");
3512 }
3513 */
3514 if (e->v.Yield.value) {
3515 VISIT(c, expr, e->v.Yield.value);
3516 }
3517 else {
3518 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3519 }
3520 ADDOP(c, YIELD_VALUE);
3521 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003522 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003526 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527 VISIT(c, expr, e->v.Repr.value);
3528 ADDOP(c, UNARY_CONVERT);
3529 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003530 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003531 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3532 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003533 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3535 break;
3536 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003537 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538 if (e->v.Attribute.ctx != AugStore)
3539 VISIT(c, expr, e->v.Attribute.value);
3540 switch (e->v.Attribute.ctx) {
3541 case AugLoad:
3542 ADDOP(c, DUP_TOP);
3543 /* Fall through to load */
3544 case Load:
3545 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3546 break;
3547 case AugStore:
3548 ADDOP(c, ROT_TWO);
3549 /* Fall through to save */
3550 case Store:
3551 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3552 break;
3553 case Del:
3554 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3555 break;
3556 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003557 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003558 PyErr_SetString(PyExc_SystemError,
3559 "param invalid in attribute expression");
3560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 }
3562 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003563 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564 switch (e->v.Subscript.ctx) {
3565 case AugLoad:
3566 VISIT(c, expr, e->v.Subscript.value);
3567 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3568 break;
3569 case Load:
3570 VISIT(c, expr, e->v.Subscript.value);
3571 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3572 break;
3573 case AugStore:
3574 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3575 break;
3576 case Store:
3577 VISIT(c, expr, e->v.Subscript.value);
3578 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3579 break;
3580 case Del:
3581 VISIT(c, expr, e->v.Subscript.value);
3582 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3583 break;
3584 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003585 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003586 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003587 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003588 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589 }
3590 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003591 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003592 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3593 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003594 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003595 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003596 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597 return compiler_tuple(c, e);
3598 }
3599 return 1;
3600}
3601
3602static int
3603compiler_augassign(struct compiler *c, stmt_ty s)
3604{
3605 expr_ty e = s->v.AugAssign.target;
3606 expr_ty auge;
3607
3608 assert(s->kind == AugAssign_kind);
3609
3610 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003611 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003613 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003614 if (auge == NULL)
3615 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003616 VISIT(c, expr, auge);
3617 VISIT(c, expr, s->v.AugAssign.value);
3618 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3619 auge->v.Attribute.ctx = AugStore;
3620 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003621 break;
3622 case Subscript_kind:
3623 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003624 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003625 if (auge == NULL)
3626 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627 VISIT(c, expr, auge);
3628 VISIT(c, expr, s->v.AugAssign.value);
3629 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003630 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003631 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003632 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633 case Name_kind:
3634 VISIT(c, expr, s->v.AugAssign.target);
3635 VISIT(c, expr, s->v.AugAssign.value);
3636 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3637 return compiler_nameop(c, e->v.Name.id, Store);
3638 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003639 PyErr_Format(PyExc_SystemError,
3640 "invalid node type (%d) for augmented assignment",
3641 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003642 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643 }
3644 return 1;
3645}
3646
3647static int
3648compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3649{
3650 struct fblockinfo *f;
3651 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3652 return 0;
3653 f = &c->u->u_fblock[c->u->u_nfblocks++];
3654 f->fb_type = t;
3655 f->fb_block = b;
3656 return 1;
3657}
3658
3659static void
3660compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3661{
3662 struct compiler_unit *u = c->u;
3663 assert(u->u_nfblocks > 0);
3664 u->u_nfblocks--;
3665 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3666 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3667}
3668
3669/* Raises a SyntaxError and returns 0.
3670 If something goes wrong, a different exception may be raised.
3671*/
3672
3673static int
3674compiler_error(struct compiler *c, const char *errstr)
3675{
3676 PyObject *loc;
3677 PyObject *u = NULL, *v = NULL;
3678
3679 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3680 if (!loc) {
3681 Py_INCREF(Py_None);
3682 loc = Py_None;
3683 }
3684 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3685 Py_None, loc);
3686 if (!u)
3687 goto exit;
3688 v = Py_BuildValue("(zO)", errstr, u);
3689 if (!v)
3690 goto exit;
3691 PyErr_SetObject(PyExc_SyntaxError, v);
3692 exit:
3693 Py_DECREF(loc);
3694 Py_XDECREF(u);
3695 Py_XDECREF(v);
3696 return 0;
3697}
3698
3699static int
3700compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003701 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003702{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003703 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003704
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003705 /* XXX this code is duplicated */
3706 switch (ctx) {
3707 case AugLoad: /* fall through to Load */
3708 case Load: op = BINARY_SUBSCR; break;
3709 case AugStore:/* fall through to Store */
3710 case Store: op = STORE_SUBSCR; break;
3711 case Del: op = DELETE_SUBSCR; break;
3712 case Param:
3713 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003714 "invalid %s kind %d in subscript\n",
3715 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003716 return 0;
3717 }
3718 if (ctx == AugLoad) {
3719 ADDOP_I(c, DUP_TOPX, 2);
3720 }
3721 else if (ctx == AugStore) {
3722 ADDOP(c, ROT_THREE);
3723 }
3724 ADDOP(c, op);
3725 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726}
3727
3728static int
3729compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3730{
3731 int n = 2;
3732 assert(s->kind == Slice_kind);
3733
3734 /* only handles the cases where BUILD_SLICE is emitted */
3735 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003736 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003737 }
3738 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003740 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003741
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003743 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003744 }
3745 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003746 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003747 }
3748
3749 if (s->v.Slice.step) {
3750 n++;
3751 VISIT(c, expr, s->v.Slice.step);
3752 }
3753 ADDOP_I(c, BUILD_SLICE, n);
3754 return 1;
3755}
3756
3757static int
3758compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3759{
3760 int op = 0, slice_offset = 0, stack_count = 0;
3761
3762 assert(s->v.Slice.step == NULL);
3763 if (s->v.Slice.lower) {
3764 slice_offset++;
3765 stack_count++;
3766 if (ctx != AugStore)
3767 VISIT(c, expr, s->v.Slice.lower);
3768 }
3769 if (s->v.Slice.upper) {
3770 slice_offset += 2;
3771 stack_count++;
3772 if (ctx != AugStore)
3773 VISIT(c, expr, s->v.Slice.upper);
3774 }
3775
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003776 if (ctx == AugLoad) {
3777 switch (stack_count) {
3778 case 0: ADDOP(c, DUP_TOP); break;
3779 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3780 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3781 }
3782 }
3783 else if (ctx == AugStore) {
3784 switch (stack_count) {
3785 case 0: ADDOP(c, ROT_TWO); break;
3786 case 1: ADDOP(c, ROT_THREE); break;
3787 case 2: ADDOP(c, ROT_FOUR); break;
3788 }
3789 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003790
3791 switch (ctx) {
3792 case AugLoad: /* fall through to Load */
3793 case Load: op = SLICE; break;
3794 case AugStore:/* fall through to Store */
3795 case Store: op = STORE_SLICE; break;
3796 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003797 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003798 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003799 PyErr_SetString(PyExc_SystemError,
3800 "param invalid in simple slice");
3801 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003802 }
3803
3804 ADDOP(c, op + slice_offset);
3805 return 1;
3806}
3807
3808static int
3809compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3810 expr_context_ty ctx)
3811{
3812 switch (s->kind) {
3813 case Ellipsis_kind:
3814 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3815 break;
3816 case Slice_kind:
3817 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003818 case Index_kind:
3819 VISIT(c, expr, s->v.Index.value);
3820 break;
3821 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003822 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003823 PyErr_SetString(PyExc_SystemError,
3824 "extended slice invalid in nested slice");
3825 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003826 }
3827 return 1;
3828}
3829
3830
3831static int
3832compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3833{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003834 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003836 case Index_kind:
3837 kindname = "index";
3838 if (ctx != AugStore) {
3839 VISIT(c, expr, s->v.Index.value);
3840 }
3841 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003842 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003843 kindname = "ellipsis";
3844 if (ctx != AugStore) {
3845 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3846 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003847 break;
3848 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003849 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003850 if (!s->v.Slice.step)
3851 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003852 if (ctx != AugStore) {
3853 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003854 return 0;
3855 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003856 break;
3857 case ExtSlice_kind:
3858 kindname = "extended slice";
3859 if (ctx != AugStore) {
3860 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3861 for (i = 0; i < n; i++) {
3862 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3863 if (!compiler_visit_nested_slice(c, sub, ctx))
3864 return 0;
3865 }
3866 ADDOP_I(c, BUILD_TUPLE, n);
3867 }
3868 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003869 default:
3870 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003871 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003872 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003874 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003875}
3876
3877/* do depth-first search of basic block graph, starting with block.
3878 post records the block indices in post-order.
3879
3880 XXX must handle implicit jumps from one block to next
3881*/
3882
3883static void
3884dfs(struct compiler *c, basicblock *b, struct assembler *a)
3885{
3886 int i;
3887 struct instr *instr = NULL;
3888
3889 if (b->b_seen)
3890 return;
3891 b->b_seen = 1;
3892 if (b->b_next != NULL)
3893 dfs(c, b->b_next, a);
3894 for (i = 0; i < b->b_iused; i++) {
3895 instr = &b->b_instr[i];
3896 if (instr->i_jrel || instr->i_jabs)
3897 dfs(c, instr->i_target, a);
3898 }
3899 a->a_postorder[a->a_nblocks++] = b;
3900}
3901
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003902static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003903stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3904{
3905 int i;
3906 struct instr *instr;
3907 if (b->b_seen || b->b_startdepth >= depth)
3908 return maxdepth;
3909 b->b_seen = 1;
3910 b->b_startdepth = depth;
3911 for (i = 0; i < b->b_iused; i++) {
3912 instr = &b->b_instr[i];
3913 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3914 if (depth > maxdepth)
3915 maxdepth = depth;
3916 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3917 if (instr->i_jrel || instr->i_jabs) {
3918 maxdepth = stackdepth_walk(c, instr->i_target,
3919 depth, maxdepth);
3920 if (instr->i_opcode == JUMP_ABSOLUTE ||
3921 instr->i_opcode == JUMP_FORWARD) {
3922 goto out; /* remaining code is dead */
3923 }
3924 }
3925 }
3926 if (b->b_next)
3927 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3928out:
3929 b->b_seen = 0;
3930 return maxdepth;
3931}
3932
3933/* Find the flow path that needs the largest stack. We assume that
3934 * cycles in the flow graph have no net effect on the stack depth.
3935 */
3936static int
3937stackdepth(struct compiler *c)
3938{
3939 basicblock *b, *entryblock;
3940 entryblock = NULL;
3941 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3942 b->b_seen = 0;
3943 b->b_startdepth = INT_MIN;
3944 entryblock = b;
3945 }
3946 return stackdepth_walk(c, entryblock, 0, 0);
3947}
3948
3949static int
3950assemble_init(struct assembler *a, int nblocks, int firstlineno)
3951{
3952 memset(a, 0, sizeof(struct assembler));
3953 a->a_lineno = firstlineno;
3954 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3955 if (!a->a_bytecode)
3956 return 0;
3957 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3958 if (!a->a_lnotab)
3959 return 0;
3960 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003961 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003962 if (!a->a_postorder) {
3963 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003964 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003965 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003966 return 1;
3967}
3968
3969static void
3970assemble_free(struct assembler *a)
3971{
3972 Py_XDECREF(a->a_bytecode);
3973 Py_XDECREF(a->a_lnotab);
3974 if (a->a_postorder)
3975 PyObject_Free(a->a_postorder);
3976}
3977
3978/* Return the size of a basic block in bytes. */
3979
3980static int
3981instrsize(struct instr *instr)
3982{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003983 if (!instr->i_hasarg)
3984 return 1;
3985 if (instr->i_oparg > 0xffff)
3986 return 6;
3987 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003988}
3989
3990static int
3991blocksize(basicblock *b)
3992{
3993 int i;
3994 int size = 0;
3995
3996 for (i = 0; i < b->b_iused; i++)
3997 size += instrsize(&b->b_instr[i]);
3998 return size;
3999}
4000
4001/* All about a_lnotab.
4002
4003c_lnotab is an array of unsigned bytes disguised as a Python string.
4004It is used to map bytecode offsets to source code line #s (when needed
4005for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004006
Tim Peters2a7f3842001-06-09 09:26:21 +00004007The array is conceptually a list of
4008 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004009pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004010
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004011 byte code offset source code line number
4012 0 1
4013 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004014 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004015 350 307
4016 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004017
4018The first trick is that these numbers aren't stored, only the increments
4019from one row to the next (this doesn't really work, but it's a start):
4020
4021 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4022
4023The second trick is that an unsigned byte can't hold negative values, or
4024values larger than 255, so (a) there's a deep assumption that byte code
4025offsets and their corresponding line #s both increase monotonically, and (b)
4026if at least one column jumps by more than 255 from one row to the next, more
4027than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004028from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004029part. A user of c_lnotab desiring to find the source line number
4030corresponding to a bytecode address A should do something like this
4031
4032 lineno = addr = 0
4033 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004034 addr += addr_incr
4035 if addr > A:
4036 return lineno
4037 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004038
4039In order for this to work, when the addr field increments by more than 255,
4040the line # increment in each pair generated must be 0 until the remaining addr
4041increment is < 256. So, in the example above, com_set_lineno should not (as
4042was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004043255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004044*/
4045
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004046static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004047assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004048{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004049 int d_bytecode, d_lineno;
4050 int len;
4051 char *lnotab;
4052
4053 d_bytecode = a->a_offset - a->a_lineno_off;
4054 d_lineno = i->i_lineno - a->a_lineno;
4055
4056 assert(d_bytecode >= 0);
4057 assert(d_lineno >= 0);
4058
4059 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004060 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004061
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004062 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004063 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064 nbytes = a->a_lnotab_off + 2 * ncodes;
4065 len = PyString_GET_SIZE(a->a_lnotab);
4066 if (nbytes >= len) {
4067 if (len * 2 < nbytes)
4068 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004069 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070 len *= 2;
4071 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4072 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004073 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004074 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004075 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004076 *lnotab++ = 255;
4077 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004078 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004079 d_bytecode -= ncodes * 255;
4080 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004081 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 assert(d_bytecode <= 255);
4083 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004084 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004085 nbytes = a->a_lnotab_off + 2 * ncodes;
4086 len = PyString_GET_SIZE(a->a_lnotab);
4087 if (nbytes >= len) {
4088 if (len * 2 < nbytes)
4089 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004090 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091 len *= 2;
4092 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4093 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004094 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004095 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4096 *lnotab++ = 255;
4097 *lnotab++ = d_bytecode;
4098 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004099 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 *lnotab++ = 255;
4101 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004102 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 d_lineno -= ncodes * 255;
4104 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004105 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004107 len = PyString_GET_SIZE(a->a_lnotab);
4108 if (a->a_lnotab_off + 2 >= len) {
4109 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004110 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004111 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004113
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004114 a->a_lnotab_off += 2;
4115 if (d_bytecode) {
4116 *lnotab++ = d_bytecode;
4117 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004118 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004119 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120 *lnotab++ = 0;
4121 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004122 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004123 a->a_lineno = i->i_lineno;
4124 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004125 return 1;
4126}
4127
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128/* assemble_emit()
4129 Extend the bytecode with a new instruction.
4130 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004131*/
4132
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004133static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004134assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004135{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004136 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 int len = PyString_GET_SIZE(a->a_bytecode);
4138 char *code;
4139
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004140 size = instrsize(i);
4141 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004142 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004143 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004144 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004146 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004147 if (a->a_offset + size >= len) {
4148 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004149 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004150 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4152 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004153 if (size == 6) {
4154 assert(i->i_hasarg);
4155 *code++ = (char)EXTENDED_ARG;
4156 *code++ = ext & 0xff;
4157 *code++ = ext >> 8;
4158 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004159 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004161 if (i->i_hasarg) {
4162 assert(size == 3 || size == 6);
4163 *code++ = arg & 0xff;
4164 *code++ = arg >> 8;
4165 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004166 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004167}
4168
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004169static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004170assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004171{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004172 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004173 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004174 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004175
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004176 /* Compute the size of each block and fixup jump args.
4177 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004178start:
4179 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004180 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004181 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004182 bsize = blocksize(b);
4183 b->b_offset = totsize;
4184 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004185 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004186 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4188 bsize = b->b_offset;
4189 for (i = 0; i < b->b_iused; i++) {
4190 struct instr *instr = &b->b_instr[i];
4191 /* Relative jumps are computed relative to
4192 the instruction pointer after fetching
4193 the jump instruction.
4194 */
4195 bsize += instrsize(instr);
4196 if (instr->i_jabs)
4197 instr->i_oparg = instr->i_target->b_offset;
4198 else if (instr->i_jrel) {
4199 int delta = instr->i_target->b_offset - bsize;
4200 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004201 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004202 else
4203 continue;
4204 if (instr->i_oparg > 0xffff)
4205 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004206 }
4207 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004208
4209 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004210 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004211 with a better solution.
4212
4213 In the meantime, should the goto be dropped in favor
4214 of a loop?
4215
4216 The issue is that in the first loop blocksize() is called
4217 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004218 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004219 i_oparg is calculated in the second loop above.
4220
4221 So we loop until we stop seeing new EXTENDED_ARGs.
4222 The only EXTENDED_ARGs that could be popping up are
4223 ones in jump instructions. So this should converge
4224 fairly quickly.
4225 */
4226 if (last_extended_arg_count != extended_arg_count) {
4227 last_extended_arg_count = extended_arg_count;
4228 goto start;
4229 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004230}
4231
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004232static PyObject *
4233dict_keys_inorder(PyObject *dict, int offset)
4234{
4235 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004236 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004237
4238 tuple = PyTuple_New(size);
4239 if (tuple == NULL)
4240 return NULL;
4241 while (PyDict_Next(dict, &pos, &k, &v)) {
4242 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004243 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004244 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004245 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004246 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004247 PyTuple_SET_ITEM(tuple, i - offset, k);
4248 }
4249 return tuple;
4250}
4251
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004252static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004253compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004254{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004255 PySTEntryObject *ste = c->u->u_ste;
4256 int flags = 0, n;
4257 if (ste->ste_type != ModuleBlock)
4258 flags |= CO_NEWLOCALS;
4259 if (ste->ste_type == FunctionBlock) {
4260 if (!ste->ste_unoptimized)
4261 flags |= CO_OPTIMIZED;
4262 if (ste->ste_nested)
4263 flags |= CO_NESTED;
4264 if (ste->ste_generator)
4265 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004267 if (ste->ste_varargs)
4268 flags |= CO_VARARGS;
4269 if (ste->ste_varkeywords)
4270 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004271 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004273
4274 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004275 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277 n = PyDict_Size(c->u->u_freevars);
4278 if (n < 0)
4279 return -1;
4280 if (n == 0) {
4281 n = PyDict_Size(c->u->u_cellvars);
4282 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004283 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284 if (n == 0) {
4285 flags |= CO_NOFREE;
4286 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004287 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004288
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004289 return flags;
4290}
4291
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004292static PyCodeObject *
4293makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004294{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295 PyObject *tmp;
4296 PyCodeObject *co = NULL;
4297 PyObject *consts = NULL;
4298 PyObject *names = NULL;
4299 PyObject *varnames = NULL;
4300 PyObject *filename = NULL;
4301 PyObject *name = NULL;
4302 PyObject *freevars = NULL;
4303 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004304 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004305 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004306
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004307 tmp = dict_keys_inorder(c->u->u_consts, 0);
4308 if (!tmp)
4309 goto error;
4310 consts = PySequence_List(tmp); /* optimize_code requires a list */
4311 Py_DECREF(tmp);
4312
4313 names = dict_keys_inorder(c->u->u_names, 0);
4314 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4315 if (!consts || !names || !varnames)
4316 goto error;
4317
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004318 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4319 if (!cellvars)
4320 goto error;
4321 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4322 if (!freevars)
4323 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324 filename = PyString_FromString(c->c_filename);
4325 if (!filename)
4326 goto error;
4327
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004328 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004329 flags = compute_code_flags(c);
4330 if (flags < 0)
4331 goto error;
4332
4333 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4334 if (!bytecode)
4335 goto error;
4336
4337 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4338 if (!tmp)
4339 goto error;
4340 Py_DECREF(consts);
4341 consts = tmp;
4342
4343 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4344 bytecode, consts, names, varnames,
4345 freevars, cellvars,
4346 filename, c->u->u_name,
4347 c->u->u_firstlineno,
4348 a->a_lnotab);
4349 error:
4350 Py_XDECREF(consts);
4351 Py_XDECREF(names);
4352 Py_XDECREF(varnames);
4353 Py_XDECREF(filename);
4354 Py_XDECREF(name);
4355 Py_XDECREF(freevars);
4356 Py_XDECREF(cellvars);
4357 Py_XDECREF(bytecode);
4358 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004359}
4360
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361static PyCodeObject *
4362assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004363{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004364 basicblock *b, *entryblock;
4365 struct assembler a;
4366 int i, j, nblocks;
4367 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004368
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369 /* Make sure every block that falls off the end returns None.
4370 XXX NEXT_BLOCK() isn't quite right, because if the last
4371 block ends with a jump or return b_next shouldn't set.
4372 */
4373 if (!c->u->u_curblock->b_return) {
4374 NEXT_BLOCK(c);
4375 if (addNone)
4376 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4377 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004378 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004379
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004380 nblocks = 0;
4381 entryblock = NULL;
4382 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4383 nblocks++;
4384 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004385 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004386
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4388 goto error;
4389 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004392 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394 /* Emit code in reverse postorder from dfs. */
4395 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004396 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004397 for (j = 0; j < b->b_iused; j++)
4398 if (!assemble_emit(&a, &b->b_instr[j]))
4399 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004400 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004401
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004402 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4403 goto error;
4404 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4405 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004407 co = makecode(c, &a);
4408 error:
4409 assemble_free(&a);
4410 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004411}