blob: 9ce2bf795fc10397c36cc296d6c7a0d13350ceaf [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:
1341 case INPLACE_DIVIDE:
1342 case INPLACE_MODULO:
1343 return -1;
1344 case STORE_SUBSCR:
1345 return -3;
1346 case DELETE_SUBSCR:
1347 return -2;
1348
1349 case BINARY_LSHIFT:
1350 case BINARY_RSHIFT:
1351 case BINARY_AND:
1352 case BINARY_XOR:
1353 case BINARY_OR:
1354 return -1;
1355 case INPLACE_POWER:
1356 return -1;
1357 case GET_ITER:
1358 return 0;
1359
1360 case PRINT_EXPR:
1361 return -1;
1362 case PRINT_ITEM:
1363 return -1;
1364 case PRINT_NEWLINE:
1365 return 0;
1366 case PRINT_ITEM_TO:
1367 return -2;
1368 case PRINT_NEWLINE_TO:
1369 return -1;
1370 case INPLACE_LSHIFT:
1371 case INPLACE_RSHIFT:
1372 case INPLACE_AND:
1373 case INPLACE_XOR:
1374 case INPLACE_OR:
1375 return -1;
1376 case BREAK_LOOP:
1377 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001378 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001379 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 case LOAD_LOCALS:
1381 return 1;
1382 case RETURN_VALUE:
1383 return -1;
1384 case IMPORT_STAR:
1385 return -1;
1386 case EXEC_STMT:
1387 return -3;
1388 case YIELD_VALUE:
1389 return 0;
1390
1391 case POP_BLOCK:
1392 return 0;
1393 case END_FINALLY:
1394 return -1; /* or -2 or -3 if exception occurred */
1395 case BUILD_CLASS:
1396 return -2;
1397
1398 case STORE_NAME:
1399 return -1;
1400 case DELETE_NAME:
1401 return 0;
1402 case UNPACK_SEQUENCE:
1403 return oparg-1;
1404 case FOR_ITER:
1405 return 1;
1406
1407 case STORE_ATTR:
1408 return -2;
1409 case DELETE_ATTR:
1410 return -1;
1411 case STORE_GLOBAL:
1412 return -1;
1413 case DELETE_GLOBAL:
1414 return 0;
1415 case DUP_TOPX:
1416 return oparg;
1417 case LOAD_CONST:
1418 return 1;
1419 case LOAD_NAME:
1420 return 1;
1421 case BUILD_TUPLE:
1422 case BUILD_LIST:
1423 return 1-oparg;
1424 case BUILD_MAP:
1425 return 1;
1426 case LOAD_ATTR:
1427 return 0;
1428 case COMPARE_OP:
1429 return -1;
1430 case IMPORT_NAME:
1431 return 0;
1432 case IMPORT_FROM:
1433 return 1;
1434
1435 case JUMP_FORWARD:
1436 case JUMP_IF_FALSE:
1437 case JUMP_IF_TRUE:
1438 case JUMP_ABSOLUTE:
1439 return 0;
1440
1441 case LOAD_GLOBAL:
1442 return 1;
1443
1444 case CONTINUE_LOOP:
1445 return 0;
1446 case SETUP_LOOP:
1447 return 0;
1448 case SETUP_EXCEPT:
1449 case SETUP_FINALLY:
1450 return 3; /* actually pushed by an exception */
1451
1452 case LOAD_FAST:
1453 return 1;
1454 case STORE_FAST:
1455 return -1;
1456 case DELETE_FAST:
1457 return 0;
1458
1459 case RAISE_VARARGS:
1460 return -oparg;
1461#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1462 case CALL_FUNCTION:
1463 return -NARGS(oparg);
1464 case CALL_FUNCTION_VAR:
1465 case CALL_FUNCTION_KW:
1466 return -NARGS(oparg)-1;
1467 case CALL_FUNCTION_VAR_KW:
1468 return -NARGS(oparg)-2;
1469#undef NARGS
1470 case MAKE_FUNCTION:
1471 return -oparg;
1472 case BUILD_SLICE:
1473 if (oparg == 3)
1474 return -2;
1475 else
1476 return -1;
1477
1478 case MAKE_CLOSURE:
1479 return -oparg;
1480 case LOAD_CLOSURE:
1481 return 1;
1482 case LOAD_DEREF:
1483 return 1;
1484 case STORE_DEREF:
1485 return -1;
1486 default:
1487 fprintf(stderr, "opcode = %d\n", opcode);
1488 Py_FatalError("opcode_stack_effect()");
1489
1490 }
1491 return 0; /* not reachable */
1492}
1493
1494/* Add an opcode with no argument.
1495 Returns 0 on failure, 1 on success.
1496*/
1497
1498static int
1499compiler_addop(struct compiler *c, int opcode)
1500{
1501 basicblock *b;
1502 struct instr *i;
1503 int off;
1504 off = compiler_next_instr(c, c->u->u_curblock);
1505 if (off < 0)
1506 return 0;
1507 b = c->u->u_curblock;
1508 i = &b->b_instr[off];
1509 i->i_opcode = opcode;
1510 i->i_hasarg = 0;
1511 if (opcode == RETURN_VALUE)
1512 b->b_return = 1;
1513 compiler_set_lineno(c, off);
1514 return 1;
1515}
1516
1517static int
1518compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1519{
1520 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001523 /* necessary to make sure types aren't coerced (e.g., int and long) */
1524 t = PyTuple_Pack(2, o, o->ob_type);
1525 if (t == NULL)
1526 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527
1528 v = PyDict_GetItem(dict, t);
1529 if (!v) {
1530 arg = PyDict_Size(dict);
1531 v = PyInt_FromLong(arg);
1532 if (!v) {
1533 Py_DECREF(t);
1534 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536 if (PyDict_SetItem(dict, t, v) < 0) {
1537 Py_DECREF(t);
1538 Py_DECREF(v);
1539 return -1;
1540 }
1541 Py_DECREF(v);
1542 }
1543 else
1544 arg = PyInt_AsLong(v);
1545 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001546 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547}
1548
1549static int
1550compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1551 PyObject *o)
1552{
1553 int arg = compiler_add_o(c, dict, o);
1554 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001555 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001556 return compiler_addop_i(c, opcode, arg);
1557}
1558
1559static int
1560compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001561 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001562{
1563 int arg;
1564 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1565 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001566 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567 arg = compiler_add_o(c, dict, mangled);
1568 Py_DECREF(mangled);
1569 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001570 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001571 return compiler_addop_i(c, opcode, arg);
1572}
1573
1574/* Add an opcode with an integer argument.
1575 Returns 0 on failure, 1 on success.
1576*/
1577
1578static int
1579compiler_addop_i(struct compiler *c, int opcode, int oparg)
1580{
1581 struct instr *i;
1582 int off;
1583 off = compiler_next_instr(c, c->u->u_curblock);
1584 if (off < 0)
1585 return 0;
1586 i = &c->u->u_curblock->b_instr[off];
1587 i->i_opcode = opcode;
1588 i->i_oparg = oparg;
1589 i->i_hasarg = 1;
1590 compiler_set_lineno(c, off);
1591 return 1;
1592}
1593
1594static int
1595compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1596{
1597 struct instr *i;
1598 int off;
1599
1600 assert(b != NULL);
1601 off = compiler_next_instr(c, c->u->u_curblock);
1602 if (off < 0)
1603 return 0;
1604 compiler_set_lineno(c, off);
1605 i = &c->u->u_curblock->b_instr[off];
1606 i->i_opcode = opcode;
1607 i->i_target = b;
1608 i->i_hasarg = 1;
1609 if (absolute)
1610 i->i_jabs = 1;
1611 else
1612 i->i_jrel = 1;
1613 return 1;
1614}
1615
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001616/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1617 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 it as the current block. NEXT_BLOCK() also creates an implicit jump
1619 from the current block to the new block.
1620*/
1621
1622/* XXX The returns inside these macros make it impossible to decref
1623 objects created in the local function.
1624*/
1625
1626
1627#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001628 if (compiler_use_new_block((C)) == NULL) \
1629 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630}
1631
1632#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001633 if (compiler_next_block((C)) == NULL) \
1634 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635}
1636
1637#define ADDOP(C, OP) { \
1638 if (!compiler_addop((C), (OP))) \
1639 return 0; \
1640}
1641
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001642#define ADDOP_IN_SCOPE(C, OP) { \
1643 if (!compiler_addop((C), (OP))) { \
1644 compiler_exit_scope(c); \
1645 return 0; \
1646 } \
1647}
1648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649#define ADDOP_O(C, OP, O, TYPE) { \
1650 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1651 return 0; \
1652}
1653
1654#define ADDOP_NAME(C, OP, O, TYPE) { \
1655 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1656 return 0; \
1657}
1658
1659#define ADDOP_I(C, OP, O) { \
1660 if (!compiler_addop_i((C), (OP), (O))) \
1661 return 0; \
1662}
1663
1664#define ADDOP_JABS(C, OP, O) { \
1665 if (!compiler_addop_j((C), (OP), (O), 1)) \
1666 return 0; \
1667}
1668
1669#define ADDOP_JREL(C, OP, O) { \
1670 if (!compiler_addop_j((C), (OP), (O), 0)) \
1671 return 0; \
1672}
1673
1674/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1675 the ASDL name to synthesize the name of the C type and the visit function.
1676*/
1677
1678#define VISIT(C, TYPE, V) {\
1679 if (!compiler_visit_ ## TYPE((C), (V))) \
1680 return 0; \
1681}
1682
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001683#define VISIT_IN_SCOPE(C, TYPE, V) {\
1684 if (!compiler_visit_ ## TYPE((C), (V))) { \
1685 compiler_exit_scope(c); \
1686 return 0; \
1687 } \
1688}
1689
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690#define VISIT_SLICE(C, V, CTX) {\
1691 if (!compiler_visit_slice((C), (V), (CTX))) \
1692 return 0; \
1693}
1694
1695#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001696 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001697 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001698 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1699 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 if (!compiler_visit_ ## TYPE((C), elt)) \
1701 return 0; \
1702 } \
1703}
1704
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001705#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001706 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001707 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001708 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1709 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001710 if (!compiler_visit_ ## TYPE((C), elt)) { \
1711 compiler_exit_scope(c); \
1712 return 0; \
1713 } \
1714 } \
1715}
1716
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001717static int
1718compiler_isdocstring(stmt_ty s)
1719{
1720 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001721 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 return s->v.Expr.value->kind == Str_kind;
1723}
1724
1725/* Compile a sequence of statements, checking for a docstring. */
1726
1727static int
1728compiler_body(struct compiler *c, asdl_seq *stmts)
1729{
1730 int i = 0;
1731 stmt_ty st;
1732
1733 if (!asdl_seq_LEN(stmts))
1734 return 1;
1735 st = asdl_seq_GET(stmts, 0);
1736 if (compiler_isdocstring(st)) {
1737 i = 1;
1738 VISIT(c, expr, st->v.Expr.value);
1739 if (!compiler_nameop(c, __doc__, Store))
1740 return 0;
1741 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001742 for (; i < asdl_seq_LEN(stmts); i++)
1743 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001744 return 1;
1745}
1746
1747static PyCodeObject *
1748compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001749{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001750 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001751 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752 static PyObject *module;
1753 if (!module) {
1754 module = PyString_FromString("<module>");
1755 if (!module)
1756 return NULL;
1757 }
1758 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001759 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760 switch (mod->kind) {
1761 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001762 if (!compiler_body(c, mod->v.Module.body)) {
1763 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001765 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766 break;
1767 case Interactive_kind:
1768 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001769 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 break;
1771 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001772 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001773 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 break;
1775 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001776 PyErr_SetString(PyExc_SystemError,
1777 "suite should not be possible");
1778 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001779 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001780 PyErr_Format(PyExc_SystemError,
1781 "module kind %d should not be possible",
1782 mod->kind);
1783 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001784 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 co = assemble(c, addNone);
1786 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001787 return co;
1788}
1789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001790/* The test for LOCAL must come before the test for FREE in order to
1791 handle classes where name is both local and free. The local var is
1792 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001793*/
1794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795static int
1796get_ref_type(struct compiler *c, PyObject *name)
1797{
1798 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001799 if (scope == 0) {
1800 char buf[350];
1801 PyOS_snprintf(buf, sizeof(buf),
1802 "unknown scope for %.100s in %.100s(%s) in %s\n"
1803 "symbols: %s\nlocals: %s\nglobals: %s\n",
1804 PyString_AS_STRING(name),
1805 PyString_AS_STRING(c->u->u_name),
1806 PyObject_REPR(c->u->u_ste->ste_id),
1807 c->c_filename,
1808 PyObject_REPR(c->u->u_ste->ste_symbols),
1809 PyObject_REPR(c->u->u_varnames),
1810 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001812 Py_FatalError(buf);
1813 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001814
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001815 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816}
1817
1818static int
1819compiler_lookup_arg(PyObject *dict, PyObject *name)
1820{
1821 PyObject *k, *v;
1822 k = Py_BuildValue("(OO)", name, name->ob_type);
1823 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001824 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001826 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001828 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 return PyInt_AS_LONG(v);
1830}
1831
1832static int
1833compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1834{
1835 int i, free = PyCode_GetNumFree(co);
1836 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001837 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1838 ADDOP_I(c, MAKE_FUNCTION, args);
1839 return 1;
1840 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001841 for (i = 0; i < free; ++i) {
1842 /* Bypass com_addop_varname because it will generate
1843 LOAD_DEREF but LOAD_CLOSURE is needed.
1844 */
1845 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1846 int arg, reftype;
1847
1848 /* Special case: If a class contains a method with a
1849 free variable that has the same name as a method,
1850 the name will be considered free *and* local in the
1851 class. It should be handled by the closure, as
1852 well as by the normal name loookup logic.
1853 */
1854 reftype = get_ref_type(c, name);
1855 if (reftype == CELL)
1856 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1857 else /* (reftype == FREE) */
1858 arg = compiler_lookup_arg(c->u->u_freevars, name);
1859 if (arg == -1) {
1860 printf("lookup %s in %s %d %d\n"
1861 "freevars of %s: %s\n",
1862 PyObject_REPR(name),
1863 PyString_AS_STRING(c->u->u_name),
1864 reftype, arg,
1865 PyString_AS_STRING(co->co_name),
1866 PyObject_REPR(co->co_freevars));
1867 Py_FatalError("compiler_make_closure()");
1868 }
1869 ADDOP_I(c, LOAD_CLOSURE, arg);
1870 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001871 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001873 ADDOP_I(c, MAKE_CLOSURE, args);
1874 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875}
1876
1877static int
1878compiler_decorators(struct compiler *c, asdl_seq* decos)
1879{
1880 int i;
1881
1882 if (!decos)
1883 return 1;
1884
1885 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1886 VISIT(c, expr, asdl_seq_GET(decos, i));
1887 }
1888 return 1;
1889}
1890
1891static int
1892compiler_arguments(struct compiler *c, arguments_ty args)
1893{
1894 int i;
1895 int n = asdl_seq_LEN(args->args);
1896 /* Correctly handle nested argument lists */
1897 for (i = 0; i < n; i++) {
1898 expr_ty arg = asdl_seq_GET(args->args, i);
1899 if (arg->kind == Tuple_kind) {
1900 PyObject *id = PyString_FromFormat(".%d", i);
1901 if (id == NULL) {
1902 return 0;
1903 }
1904 if (!compiler_nameop(c, id, Load)) {
1905 Py_DECREF(id);
1906 return 0;
1907 }
1908 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001909 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910 }
1911 }
1912 return 1;
1913}
1914
1915static int
1916compiler_function(struct compiler *c, stmt_ty s)
1917{
1918 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001919 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 arguments_ty args = s->v.FunctionDef.args;
1921 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001922 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923 int i, n, docstring;
1924
1925 assert(s->kind == FunctionDef_kind);
1926
1927 if (!compiler_decorators(c, decos))
1928 return 0;
1929 if (args->defaults)
1930 VISIT_SEQ(c, expr, args->defaults);
1931 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1932 s->lineno))
1933 return 0;
1934
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001935 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1936 docstring = compiler_isdocstring(st);
1937 if (docstring)
1938 first_const = st->v.Expr.value->v.Str.s;
1939 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001940 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001941 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001942 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001944 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945 compiler_arguments(c, args);
1946
1947 c->u->u_argcount = asdl_seq_LEN(args->args);
1948 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001949 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001950 for (i = docstring; i < n; i++) {
1951 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1952 if (i == 0 && s2->kind == Expr_kind &&
1953 s2->v.Expr.value->kind == Str_kind)
1954 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001955 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956 }
1957 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001958 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 if (co == NULL)
1960 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001961
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001962 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001963 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964
1965 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1966 ADDOP_I(c, CALL_FUNCTION, 1);
1967 }
1968
1969 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1970}
1971
1972static int
1973compiler_class(struct compiler *c, stmt_ty s)
1974{
1975 int n;
1976 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001977 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 /* push class name on stack, needed by BUILD_CLASS */
1979 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1980 /* push the tuple of base classes on the stack */
1981 n = asdl_seq_LEN(s->v.ClassDef.bases);
1982 if (n > 0)
1983 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1984 ADDOP_I(c, BUILD_TUPLE, n);
1985 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1986 s->lineno))
1987 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001988 c->u->u_private = s->v.ClassDef.name;
1989 Py_INCREF(c->u->u_private);
1990 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 if (!str || !compiler_nameop(c, str, Load)) {
1992 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001993 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001995 }
1996
1997 Py_DECREF(str);
1998 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 if (!str || !compiler_nameop(c, str, Store)) {
2000 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002001 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002003 }
2004 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002006 if (!compiler_body(c, s->v.ClassDef.body)) {
2007 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002009 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002011 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2012 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002014 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015 if (co == NULL)
2016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002017
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002018 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002019 Py_DECREF(co);
2020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021 ADDOP_I(c, CALL_FUNCTION, 0);
2022 ADDOP(c, BUILD_CLASS);
2023 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2024 return 0;
2025 return 1;
2026}
2027
2028static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002029compiler_ifexp(struct compiler *c, expr_ty e)
2030{
2031 basicblock *end, *next;
2032
2033 assert(e->kind == IfExp_kind);
2034 end = compiler_new_block(c);
2035 if (end == NULL)
2036 return 0;
2037 next = compiler_new_block(c);
2038 if (next == NULL)
2039 return 0;
2040 VISIT(c, expr, e->v.IfExp.test);
2041 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2042 ADDOP(c, POP_TOP);
2043 VISIT(c, expr, e->v.IfExp.body);
2044 ADDOP_JREL(c, JUMP_FORWARD, end);
2045 compiler_use_next_block(c, next);
2046 ADDOP(c, POP_TOP);
2047 VISIT(c, expr, e->v.IfExp.orelse);
2048 compiler_use_next_block(c, end);
2049 return 1;
2050}
2051
2052static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002053compiler_lambda(struct compiler *c, expr_ty e)
2054{
2055 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002056 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002057 arguments_ty args = e->v.Lambda.args;
2058 assert(e->kind == Lambda_kind);
2059
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002060 if (!name) {
2061 name = PyString_InternFromString("<lambda>");
2062 if (!name)
2063 return 0;
2064 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065
2066 if (args->defaults)
2067 VISIT_SEQ(c, expr, args->defaults);
2068 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2069 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002070
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002071 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072 compiler_arguments(c, args);
2073
2074 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002075 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2076 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002078 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 if (co == NULL)
2080 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002081
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002082 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002083 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084
2085 return 1;
2086}
2087
2088static int
2089compiler_print(struct compiler *c, stmt_ty s)
2090{
2091 int i, n;
2092 bool dest;
2093
2094 assert(s->kind == Print_kind);
2095 n = asdl_seq_LEN(s->v.Print.values);
2096 dest = false;
2097 if (s->v.Print.dest) {
2098 VISIT(c, expr, s->v.Print.dest);
2099 dest = true;
2100 }
2101 for (i = 0; i < n; i++) {
2102 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2103 if (dest) {
2104 ADDOP(c, DUP_TOP);
2105 VISIT(c, expr, e);
2106 ADDOP(c, ROT_TWO);
2107 ADDOP(c, PRINT_ITEM_TO);
2108 }
2109 else {
2110 VISIT(c, expr, e);
2111 ADDOP(c, PRINT_ITEM);
2112 }
2113 }
2114 if (s->v.Print.nl) {
2115 if (dest)
2116 ADDOP(c, PRINT_NEWLINE_TO)
2117 else
2118 ADDOP(c, PRINT_NEWLINE)
2119 }
2120 else if (dest)
2121 ADDOP(c, POP_TOP);
2122 return 1;
2123}
2124
2125static int
2126compiler_if(struct compiler *c, stmt_ty s)
2127{
2128 basicblock *end, *next;
2129
2130 assert(s->kind == If_kind);
2131 end = compiler_new_block(c);
2132 if (end == NULL)
2133 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002134 next = compiler_new_block(c);
2135 if (next == NULL)
2136 return 0;
2137 VISIT(c, expr, s->v.If.test);
2138 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2139 ADDOP(c, POP_TOP);
2140 VISIT_SEQ(c, stmt, s->v.If.body);
2141 ADDOP_JREL(c, JUMP_FORWARD, end);
2142 compiler_use_next_block(c, next);
2143 ADDOP(c, POP_TOP);
2144 if (s->v.If.orelse)
2145 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002146 compiler_use_next_block(c, end);
2147 return 1;
2148}
2149
2150static int
2151compiler_for(struct compiler *c, stmt_ty s)
2152{
2153 basicblock *start, *cleanup, *end;
2154
2155 start = compiler_new_block(c);
2156 cleanup = compiler_new_block(c);
2157 end = compiler_new_block(c);
2158 if (start == NULL || end == NULL || cleanup == NULL)
2159 return 0;
2160 ADDOP_JREL(c, SETUP_LOOP, end);
2161 if (!compiler_push_fblock(c, LOOP, start))
2162 return 0;
2163 VISIT(c, expr, s->v.For.iter);
2164 ADDOP(c, GET_ITER);
2165 compiler_use_next_block(c, start);
2166 ADDOP_JREL(c, FOR_ITER, cleanup);
2167 VISIT(c, expr, s->v.For.target);
2168 VISIT_SEQ(c, stmt, s->v.For.body);
2169 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2170 compiler_use_next_block(c, cleanup);
2171 ADDOP(c, POP_BLOCK);
2172 compiler_pop_fblock(c, LOOP, start);
2173 VISIT_SEQ(c, stmt, s->v.For.orelse);
2174 compiler_use_next_block(c, end);
2175 return 1;
2176}
2177
2178static int
2179compiler_while(struct compiler *c, stmt_ty s)
2180{
2181 basicblock *loop, *orelse, *end, *anchor = NULL;
2182 int constant = expr_constant(s->v.While.test);
2183
2184 if (constant == 0)
2185 return 1;
2186 loop = compiler_new_block(c);
2187 end = compiler_new_block(c);
2188 if (constant == -1) {
2189 anchor = compiler_new_block(c);
2190 if (anchor == NULL)
2191 return 0;
2192 }
2193 if (loop == NULL || end == NULL)
2194 return 0;
2195 if (s->v.While.orelse) {
2196 orelse = compiler_new_block(c);
2197 if (orelse == NULL)
2198 return 0;
2199 }
2200 else
2201 orelse = NULL;
2202
2203 ADDOP_JREL(c, SETUP_LOOP, end);
2204 compiler_use_next_block(c, loop);
2205 if (!compiler_push_fblock(c, LOOP, loop))
2206 return 0;
2207 if (constant == -1) {
2208 VISIT(c, expr, s->v.While.test);
2209 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2210 ADDOP(c, POP_TOP);
2211 }
2212 VISIT_SEQ(c, stmt, s->v.While.body);
2213 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2214
2215 /* XXX should the two POP instructions be in a separate block
2216 if there is no else clause ?
2217 */
2218
2219 if (constant == -1) {
2220 compiler_use_next_block(c, anchor);
2221 ADDOP(c, POP_TOP);
2222 ADDOP(c, POP_BLOCK);
2223 }
2224 compiler_pop_fblock(c, LOOP, loop);
2225 if (orelse != NULL)
2226 VISIT_SEQ(c, stmt, s->v.While.orelse);
2227 compiler_use_next_block(c, end);
2228
2229 return 1;
2230}
2231
2232static int
2233compiler_continue(struct compiler *c)
2234{
2235 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2236 int i;
2237
2238 if (!c->u->u_nfblocks)
2239 return compiler_error(c, LOOP_ERROR_MSG);
2240 i = c->u->u_nfblocks - 1;
2241 switch (c->u->u_fblock[i].fb_type) {
2242 case LOOP:
2243 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2244 break;
2245 case EXCEPT:
2246 case FINALLY_TRY:
2247 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2248 ;
2249 if (i == -1)
2250 return compiler_error(c, LOOP_ERROR_MSG);
2251 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2252 break;
2253 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002254 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002255 "'continue' not supported inside 'finally' clause");
2256 }
2257
2258 return 1;
2259}
2260
2261/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2262
2263 SETUP_FINALLY L
2264 <code for body>
2265 POP_BLOCK
2266 LOAD_CONST <None>
2267 L: <code for finalbody>
2268 END_FINALLY
2269
2270 The special instructions use the block stack. Each block
2271 stack entry contains the instruction that created it (here
2272 SETUP_FINALLY), the level of the value stack at the time the
2273 block stack entry was created, and a label (here L).
2274
2275 SETUP_FINALLY:
2276 Pushes the current value stack level and the label
2277 onto the block stack.
2278 POP_BLOCK:
2279 Pops en entry from the block stack, and pops the value
2280 stack until its level is the same as indicated on the
2281 block stack. (The label is ignored.)
2282 END_FINALLY:
2283 Pops a variable number of entries from the *value* stack
2284 and re-raises the exception they specify. The number of
2285 entries popped depends on the (pseudo) exception type.
2286
2287 The block stack is unwound when an exception is raised:
2288 when a SETUP_FINALLY entry is found, the exception is pushed
2289 onto the value stack (and the exception condition is cleared),
2290 and the interpreter jumps to the label gotten from the block
2291 stack.
2292*/
2293
2294static int
2295compiler_try_finally(struct compiler *c, stmt_ty s)
2296{
2297 basicblock *body, *end;
2298 body = compiler_new_block(c);
2299 end = compiler_new_block(c);
2300 if (body == NULL || end == NULL)
2301 return 0;
2302
2303 ADDOP_JREL(c, SETUP_FINALLY, end);
2304 compiler_use_next_block(c, body);
2305 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2306 return 0;
2307 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2308 ADDOP(c, POP_BLOCK);
2309 compiler_pop_fblock(c, FINALLY_TRY, body);
2310
2311 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2312 compiler_use_next_block(c, end);
2313 if (!compiler_push_fblock(c, FINALLY_END, end))
2314 return 0;
2315 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2316 ADDOP(c, END_FINALLY);
2317 compiler_pop_fblock(c, FINALLY_END, end);
2318
2319 return 1;
2320}
2321
2322/*
2323 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2324 (The contents of the value stack is shown in [], with the top
2325 at the right; 'tb' is trace-back info, 'val' the exception's
2326 associated value, and 'exc' the exception.)
2327
2328 Value stack Label Instruction Argument
2329 [] SETUP_EXCEPT L1
2330 [] <code for S>
2331 [] POP_BLOCK
2332 [] JUMP_FORWARD L0
2333
2334 [tb, val, exc] L1: DUP )
2335 [tb, val, exc, exc] <evaluate E1> )
2336 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2337 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2338 [tb, val, exc, 1] POP )
2339 [tb, val, exc] POP
2340 [tb, val] <assign to V1> (or POP if no V1)
2341 [tb] POP
2342 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002343 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344
2345 [tb, val, exc, 0] L2: POP
2346 [tb, val, exc] DUP
2347 .............................etc.......................
2348
2349 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002350 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
2352 [] L0: <next statement>
2353
2354 Of course, parts are not generated if Vi or Ei is not present.
2355*/
2356static int
2357compiler_try_except(struct compiler *c, stmt_ty s)
2358{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002359 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 int i, n;
2361
2362 body = compiler_new_block(c);
2363 except = compiler_new_block(c);
2364 orelse = compiler_new_block(c);
2365 end = compiler_new_block(c);
2366 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2367 return 0;
2368 ADDOP_JREL(c, SETUP_EXCEPT, except);
2369 compiler_use_next_block(c, body);
2370 if (!compiler_push_fblock(c, EXCEPT, body))
2371 return 0;
2372 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2373 ADDOP(c, POP_BLOCK);
2374 compiler_pop_fblock(c, EXCEPT, body);
2375 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2376 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2377 compiler_use_next_block(c, except);
2378 for (i = 0; i < n; i++) {
2379 excepthandler_ty handler = asdl_seq_GET(
2380 s->v.TryExcept.handlers, i);
2381 if (!handler->type && i < n-1)
2382 return compiler_error(c, "default 'except:' must be last");
2383 except = compiler_new_block(c);
2384 if (except == NULL)
2385 return 0;
2386 if (handler->type) {
2387 ADDOP(c, DUP_TOP);
2388 VISIT(c, expr, handler->type);
2389 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2390 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2391 ADDOP(c, POP_TOP);
2392 }
2393 ADDOP(c, POP_TOP);
2394 if (handler->name) {
2395 VISIT(c, expr, handler->name);
2396 }
2397 else {
2398 ADDOP(c, POP_TOP);
2399 }
2400 ADDOP(c, POP_TOP);
2401 VISIT_SEQ(c, stmt, handler->body);
2402 ADDOP_JREL(c, JUMP_FORWARD, end);
2403 compiler_use_next_block(c, except);
2404 if (handler->type)
2405 ADDOP(c, POP_TOP);
2406 }
2407 ADDOP(c, END_FINALLY);
2408 compiler_use_next_block(c, orelse);
2409 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2410 compiler_use_next_block(c, end);
2411 return 1;
2412}
2413
2414static int
2415compiler_import_as(struct compiler *c, identifier name, identifier asname)
2416{
2417 /* The IMPORT_NAME opcode was already generated. This function
2418 merely needs to bind the result to a name.
2419
2420 If there is a dot in name, we need to split it and emit a
2421 LOAD_ATTR for each name.
2422 */
2423 const char *src = PyString_AS_STRING(name);
2424 const char *dot = strchr(src, '.');
2425 if (dot) {
2426 /* Consume the base module name to get the first attribute */
2427 src = dot + 1;
2428 while (dot) {
2429 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002430 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002432 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002434 if (!attr)
2435 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002437 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002438 src = dot + 1;
2439 }
2440 }
2441 return compiler_nameop(c, asname, Store);
2442}
2443
2444static int
2445compiler_import(struct compiler *c, stmt_ty s)
2446{
2447 /* The Import node stores a module name like a.b.c as a single
2448 string. This is convenient for all cases except
2449 import a.b.c as d
2450 where we need to parse that string to extract the individual
2451 module names.
2452 XXX Perhaps change the representation to make this case simpler?
2453 */
2454 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002455
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456 for (i = 0; i < n; i++) {
2457 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2458 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002459 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002460
Guido van Rossum45aecf42006-03-15 04:58:47 +00002461 level = PyInt_FromLong(0);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002462 if (level == NULL)
2463 return 0;
2464
2465 ADDOP_O(c, LOAD_CONST, level, consts);
2466 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2468 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2469
2470 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002471 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002472 if (!r)
2473 return r;
2474 }
2475 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476 identifier tmp = alias->name;
2477 const char *base = PyString_AS_STRING(alias->name);
2478 char *dot = strchr(base, '.');
2479 if (dot)
2480 tmp = PyString_FromStringAndSize(base,
2481 dot - base);
2482 r = compiler_nameop(c, tmp, Store);
2483 if (dot) {
2484 Py_DECREF(tmp);
2485 }
2486 if (!r)
2487 return r;
2488 }
2489 }
2490 return 1;
2491}
2492
2493static int
2494compiler_from_import(struct compiler *c, stmt_ty s)
2495{
2496 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002497
2498 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002499 PyObject *level;
2500
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002501 if (!names)
2502 return 0;
2503
Guido van Rossum45aecf42006-03-15 04:58:47 +00002504 level = PyInt_FromLong(s->v.ImportFrom.level);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002505 if (!level) {
2506 Py_DECREF(names);
2507 return 0;
2508 }
2509
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002510 /* build up the names */
2511 for (i = 0; i < n; i++) {
2512 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2513 Py_INCREF(alias->name);
2514 PyTuple_SET_ITEM(names, i, alias->name);
2515 }
2516
2517 if (s->lineno > c->c_future->ff_lineno) {
2518 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2519 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002520 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002521 Py_DECREF(names);
2522 return compiler_error(c,
2523 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002524 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002525
2526 }
2527 }
2528
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002529 ADDOP_O(c, LOAD_CONST, level, consts);
2530 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002531 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002532 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2534 for (i = 0; i < n; i++) {
2535 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2536 identifier store_name;
2537
2538 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2539 assert(n == 1);
2540 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002541 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 }
2543
2544 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2545 store_name = alias->name;
2546 if (alias->asname)
2547 store_name = alias->asname;
2548
2549 if (!compiler_nameop(c, store_name, Store)) {
2550 Py_DECREF(names);
2551 return 0;
2552 }
2553 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002554 /* remove imported module */
2555 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002556 return 1;
2557}
2558
2559static int
2560compiler_assert(struct compiler *c, stmt_ty s)
2561{
2562 static PyObject *assertion_error = NULL;
2563 basicblock *end;
2564
2565 if (Py_OptimizeFlag)
2566 return 1;
2567 if (assertion_error == NULL) {
2568 assertion_error = PyString_FromString("AssertionError");
2569 if (assertion_error == NULL)
2570 return 0;
2571 }
2572 VISIT(c, expr, s->v.Assert.test);
2573 end = compiler_new_block(c);
2574 if (end == NULL)
2575 return 0;
2576 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2577 ADDOP(c, POP_TOP);
2578 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2579 if (s->v.Assert.msg) {
2580 VISIT(c, expr, s->v.Assert.msg);
2581 ADDOP_I(c, RAISE_VARARGS, 2);
2582 }
2583 else {
2584 ADDOP_I(c, RAISE_VARARGS, 1);
2585 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002586 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002587 ADDOP(c, POP_TOP);
2588 return 1;
2589}
2590
2591static int
2592compiler_visit_stmt(struct compiler *c, stmt_ty s)
2593{
2594 int i, n;
2595
2596 c->u->u_lineno = s->lineno;
2597 c->u->u_lineno_set = false;
2598 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002599 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002600 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002601 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002602 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002603 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002604 if (c->u->u_ste->ste_type != FunctionBlock)
2605 return compiler_error(c, "'return' outside function");
2606 if (s->v.Return.value) {
2607 if (c->u->u_ste->ste_generator) {
2608 return compiler_error(c,
2609 "'return' with argument inside generator");
2610 }
2611 VISIT(c, expr, s->v.Return.value);
2612 }
2613 else
2614 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2615 ADDOP(c, RETURN_VALUE);
2616 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002617 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618 VISIT_SEQ(c, expr, s->v.Delete.targets)
2619 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002620 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621 n = asdl_seq_LEN(s->v.Assign.targets);
2622 VISIT(c, expr, s->v.Assign.value);
2623 for (i = 0; i < n; i++) {
2624 if (i < n - 1)
2625 ADDOP(c, DUP_TOP);
2626 VISIT(c, expr,
2627 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2628 }
2629 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002630 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002634 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002635 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002636 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002638 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002640 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641 n = 0;
2642 if (s->v.Raise.type) {
2643 VISIT(c, expr, s->v.Raise.type);
2644 n++;
2645 if (s->v.Raise.inst) {
2646 VISIT(c, expr, s->v.Raise.inst);
2647 n++;
2648 if (s->v.Raise.tback) {
2649 VISIT(c, expr, s->v.Raise.tback);
2650 n++;
2651 }
2652 }
2653 }
2654 ADDOP_I(c, RAISE_VARARGS, n);
2655 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002656 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002658 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002659 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002660 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002662 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002663 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002664 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002665 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002666 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002667 VISIT(c, expr, s->v.Exec.body);
2668 if (s->v.Exec.globals) {
2669 VISIT(c, expr, s->v.Exec.globals);
2670 if (s->v.Exec.locals) {
2671 VISIT(c, expr, s->v.Exec.locals);
2672 } else {
2673 ADDOP(c, DUP_TOP);
2674 }
2675 } else {
2676 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2677 ADDOP(c, DUP_TOP);
2678 }
2679 ADDOP(c, EXEC_STMT);
2680 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002681 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002683 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002684 VISIT(c, expr, s->v.Expr.value);
2685 if (c->c_interactive && c->c_nestlevel <= 1) {
2686 ADDOP(c, PRINT_EXPR);
2687 }
2688 else {
2689 ADDOP(c, POP_TOP);
2690 }
2691 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002692 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002694 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695 if (!c->u->u_nfblocks)
2696 return compiler_error(c, "'break' outside loop");
2697 ADDOP(c, BREAK_LOOP);
2698 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002699 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002701 case With_kind:
2702 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703 }
2704 return 1;
2705}
2706
2707static int
2708unaryop(unaryop_ty op)
2709{
2710 switch (op) {
2711 case Invert:
2712 return UNARY_INVERT;
2713 case Not:
2714 return UNARY_NOT;
2715 case UAdd:
2716 return UNARY_POSITIVE;
2717 case USub:
2718 return UNARY_NEGATIVE;
2719 }
2720 return 0;
2721}
2722
2723static int
2724binop(struct compiler *c, operator_ty op)
2725{
2726 switch (op) {
2727 case Add:
2728 return BINARY_ADD;
2729 case Sub:
2730 return BINARY_SUBTRACT;
2731 case Mult:
2732 return BINARY_MULTIPLY;
2733 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002734 return BINARY_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735 case Mod:
2736 return BINARY_MODULO;
2737 case Pow:
2738 return BINARY_POWER;
2739 case LShift:
2740 return BINARY_LSHIFT;
2741 case RShift:
2742 return BINARY_RSHIFT;
2743 case BitOr:
2744 return BINARY_OR;
2745 case BitXor:
2746 return BINARY_XOR;
2747 case BitAnd:
2748 return BINARY_AND;
2749 case FloorDiv:
2750 return BINARY_FLOOR_DIVIDE;
2751 }
2752 return 0;
2753}
2754
2755static int
2756cmpop(cmpop_ty op)
2757{
2758 switch (op) {
2759 case Eq:
2760 return PyCmp_EQ;
2761 case NotEq:
2762 return PyCmp_NE;
2763 case Lt:
2764 return PyCmp_LT;
2765 case LtE:
2766 return PyCmp_LE;
2767 case Gt:
2768 return PyCmp_GT;
2769 case GtE:
2770 return PyCmp_GE;
2771 case Is:
2772 return PyCmp_IS;
2773 case IsNot:
2774 return PyCmp_IS_NOT;
2775 case In:
2776 return PyCmp_IN;
2777 case NotIn:
2778 return PyCmp_NOT_IN;
2779 }
2780 return PyCmp_BAD;
2781}
2782
2783static int
2784inplace_binop(struct compiler *c, operator_ty op)
2785{
2786 switch (op) {
2787 case Add:
2788 return INPLACE_ADD;
2789 case Sub:
2790 return INPLACE_SUBTRACT;
2791 case Mult:
2792 return INPLACE_MULTIPLY;
2793 case Div:
Guido van Rossum45aecf42006-03-15 04:58:47 +00002794 return INPLACE_TRUE_DIVIDE;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 case Mod:
2796 return INPLACE_MODULO;
2797 case Pow:
2798 return INPLACE_POWER;
2799 case LShift:
2800 return INPLACE_LSHIFT;
2801 case RShift:
2802 return INPLACE_RSHIFT;
2803 case BitOr:
2804 return INPLACE_OR;
2805 case BitXor:
2806 return INPLACE_XOR;
2807 case BitAnd:
2808 return INPLACE_AND;
2809 case FloorDiv:
2810 return INPLACE_FLOOR_DIVIDE;
2811 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002812 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002813 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002814 return 0;
2815}
2816
2817static int
2818compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2819{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002820 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002821 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2822
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002823 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002824 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002825 /* XXX AugStore isn't used anywhere! */
2826
2827 /* First check for assignment to __debug__. Param? */
2828 if ((ctx == Store || ctx == AugStore || ctx == Del)
2829 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2830 return compiler_error(c, "can not assign to __debug__");
2831 }
2832
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002833 mangled = _Py_Mangle(c->u->u_private, name);
2834 if (!mangled)
2835 return 0;
2836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837 op = 0;
2838 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002839 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002840 switch (scope) {
2841 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002842 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843 optype = OP_DEREF;
2844 break;
2845 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002846 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847 optype = OP_DEREF;
2848 break;
2849 case LOCAL:
2850 if (c->u->u_ste->ste_type == FunctionBlock)
2851 optype = OP_FAST;
2852 break;
2853 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002854 if (c->u->u_ste->ste_type == FunctionBlock &&
2855 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856 optype = OP_GLOBAL;
2857 break;
2858 case GLOBAL_EXPLICIT:
2859 optype = OP_GLOBAL;
2860 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002861 default:
2862 /* scope can be 0 */
2863 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 }
2865
2866 /* XXX Leave assert here, but handle __doc__ and the like better */
2867 assert(scope || PyString_AS_STRING(name)[0] == '_');
2868
2869 switch (optype) {
2870 case OP_DEREF:
2871 switch (ctx) {
2872 case Load: op = LOAD_DEREF; break;
2873 case Store: op = STORE_DEREF; break;
2874 case AugLoad:
2875 case AugStore:
2876 break;
2877 case Del:
2878 PyErr_Format(PyExc_SyntaxError,
2879 "can not delete variable '%s' referenced "
2880 "in nested scope",
2881 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002882 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002883 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002885 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002886 PyErr_SetString(PyExc_SystemError,
2887 "param invalid for deref variable");
2888 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002889 }
2890 break;
2891 case OP_FAST:
2892 switch (ctx) {
2893 case Load: op = LOAD_FAST; break;
2894 case Store: op = STORE_FAST; break;
2895 case Del: op = DELETE_FAST; break;
2896 case AugLoad:
2897 case AugStore:
2898 break;
2899 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002900 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002901 PyErr_SetString(PyExc_SystemError,
2902 "param invalid for local variable");
2903 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002904 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002905 ADDOP_O(c, op, mangled, varnames);
2906 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 return 1;
2908 case OP_GLOBAL:
2909 switch (ctx) {
2910 case Load: op = LOAD_GLOBAL; break;
2911 case Store: op = STORE_GLOBAL; break;
2912 case Del: op = DELETE_GLOBAL; break;
2913 case AugLoad:
2914 case AugStore:
2915 break;
2916 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002917 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002918 PyErr_SetString(PyExc_SystemError,
2919 "param invalid for global variable");
2920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 }
2922 break;
2923 case OP_NAME:
2924 switch (ctx) {
2925 case Load: op = LOAD_NAME; break;
2926 case Store: op = STORE_NAME; break;
2927 case Del: op = DELETE_NAME; break;
2928 case AugLoad:
2929 case AugStore:
2930 break;
2931 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002932 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002933 PyErr_SetString(PyExc_SystemError,
2934 "param invalid for name variable");
2935 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 }
2937 break;
2938 }
2939
2940 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002941 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002942 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002943 if (arg < 0)
2944 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002945 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946}
2947
2948static int
2949compiler_boolop(struct compiler *c, expr_ty e)
2950{
2951 basicblock *end;
2952 int jumpi, i, n;
2953 asdl_seq *s;
2954
2955 assert(e->kind == BoolOp_kind);
2956 if (e->v.BoolOp.op == And)
2957 jumpi = JUMP_IF_FALSE;
2958 else
2959 jumpi = JUMP_IF_TRUE;
2960 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002961 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962 return 0;
2963 s = e->v.BoolOp.values;
2964 n = asdl_seq_LEN(s) - 1;
2965 for (i = 0; i < n; ++i) {
2966 VISIT(c, expr, asdl_seq_GET(s, i));
2967 ADDOP_JREL(c, jumpi, end);
2968 ADDOP(c, POP_TOP)
2969 }
2970 VISIT(c, expr, asdl_seq_GET(s, n));
2971 compiler_use_next_block(c, end);
2972 return 1;
2973}
2974
2975static int
2976compiler_list(struct compiler *c, expr_ty e)
2977{
2978 int n = asdl_seq_LEN(e->v.List.elts);
2979 if (e->v.List.ctx == Store) {
2980 ADDOP_I(c, UNPACK_SEQUENCE, n);
2981 }
2982 VISIT_SEQ(c, expr, e->v.List.elts);
2983 if (e->v.List.ctx == Load) {
2984 ADDOP_I(c, BUILD_LIST, n);
2985 }
2986 return 1;
2987}
2988
2989static int
2990compiler_tuple(struct compiler *c, expr_ty e)
2991{
2992 int n = asdl_seq_LEN(e->v.Tuple.elts);
2993 if (e->v.Tuple.ctx == Store) {
2994 ADDOP_I(c, UNPACK_SEQUENCE, n);
2995 }
2996 VISIT_SEQ(c, expr, e->v.Tuple.elts);
2997 if (e->v.Tuple.ctx == Load) {
2998 ADDOP_I(c, BUILD_TUPLE, n);
2999 }
3000 return 1;
3001}
3002
3003static int
3004compiler_compare(struct compiler *c, expr_ty e)
3005{
3006 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003007 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003008
3009 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3010 VISIT(c, expr, e->v.Compare.left);
3011 n = asdl_seq_LEN(e->v.Compare.ops);
3012 assert(n > 0);
3013 if (n > 1) {
3014 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003015 if (cleanup == NULL)
3016 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3018 }
3019 for (i = 1; i < n; i++) {
3020 ADDOP(c, DUP_TOP);
3021 ADDOP(c, ROT_THREE);
3022 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3023 ADDOP_I(c, COMPARE_OP,
3024 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3025 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3026 NEXT_BLOCK(c);
3027 ADDOP(c, POP_TOP);
3028 if (i < (n - 1))
3029 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3030 }
3031 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3032 ADDOP_I(c, COMPARE_OP,
3033 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3034 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3035 if (n > 1) {
3036 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003037 if (end == NULL)
3038 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 ADDOP_JREL(c, JUMP_FORWARD, end);
3040 compiler_use_next_block(c, cleanup);
3041 ADDOP(c, ROT_TWO);
3042 ADDOP(c, POP_TOP);
3043 compiler_use_next_block(c, end);
3044 }
3045 return 1;
3046}
3047
3048static int
3049compiler_call(struct compiler *c, expr_ty e)
3050{
3051 int n, code = 0;
3052
3053 VISIT(c, expr, e->v.Call.func);
3054 n = asdl_seq_LEN(e->v.Call.args);
3055 VISIT_SEQ(c, expr, e->v.Call.args);
3056 if (e->v.Call.keywords) {
3057 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3058 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3059 }
3060 if (e->v.Call.starargs) {
3061 VISIT(c, expr, e->v.Call.starargs);
3062 code |= 1;
3063 }
3064 if (e->v.Call.kwargs) {
3065 VISIT(c, expr, e->v.Call.kwargs);
3066 code |= 2;
3067 }
3068 switch (code) {
3069 case 0:
3070 ADDOP_I(c, CALL_FUNCTION, n);
3071 break;
3072 case 1:
3073 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3074 break;
3075 case 2:
3076 ADDOP_I(c, CALL_FUNCTION_KW, n);
3077 break;
3078 case 3:
3079 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3080 break;
3081 }
3082 return 1;
3083}
3084
3085static int
3086compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003087 asdl_seq *generators, int gen_index,
3088 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089{
3090 /* generate code for the iterator, then each of the ifs,
3091 and then write to the element */
3092
3093 comprehension_ty l;
3094 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003095 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003096
3097 start = compiler_new_block(c);
3098 skip = compiler_new_block(c);
3099 if_cleanup = compiler_new_block(c);
3100 anchor = compiler_new_block(c);
3101
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003102 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3103 anchor == NULL)
3104 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105
3106 l = asdl_seq_GET(generators, gen_index);
3107 VISIT(c, expr, l->iter);
3108 ADDOP(c, GET_ITER);
3109 compiler_use_next_block(c, start);
3110 ADDOP_JREL(c, FOR_ITER, anchor);
3111 NEXT_BLOCK(c);
3112 VISIT(c, expr, l->target);
3113
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003114 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003115 n = asdl_seq_LEN(l->ifs);
3116 for (i = 0; i < n; i++) {
3117 expr_ty e = asdl_seq_GET(l->ifs, i);
3118 VISIT(c, expr, e);
3119 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3120 NEXT_BLOCK(c);
3121 ADDOP(c, POP_TOP);
3122 }
3123
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003124 if (++gen_index < asdl_seq_LEN(generators))
3125 if (!compiler_listcomp_generator(c, tmpname,
3126 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003128
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 /* only append after the last for generator */
3130 if (gen_index >= asdl_seq_LEN(generators)) {
3131 if (!compiler_nameop(c, tmpname, Load))
3132 return 0;
3133 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003134 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003135
3136 compiler_use_next_block(c, skip);
3137 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003138 for (i = 0; i < n; i++) {
3139 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003140 if (i == 0)
3141 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 ADDOP(c, POP_TOP);
3143 }
3144 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3145 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003147 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003148 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149 return 0;
3150
3151 return 1;
3152}
3153
3154static int
3155compiler_listcomp(struct compiler *c, expr_ty e)
3156{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159 static identifier append;
3160 asdl_seq *generators = e->v.ListComp.generators;
3161
3162 assert(e->kind == ListComp_kind);
3163 if (!append) {
3164 append = PyString_InternFromString("append");
3165 if (!append)
3166 return 0;
3167 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003168 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169 if (!tmp)
3170 return 0;
3171 ADDOP_I(c, BUILD_LIST, 0);
3172 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003174 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3175 e->v.ListComp.elt);
3176 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 return rc;
3178}
3179
3180static int
3181compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003182 asdl_seq *generators, int gen_index,
3183 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003184{
3185 /* generate code for the iterator, then each of the ifs,
3186 and then write to the element */
3187
3188 comprehension_ty ge;
3189 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003190 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191
3192 start = compiler_new_block(c);
3193 skip = compiler_new_block(c);
3194 if_cleanup = compiler_new_block(c);
3195 anchor = compiler_new_block(c);
3196 end = compiler_new_block(c);
3197
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003198 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003199 anchor == NULL || end == NULL)
3200 return 0;
3201
3202 ge = asdl_seq_GET(generators, gen_index);
3203 ADDOP_JREL(c, SETUP_LOOP, end);
3204 if (!compiler_push_fblock(c, LOOP, start))
3205 return 0;
3206
3207 if (gen_index == 0) {
3208 /* Receive outermost iter as an implicit argument */
3209 c->u->u_argcount = 1;
3210 ADDOP_I(c, LOAD_FAST, 0);
3211 }
3212 else {
3213 /* Sub-iter - calculate on the fly */
3214 VISIT(c, expr, ge->iter);
3215 ADDOP(c, GET_ITER);
3216 }
3217 compiler_use_next_block(c, start);
3218 ADDOP_JREL(c, FOR_ITER, anchor);
3219 NEXT_BLOCK(c);
3220 VISIT(c, expr, ge->target);
3221
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003222 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003223 n = asdl_seq_LEN(ge->ifs);
3224 for (i = 0; i < n; i++) {
3225 expr_ty e = asdl_seq_GET(ge->ifs, i);
3226 VISIT(c, expr, e);
3227 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3228 NEXT_BLOCK(c);
3229 ADDOP(c, POP_TOP);
3230 }
3231
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003232 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003233 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3234 return 0;
3235
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003236 /* only append after the last 'for' generator */
3237 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238 VISIT(c, expr, elt);
3239 ADDOP(c, YIELD_VALUE);
3240 ADDOP(c, POP_TOP);
3241
3242 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003243 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244 for (i = 0; i < n; i++) {
3245 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003246 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003247 compiler_use_next_block(c, if_cleanup);
3248
3249 ADDOP(c, POP_TOP);
3250 }
3251 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3252 compiler_use_next_block(c, anchor);
3253 ADDOP(c, POP_BLOCK);
3254 compiler_pop_fblock(c, LOOP, start);
3255 compiler_use_next_block(c, end);
3256
3257 return 1;
3258}
3259
3260static int
3261compiler_genexp(struct compiler *c, expr_ty e)
3262{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003263 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 PyCodeObject *co;
3265 expr_ty outermost_iter = ((comprehension_ty)
3266 (asdl_seq_GET(e->v.GeneratorExp.generators,
3267 0)))->iter;
3268
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003269 if (!name) {
3270 name = PyString_FromString("<genexpr>");
3271 if (!name)
3272 return 0;
3273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274
3275 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3276 return 0;
3277 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3278 e->v.GeneratorExp.elt);
3279 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003280 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 if (co == NULL)
3282 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003284 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003285 Py_DECREF(co);
3286
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287 VISIT(c, expr, outermost_iter);
3288 ADDOP(c, GET_ITER);
3289 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290
3291 return 1;
3292}
3293
3294static int
3295compiler_visit_keyword(struct compiler *c, keyword_ty k)
3296{
3297 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3298 VISIT(c, expr, k->value);
3299 return 1;
3300}
3301
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003302/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303 whether they are true or false.
3304
3305 Return values: 1 for true, 0 for false, -1 for non-constant.
3306 */
3307
3308static int
3309expr_constant(expr_ty e)
3310{
3311 switch (e->kind) {
3312 case Num_kind:
3313 return PyObject_IsTrue(e->v.Num.n);
3314 case Str_kind:
3315 return PyObject_IsTrue(e->v.Str.s);
3316 default:
3317 return -1;
3318 }
3319}
3320
Guido van Rossumc2e20742006-02-27 22:32:47 +00003321/*
3322 Implements the with statement from PEP 343.
3323
3324 The semantics outlined in that PEP are as follows:
3325
3326 with EXPR as VAR:
3327 BLOCK
3328
3329 It is implemented roughly as:
3330
3331 context = (EXPR).__context__()
3332 exit = context.__exit__ # not calling it
3333 value = context.__enter__()
3334 try:
3335 VAR = value # if VAR present in the syntax
3336 BLOCK
3337 finally:
3338 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003339 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003340 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003341 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003342 exit(*exc)
3343 */
3344static int
3345compiler_with(struct compiler *c, stmt_ty s)
3346{
3347 static identifier context_attr, enter_attr, exit_attr;
3348 basicblock *block, *finally;
3349 identifier tmpexit, tmpvalue = NULL;
3350
3351 assert(s->kind == With_kind);
3352
3353 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003354 context_attr = PyString_InternFromString("__context__");
3355 if (!context_attr)
3356 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003357 }
3358 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003359 enter_attr = PyString_InternFromString("__enter__");
3360 if (!enter_attr)
3361 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003362 }
3363 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003364 exit_attr = PyString_InternFromString("__exit__");
3365 if (!exit_attr)
3366 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003367 }
3368
3369 block = compiler_new_block(c);
3370 finally = compiler_new_block(c);
3371 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003372 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003373
3374 /* Create a temporary variable to hold context.__exit__ */
3375 tmpexit = compiler_new_tmpname(c);
3376 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003377 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003378 PyArena_AddPyObject(c->c_arena, tmpexit);
3379
3380 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003381 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003382 We need to do this rather than preserving it on the stack
3383 because SETUP_FINALLY remembers the stack level.
3384 We need to do the assignment *inside* the try/finally
3385 so that context.__exit__() is called when the assignment
3386 fails. But we need to call context.__enter__() *before*
3387 the try/finally so that if it fails we won't call
3388 context.__exit__().
3389 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003390 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003391 if (tmpvalue == NULL)
3392 return 0;
3393 PyArena_AddPyObject(c->c_arena, tmpvalue);
3394 }
3395
3396 /* Evaluate (EXPR).__context__() */
3397 VISIT(c, expr, s->v.With.context_expr);
3398 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3399 ADDOP_I(c, CALL_FUNCTION, 0);
3400
3401 /* Squirrel away context.__exit__ */
3402 ADDOP(c, DUP_TOP);
3403 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3404 if (!compiler_nameop(c, tmpexit, Store))
3405 return 0;
3406
3407 /* Call context.__enter__() */
3408 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3409 ADDOP_I(c, CALL_FUNCTION, 0);
3410
3411 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003412 /* Store it in tmpvalue */
3413 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003414 return 0;
3415 }
3416 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003417 /* Discard result from context.__enter__() */
3418 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003419 }
3420
3421 /* Start the try block */
3422 ADDOP_JREL(c, SETUP_FINALLY, finally);
3423
3424 compiler_use_next_block(c, block);
3425 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003427 }
3428
3429 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003430 /* Bind saved result of context.__enter__() to VAR */
3431 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003432 !compiler_nameop(c, tmpvalue, Del))
3433 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003434 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003435 }
3436
3437 /* BLOCK code */
3438 VISIT_SEQ(c, stmt, s->v.With.body);
3439
3440 /* End of try block; start the finally block */
3441 ADDOP(c, POP_BLOCK);
3442 compiler_pop_fblock(c, FINALLY_TRY, block);
3443
3444 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3445 compiler_use_next_block(c, finally);
3446 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003447 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003448
3449 /* Finally block starts; push tmpexit and issue our magic opcode. */
3450 if (!compiler_nameop(c, tmpexit, Load) ||
3451 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003452 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003453 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003454
3455 /* Finally block ends. */
3456 ADDOP(c, END_FINALLY);
3457 compiler_pop_fblock(c, FINALLY_END, finally);
3458 return 1;
3459}
3460
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461static int
3462compiler_visit_expr(struct compiler *c, expr_ty e)
3463{
3464 int i, n;
3465
3466 if (e->lineno > c->u->u_lineno) {
3467 c->u->u_lineno = e->lineno;
3468 c->u->u_lineno_set = false;
3469 }
3470 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003472 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003473 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003474 VISIT(c, expr, e->v.BinOp.left);
3475 VISIT(c, expr, e->v.BinOp.right);
3476 ADDOP(c, binop(c, e->v.BinOp.op));
3477 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003478 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003479 VISIT(c, expr, e->v.UnaryOp.operand);
3480 ADDOP(c, unaryop(e->v.UnaryOp.op));
3481 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003482 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003484 case IfExp_kind:
3485 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003486 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003487 /* XXX get rid of arg? */
3488 ADDOP_I(c, BUILD_MAP, 0);
3489 n = asdl_seq_LEN(e->v.Dict.values);
3490 /* We must arrange things just right for STORE_SUBSCR.
3491 It wants the stack to look like (value) (dict) (key) */
3492 for (i = 0; i < n; i++) {
3493 ADDOP(c, DUP_TOP);
3494 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3495 ADDOP(c, ROT_TWO);
3496 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3497 ADDOP(c, STORE_SUBSCR);
3498 }
3499 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003500 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003502 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503 return compiler_genexp(c, e);
3504 case Yield_kind:
3505 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003506 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003507 /*
3508 for (i = 0; i < c->u->u_nfblocks; i++) {
3509 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3510 return compiler_error(
3511 c, "'yield' not allowed in a 'try' "
3512 "block with a 'finally' clause");
3513 }
3514 */
3515 if (e->v.Yield.value) {
3516 VISIT(c, expr, e->v.Yield.value);
3517 }
3518 else {
3519 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3520 }
3521 ADDOP(c, YIELD_VALUE);
3522 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003525 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003527 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 VISIT(c, expr, e->v.Repr.value);
3529 ADDOP(c, UNARY_CONVERT);
3530 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003531 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3533 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003534 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003535 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3536 break;
3537 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003538 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539 if (e->v.Attribute.ctx != AugStore)
3540 VISIT(c, expr, e->v.Attribute.value);
3541 switch (e->v.Attribute.ctx) {
3542 case AugLoad:
3543 ADDOP(c, DUP_TOP);
3544 /* Fall through to load */
3545 case Load:
3546 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3547 break;
3548 case AugStore:
3549 ADDOP(c, ROT_TWO);
3550 /* Fall through to save */
3551 case Store:
3552 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3553 break;
3554 case Del:
3555 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3556 break;
3557 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003558 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003559 PyErr_SetString(PyExc_SystemError,
3560 "param invalid in attribute expression");
3561 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562 }
3563 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003564 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565 switch (e->v.Subscript.ctx) {
3566 case AugLoad:
3567 VISIT(c, expr, e->v.Subscript.value);
3568 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3569 break;
3570 case Load:
3571 VISIT(c, expr, e->v.Subscript.value);
3572 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3573 break;
3574 case AugStore:
3575 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3576 break;
3577 case Store:
3578 VISIT(c, expr, e->v.Subscript.value);
3579 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3580 break;
3581 case Del:
3582 VISIT(c, expr, e->v.Subscript.value);
3583 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3584 break;
3585 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003586 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003587 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003588 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003589 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003590 }
3591 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003592 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3594 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003595 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003596 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003597 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003598 return compiler_tuple(c, e);
3599 }
3600 return 1;
3601}
3602
3603static int
3604compiler_augassign(struct compiler *c, stmt_ty s)
3605{
3606 expr_ty e = s->v.AugAssign.target;
3607 expr_ty auge;
3608
3609 assert(s->kind == AugAssign_kind);
3610
3611 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003612 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003614 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003615 if (auge == NULL)
3616 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 VISIT(c, expr, auge);
3618 VISIT(c, expr, s->v.AugAssign.value);
3619 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3620 auge->v.Attribute.ctx = AugStore;
3621 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003622 break;
3623 case Subscript_kind:
3624 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003625 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003626 if (auge == NULL)
3627 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003628 VISIT(c, expr, auge);
3629 VISIT(c, expr, s->v.AugAssign.value);
3630 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003631 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003633 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 case Name_kind:
3635 VISIT(c, expr, s->v.AugAssign.target);
3636 VISIT(c, expr, s->v.AugAssign.value);
3637 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3638 return compiler_nameop(c, e->v.Name.id, Store);
3639 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003640 PyErr_Format(PyExc_SystemError,
3641 "invalid node type (%d) for augmented assignment",
3642 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003643 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 }
3645 return 1;
3646}
3647
3648static int
3649compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3650{
3651 struct fblockinfo *f;
3652 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3653 return 0;
3654 f = &c->u->u_fblock[c->u->u_nfblocks++];
3655 f->fb_type = t;
3656 f->fb_block = b;
3657 return 1;
3658}
3659
3660static void
3661compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3662{
3663 struct compiler_unit *u = c->u;
3664 assert(u->u_nfblocks > 0);
3665 u->u_nfblocks--;
3666 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3667 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3668}
3669
3670/* Raises a SyntaxError and returns 0.
3671 If something goes wrong, a different exception may be raised.
3672*/
3673
3674static int
3675compiler_error(struct compiler *c, const char *errstr)
3676{
3677 PyObject *loc;
3678 PyObject *u = NULL, *v = NULL;
3679
3680 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3681 if (!loc) {
3682 Py_INCREF(Py_None);
3683 loc = Py_None;
3684 }
3685 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3686 Py_None, loc);
3687 if (!u)
3688 goto exit;
3689 v = Py_BuildValue("(zO)", errstr, u);
3690 if (!v)
3691 goto exit;
3692 PyErr_SetObject(PyExc_SyntaxError, v);
3693 exit:
3694 Py_DECREF(loc);
3695 Py_XDECREF(u);
3696 Py_XDECREF(v);
3697 return 0;
3698}
3699
3700static int
3701compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003702 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003704 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003705
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003706 /* XXX this code is duplicated */
3707 switch (ctx) {
3708 case AugLoad: /* fall through to Load */
3709 case Load: op = BINARY_SUBSCR; break;
3710 case AugStore:/* fall through to Store */
3711 case Store: op = STORE_SUBSCR; break;
3712 case Del: op = DELETE_SUBSCR; break;
3713 case Param:
3714 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003715 "invalid %s kind %d in subscript\n",
3716 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003717 return 0;
3718 }
3719 if (ctx == AugLoad) {
3720 ADDOP_I(c, DUP_TOPX, 2);
3721 }
3722 else if (ctx == AugStore) {
3723 ADDOP(c, ROT_THREE);
3724 }
3725 ADDOP(c, op);
3726 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727}
3728
3729static int
3730compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3731{
3732 int n = 2;
3733 assert(s->kind == Slice_kind);
3734
3735 /* only handles the cases where BUILD_SLICE is emitted */
3736 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003737 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003738 }
3739 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003740 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003741 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003742
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003743 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003744 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003745 }
3746 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003747 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748 }
3749
3750 if (s->v.Slice.step) {
3751 n++;
3752 VISIT(c, expr, s->v.Slice.step);
3753 }
3754 ADDOP_I(c, BUILD_SLICE, n);
3755 return 1;
3756}
3757
3758static int
3759compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3760{
3761 int op = 0, slice_offset = 0, stack_count = 0;
3762
3763 assert(s->v.Slice.step == NULL);
3764 if (s->v.Slice.lower) {
3765 slice_offset++;
3766 stack_count++;
3767 if (ctx != AugStore)
3768 VISIT(c, expr, s->v.Slice.lower);
3769 }
3770 if (s->v.Slice.upper) {
3771 slice_offset += 2;
3772 stack_count++;
3773 if (ctx != AugStore)
3774 VISIT(c, expr, s->v.Slice.upper);
3775 }
3776
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003777 if (ctx == AugLoad) {
3778 switch (stack_count) {
3779 case 0: ADDOP(c, DUP_TOP); break;
3780 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3781 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3782 }
3783 }
3784 else if (ctx == AugStore) {
3785 switch (stack_count) {
3786 case 0: ADDOP(c, ROT_TWO); break;
3787 case 1: ADDOP(c, ROT_THREE); break;
3788 case 2: ADDOP(c, ROT_FOUR); break;
3789 }
3790 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791
3792 switch (ctx) {
3793 case AugLoad: /* fall through to Load */
3794 case Load: op = SLICE; break;
3795 case AugStore:/* fall through to Store */
3796 case Store: op = STORE_SLICE; break;
3797 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003798 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003799 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003800 PyErr_SetString(PyExc_SystemError,
3801 "param invalid in simple slice");
3802 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003803 }
3804
3805 ADDOP(c, op + slice_offset);
3806 return 1;
3807}
3808
3809static int
3810compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3811 expr_context_ty ctx)
3812{
3813 switch (s->kind) {
3814 case Ellipsis_kind:
3815 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3816 break;
3817 case Slice_kind:
3818 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003819 case Index_kind:
3820 VISIT(c, expr, s->v.Index.value);
3821 break;
3822 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003823 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003824 PyErr_SetString(PyExc_SystemError,
3825 "extended slice invalid in nested slice");
3826 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003827 }
3828 return 1;
3829}
3830
3831
3832static int
3833compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3834{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003835 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003836 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003837 case Index_kind:
3838 kindname = "index";
3839 if (ctx != AugStore) {
3840 VISIT(c, expr, s->v.Index.value);
3841 }
3842 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003843 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003844 kindname = "ellipsis";
3845 if (ctx != AugStore) {
3846 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3847 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 break;
3849 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003850 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003851 if (!s->v.Slice.step)
3852 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003853 if (ctx != AugStore) {
3854 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003855 return 0;
3856 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003857 break;
3858 case ExtSlice_kind:
3859 kindname = "extended slice";
3860 if (ctx != AugStore) {
3861 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3862 for (i = 0; i < n; i++) {
3863 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3864 if (!compiler_visit_nested_slice(c, sub, ctx))
3865 return 0;
3866 }
3867 ADDOP_I(c, BUILD_TUPLE, n);
3868 }
3869 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003870 default:
3871 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003872 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003873 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003874 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003875 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003876}
3877
3878/* do depth-first search of basic block graph, starting with block.
3879 post records the block indices in post-order.
3880
3881 XXX must handle implicit jumps from one block to next
3882*/
3883
3884static void
3885dfs(struct compiler *c, basicblock *b, struct assembler *a)
3886{
3887 int i;
3888 struct instr *instr = NULL;
3889
3890 if (b->b_seen)
3891 return;
3892 b->b_seen = 1;
3893 if (b->b_next != NULL)
3894 dfs(c, b->b_next, a);
3895 for (i = 0; i < b->b_iused; i++) {
3896 instr = &b->b_instr[i];
3897 if (instr->i_jrel || instr->i_jabs)
3898 dfs(c, instr->i_target, a);
3899 }
3900 a->a_postorder[a->a_nblocks++] = b;
3901}
3902
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003903static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3905{
3906 int i;
3907 struct instr *instr;
3908 if (b->b_seen || b->b_startdepth >= depth)
3909 return maxdepth;
3910 b->b_seen = 1;
3911 b->b_startdepth = depth;
3912 for (i = 0; i < b->b_iused; i++) {
3913 instr = &b->b_instr[i];
3914 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3915 if (depth > maxdepth)
3916 maxdepth = depth;
3917 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3918 if (instr->i_jrel || instr->i_jabs) {
3919 maxdepth = stackdepth_walk(c, instr->i_target,
3920 depth, maxdepth);
3921 if (instr->i_opcode == JUMP_ABSOLUTE ||
3922 instr->i_opcode == JUMP_FORWARD) {
3923 goto out; /* remaining code is dead */
3924 }
3925 }
3926 }
3927 if (b->b_next)
3928 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3929out:
3930 b->b_seen = 0;
3931 return maxdepth;
3932}
3933
3934/* Find the flow path that needs the largest stack. We assume that
3935 * cycles in the flow graph have no net effect on the stack depth.
3936 */
3937static int
3938stackdepth(struct compiler *c)
3939{
3940 basicblock *b, *entryblock;
3941 entryblock = NULL;
3942 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3943 b->b_seen = 0;
3944 b->b_startdepth = INT_MIN;
3945 entryblock = b;
3946 }
3947 return stackdepth_walk(c, entryblock, 0, 0);
3948}
3949
3950static int
3951assemble_init(struct assembler *a, int nblocks, int firstlineno)
3952{
3953 memset(a, 0, sizeof(struct assembler));
3954 a->a_lineno = firstlineno;
3955 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3956 if (!a->a_bytecode)
3957 return 0;
3958 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3959 if (!a->a_lnotab)
3960 return 0;
3961 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003962 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003963 if (!a->a_postorder) {
3964 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003966 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967 return 1;
3968}
3969
3970static void
3971assemble_free(struct assembler *a)
3972{
3973 Py_XDECREF(a->a_bytecode);
3974 Py_XDECREF(a->a_lnotab);
3975 if (a->a_postorder)
3976 PyObject_Free(a->a_postorder);
3977}
3978
3979/* Return the size of a basic block in bytes. */
3980
3981static int
3982instrsize(struct instr *instr)
3983{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00003984 if (!instr->i_hasarg)
3985 return 1;
3986 if (instr->i_oparg > 0xffff)
3987 return 6;
3988 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003989}
3990
3991static int
3992blocksize(basicblock *b)
3993{
3994 int i;
3995 int size = 0;
3996
3997 for (i = 0; i < b->b_iused; i++)
3998 size += instrsize(&b->b_instr[i]);
3999 return size;
4000}
4001
4002/* All about a_lnotab.
4003
4004c_lnotab is an array of unsigned bytes disguised as a Python string.
4005It is used to map bytecode offsets to source code line #s (when needed
4006for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004007
Tim Peters2a7f3842001-06-09 09:26:21 +00004008The array is conceptually a list of
4009 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004010pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004011
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004012 byte code offset source code line number
4013 0 1
4014 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004015 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004016 350 307
4017 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004018
4019The first trick is that these numbers aren't stored, only the increments
4020from one row to the next (this doesn't really work, but it's a start):
4021
4022 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4023
4024The second trick is that an unsigned byte can't hold negative values, or
4025values larger than 255, so (a) there's a deep assumption that byte code
4026offsets and their corresponding line #s both increase monotonically, and (b)
4027if at least one column jumps by more than 255 from one row to the next, more
4028than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004029from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004030part. A user of c_lnotab desiring to find the source line number
4031corresponding to a bytecode address A should do something like this
4032
4033 lineno = addr = 0
4034 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004035 addr += addr_incr
4036 if addr > A:
4037 return lineno
4038 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004039
4040In order for this to work, when the addr field increments by more than 255,
4041the line # increment in each pair generated must be 0 until the remaining addr
4042increment is < 256. So, in the example above, com_set_lineno should not (as
4043was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004044255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004045*/
4046
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004047static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004049{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050 int d_bytecode, d_lineno;
4051 int len;
4052 char *lnotab;
4053
4054 d_bytecode = a->a_offset - a->a_lineno_off;
4055 d_lineno = i->i_lineno - a->a_lineno;
4056
4057 assert(d_bytecode >= 0);
4058 assert(d_lineno >= 0);
4059
4060 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004061 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004062
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004063 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004064 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065 nbytes = a->a_lnotab_off + 2 * ncodes;
4066 len = PyString_GET_SIZE(a->a_lnotab);
4067 if (nbytes >= len) {
4068 if (len * 2 < nbytes)
4069 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004070 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004071 len *= 2;
4072 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4073 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004074 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004075 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004076 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004077 *lnotab++ = 255;
4078 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004079 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080 d_bytecode -= ncodes * 255;
4081 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004082 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004083 assert(d_bytecode <= 255);
4084 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004085 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004086 nbytes = a->a_lnotab_off + 2 * ncodes;
4087 len = PyString_GET_SIZE(a->a_lnotab);
4088 if (nbytes >= len) {
4089 if (len * 2 < nbytes)
4090 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004091 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004092 len *= 2;
4093 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4094 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004095 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4097 *lnotab++ = 255;
4098 *lnotab++ = d_bytecode;
4099 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004100 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004101 *lnotab++ = 255;
4102 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004103 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004104 d_lineno -= ncodes * 255;
4105 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004106 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004107
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004108 len = PyString_GET_SIZE(a->a_lnotab);
4109 if (a->a_lnotab_off + 2 >= len) {
4110 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004111 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004112 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004114
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115 a->a_lnotab_off += 2;
4116 if (d_bytecode) {
4117 *lnotab++ = d_bytecode;
4118 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004119 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004120 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121 *lnotab++ = 0;
4122 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004123 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 a->a_lineno = i->i_lineno;
4125 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004126 return 1;
4127}
4128
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129/* assemble_emit()
4130 Extend the bytecode with a new instruction.
4131 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004132*/
4133
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004134static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004135assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004136{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004137 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 int len = PyString_GET_SIZE(a->a_bytecode);
4139 char *code;
4140
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004141 size = instrsize(i);
4142 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004143 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004144 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004145 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004147 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148 if (a->a_offset + size >= len) {
4149 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004150 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004151 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4153 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004154 if (size == 6) {
4155 assert(i->i_hasarg);
4156 *code++ = (char)EXTENDED_ARG;
4157 *code++ = ext & 0xff;
4158 *code++ = ext >> 8;
4159 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004160 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004161 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004162 if (i->i_hasarg) {
4163 assert(size == 3 || size == 6);
4164 *code++ = arg & 0xff;
4165 *code++ = arg >> 8;
4166 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004167 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004168}
4169
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004170static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004171assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004172{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004173 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004174 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004175 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004176
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177 /* Compute the size of each block and fixup jump args.
4178 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004179start:
4180 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004181 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004182 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 bsize = blocksize(b);
4184 b->b_offset = totsize;
4185 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004186 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004187 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4189 bsize = b->b_offset;
4190 for (i = 0; i < b->b_iused; i++) {
4191 struct instr *instr = &b->b_instr[i];
4192 /* Relative jumps are computed relative to
4193 the instruction pointer after fetching
4194 the jump instruction.
4195 */
4196 bsize += instrsize(instr);
4197 if (instr->i_jabs)
4198 instr->i_oparg = instr->i_target->b_offset;
4199 else if (instr->i_jrel) {
4200 int delta = instr->i_target->b_offset - bsize;
4201 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004202 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004203 else
4204 continue;
4205 if (instr->i_oparg > 0xffff)
4206 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004207 }
4208 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004209
4210 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004211 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004212 with a better solution.
4213
4214 In the meantime, should the goto be dropped in favor
4215 of a loop?
4216
4217 The issue is that in the first loop blocksize() is called
4218 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004219 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004220 i_oparg is calculated in the second loop above.
4221
4222 So we loop until we stop seeing new EXTENDED_ARGs.
4223 The only EXTENDED_ARGs that could be popping up are
4224 ones in jump instructions. So this should converge
4225 fairly quickly.
4226 */
4227 if (last_extended_arg_count != extended_arg_count) {
4228 last_extended_arg_count = extended_arg_count;
4229 goto start;
4230 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004231}
4232
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004233static PyObject *
4234dict_keys_inorder(PyObject *dict, int offset)
4235{
4236 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004237 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004238
4239 tuple = PyTuple_New(size);
4240 if (tuple == NULL)
4241 return NULL;
4242 while (PyDict_Next(dict, &pos, &k, &v)) {
4243 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004244 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004245 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004246 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004247 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004248 PyTuple_SET_ITEM(tuple, i - offset, k);
4249 }
4250 return tuple;
4251}
4252
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004253static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004254compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004255{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004256 PySTEntryObject *ste = c->u->u_ste;
4257 int flags = 0, n;
4258 if (ste->ste_type != ModuleBlock)
4259 flags |= CO_NEWLOCALS;
4260 if (ste->ste_type == FunctionBlock) {
4261 if (!ste->ste_unoptimized)
4262 flags |= CO_OPTIMIZED;
4263 if (ste->ste_nested)
4264 flags |= CO_NESTED;
4265 if (ste->ste_generator)
4266 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004267 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004268 if (ste->ste_varargs)
4269 flags |= CO_VARARGS;
4270 if (ste->ste_varkeywords)
4271 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004272 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004273 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004274
4275 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004276 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004278 n = PyDict_Size(c->u->u_freevars);
4279 if (n < 0)
4280 return -1;
4281 if (n == 0) {
4282 n = PyDict_Size(c->u->u_cellvars);
4283 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004284 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285 if (n == 0) {
4286 flags |= CO_NOFREE;
4287 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004288 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004289
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004290 return flags;
4291}
4292
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004293static PyCodeObject *
4294makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004295{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004296 PyObject *tmp;
4297 PyCodeObject *co = NULL;
4298 PyObject *consts = NULL;
4299 PyObject *names = NULL;
4300 PyObject *varnames = NULL;
4301 PyObject *filename = NULL;
4302 PyObject *name = NULL;
4303 PyObject *freevars = NULL;
4304 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004305 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004306 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308 tmp = dict_keys_inorder(c->u->u_consts, 0);
4309 if (!tmp)
4310 goto error;
4311 consts = PySequence_List(tmp); /* optimize_code requires a list */
4312 Py_DECREF(tmp);
4313
4314 names = dict_keys_inorder(c->u->u_names, 0);
4315 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4316 if (!consts || !names || !varnames)
4317 goto error;
4318
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004319 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4320 if (!cellvars)
4321 goto error;
4322 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4323 if (!freevars)
4324 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 filename = PyString_FromString(c->c_filename);
4326 if (!filename)
4327 goto error;
4328
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004329 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004330 flags = compute_code_flags(c);
4331 if (flags < 0)
4332 goto error;
4333
4334 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4335 if (!bytecode)
4336 goto error;
4337
4338 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4339 if (!tmp)
4340 goto error;
4341 Py_DECREF(consts);
4342 consts = tmp;
4343
4344 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4345 bytecode, consts, names, varnames,
4346 freevars, cellvars,
4347 filename, c->u->u_name,
4348 c->u->u_firstlineno,
4349 a->a_lnotab);
4350 error:
4351 Py_XDECREF(consts);
4352 Py_XDECREF(names);
4353 Py_XDECREF(varnames);
4354 Py_XDECREF(filename);
4355 Py_XDECREF(name);
4356 Py_XDECREF(freevars);
4357 Py_XDECREF(cellvars);
4358 Py_XDECREF(bytecode);
4359 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004360}
4361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004362static PyCodeObject *
4363assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004364{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365 basicblock *b, *entryblock;
4366 struct assembler a;
4367 int i, j, nblocks;
4368 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004369
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004370 /* Make sure every block that falls off the end returns None.
4371 XXX NEXT_BLOCK() isn't quite right, because if the last
4372 block ends with a jump or return b_next shouldn't set.
4373 */
4374 if (!c->u->u_curblock->b_return) {
4375 NEXT_BLOCK(c);
4376 if (addNone)
4377 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4378 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004379 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381 nblocks = 0;
4382 entryblock = NULL;
4383 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4384 nblocks++;
4385 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004386 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004387
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004388 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4389 goto error;
4390 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004391
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004392 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004393 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004394
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395 /* Emit code in reverse postorder from dfs. */
4396 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004397 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398 for (j = 0; j < b->b_iused; j++)
4399 if (!assemble_emit(&a, &b->b_instr[j]))
4400 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004401 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004403 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4404 goto error;
4405 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4406 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 co = makecode(c, &a);
4409 error:
4410 assemble_free(&a);
4411 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004412}