blob: 45fc3698492f05c93453807b04c1aa995faa3faf [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Jeremy Hyltone9357b22006-03-01 15:47:05 +00008 * 2. Builds a symbol table. See symtable.c.
9 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Jeremy Hyltone9357b22006-03-01 15:47:05 +000011 * this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012 *
13 * Note that compiler_mod() suggests module, but the module ast type
14 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000015 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000016 * CAUTION: The VISIT_* macros abort the current function when they
17 * encounter a problem. So don't invoke them when there is memory
18 * which needs to be released. Code blocks are OK, as the compiler
19 * structure takes care of releasing those.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000021
Guido van Rossum79f25d91997-04-29 20:08:16 +000022#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000024#include "Python-ast.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000025#include "node.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000026#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000027#include "ast.h"
28#include "code.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000029#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Guido van Rossum10dc2e81990-11-18 17:27:39 +000031#include "opcode.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000032
Guido van Rossum8e793d91997-03-03 19:13:14 +000033int Py_OptimizeFlag = 0;
34
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035/*
Jeremy Hyltone9357b22006-03-01 15:47:05 +000036 ISSUES:
Guido van Rossum8861b741996-07-30 16:49:37 +000037
Jeremy Hyltone9357b22006-03-01 15:47:05 +000038 opcode_stack_effect() function should be reviewed since stack depth bugs
39 could be really hard to find later.
Jeremy Hyltoneab156f2001-01-30 01:24:43 +000040
Jeremy Hyltone9357b22006-03-01 15:47:05 +000041 Dead code is being generated (i.e. after unconditional jumps).
Neal Norwitz3a5468e2006-03-02 04:06:10 +000042 XXX(nnorwitz): not sure this is still true
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000043*/
Jeremy Hylton29906ee2001-02-27 04:23:34 +000044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000045#define DEFAULT_BLOCK_SIZE 16
46#define DEFAULT_BLOCKS 8
47#define DEFAULT_CODE_SIZE 128
48#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Neal Norwitz08b401f2006-01-07 21:24:09 +000051 unsigned i_jabs : 1;
52 unsigned i_jrel : 1;
53 unsigned i_hasarg : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 unsigned char i_opcode;
55 int i_oparg;
56 struct basicblock_ *i_target; /* target block (if jump instruction) */
57 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000058};
59
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060typedef struct basicblock_ {
61 /* next block in the list of blocks for a unit (don't confuse with
62 * b_next) */
63 struct basicblock_ *b_list;
64 /* number of instructions used */
65 int b_iused;
66 /* length of instruction array (b_instr) */
67 int b_ialloc;
68 /* pointer to an array of instructions, initially NULL */
69 struct instr *b_instr;
70 /* If b_next is non-NULL, it is a pointer to the next
71 block reached by normal control flow. */
72 struct basicblock_ *b_next;
73 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000074 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000076 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000077 /* depth of stack upon entry of block, computed by stackdepth() */
78 int b_startdepth;
79 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000080 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000081} basicblock;
82
83/* fblockinfo tracks the current frame block.
84
Jeremy Hyltone9357b22006-03-01 15:47:05 +000085A frame block is used to handle loops, try/except, and try/finally.
86It's called a frame block to distinguish it from a basic block in the
87compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000088*/
89
90enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
91
92struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000093 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000094 basicblock *fb_block;
95};
96
97/* The following items change on entry and exit of code blocks.
98 They must be saved and restored when returning to a block.
99*/
100struct compiler_unit {
101 PySTEntryObject *u_ste;
102
103 PyObject *u_name;
104 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000105 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000106 the argument for opcodes that refer to those collections.
107 */
108 PyObject *u_consts; /* all constants */
109 PyObject *u_names; /* all names */
110 PyObject *u_varnames; /* local variables */
111 PyObject *u_cellvars; /* cell variables */
112 PyObject *u_freevars; /* free variables */
113
114 PyObject *u_private; /* for private name mangling */
115
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000116 int u_argcount; /* number of arguments for block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000117 basicblock *u_blocks; /* pointer to list of blocks */
118 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000119 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
121 int u_nfblocks;
122 struct fblockinfo u_fblock[CO_MAXBLOCKS];
123
124 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000125 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126 bool u_lineno_set; /* boolean to indicate whether instr
127 has been generated with current lineno */
128};
129
130/* This struct captures the global state of a compilation.
131
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000132The u pointer points to the current compilation unit, while units
133for enclosing blocks are stored in c_stack. The u and c_stack are
134managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000135*/
136
137struct compiler {
138 const char *c_filename;
139 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000140 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000141 PyCompilerFlags *c_flags;
142
143 int c_interactive;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000144 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000146 struct compiler_unit *u; /* compiler state for current block */
147 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000150};
151
152struct assembler {
153 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000154 int a_offset; /* offset into bytecode */
155 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156 basicblock **a_postorder; /* list of blocks in dfs postorder */
157 PyObject *a_lnotab; /* string containing lnotab */
158 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000159 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160 int a_lineno_off; /* bytecode offset of last lineno */
161};
162
163static int compiler_enter_scope(struct compiler *, identifier, void *, int);
164static void compiler_free(struct compiler *);
165static basicblock *compiler_new_block(struct compiler *);
166static int compiler_next_instr(struct compiler *, basicblock *);
167static int compiler_addop(struct compiler *, int);
168static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
169static int compiler_addop_i(struct compiler *, int, int);
170static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171static basicblock *compiler_use_new_block(struct compiler *);
172static int compiler_error(struct compiler *, const char *);
173static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
174
175static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
176static int compiler_visit_stmt(struct compiler *, stmt_ty);
177static int compiler_visit_keyword(struct compiler *, keyword_ty);
178static int compiler_visit_expr(struct compiler *, expr_ty);
179static int compiler_augassign(struct compiler *, stmt_ty);
180static int compiler_visit_slice(struct compiler *, slice_ty,
181 expr_context_ty);
182
183static int compiler_push_fblock(struct compiler *, enum fblocktype,
184 basicblock *);
185static void compiler_pop_fblock(struct compiler *, enum fblocktype,
186 basicblock *);
187
188static int inplace_binop(struct compiler *, operator_ty);
189static int expr_constant(expr_ty e);
190
Guido van Rossumc2e20742006-02-27 22:32:47 +0000191static int compiler_with(struct compiler *, stmt_ty);
192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193static PyCodeObject *assemble(struct compiler *, int addNone);
194static PyObject *__doc__;
195
196PyObject *
197_Py_Mangle(PyObject *private, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000198{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000199 /* Name mangling: __private becomes _classname__private.
200 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000201 const char *p, *name = PyString_AsString(ident);
202 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203 size_t nlen, plen;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000204 if (private == NULL || name == NULL || name[0] != '_' ||
205 name[1] != '_') {
206 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208 }
209 p = PyString_AsString(private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210 nlen = strlen(name);
211 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000212 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000214 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 /* Strip leading underscores from class name */
216 while (*p == '_')
217 p++;
218 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000221 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000222 plen = strlen(p);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000223 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
224 if (!ident)
225 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000226 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000227 buffer = PyString_AS_STRING(ident);
228 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229 strncpy(buffer+1, p, plen);
230 strcpy(buffer+1+plen, name);
231 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000232}
233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234static int
235compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000236{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000237 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000238
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000239 c->c_stack = PyList_New(0);
240 if (!c->c_stack)
241 return 0;
242
243 return 1;
244}
245
246PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000247PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000248 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249{
250 struct compiler c;
251 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000252 PyCompilerFlags local_flags;
253 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000255 if (!__doc__) {
256 __doc__ = PyString_InternFromString("__doc__");
257 if (!__doc__)
258 return NULL;
259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000260
261 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000262 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000265 c.c_future = PyFuture_FromAST(mod, filename);
266 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000267 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000268 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000269 local_flags.cf_flags = 0;
270 flags = &local_flags;
271 }
272 merged = c.c_future->ff_features | flags->cf_flags;
273 c.c_future->ff_features = merged;
274 flags->cf_flags = merged;
275 c.c_flags = flags;
276 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
278 c.c_st = PySymtable_Build(mod, filename, c.c_future);
279 if (c.c_st == NULL) {
280 if (!PyErr_Occurred())
281 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000282 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000283 }
284
285 /* XXX initialize to NULL for now, need to handle */
286 c.c_encoding = NULL;
287
288 co = compiler_mod(&c, mod);
289
Thomas Wouters1175c432006-02-27 22:49:54 +0000290 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000291 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000292 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000293 return co;
294}
295
296PyCodeObject *
297PyNode_Compile(struct _node *n, const char *filename)
298{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000299 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000300 PyArena *arena = PyArena_New();
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000301 mod_ty mod = PyAST_FromNode(n, NULL, filename, arena);
302 if (mod)
303 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000304 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000305 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000306}
307
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000308static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000309compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000310{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000311 if (c->c_st)
312 PySymtable_Free(c->c_st);
313 if (c->c_future)
Neal Norwitzb6fc9df2005-11-13 18:50:34 +0000314 PyMem_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000315 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000316}
317
Guido van Rossum79f25d91997-04-29 20:08:16 +0000318static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000320{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000321 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322 PyObject *v, *k, *dict = PyDict_New();
Guido van Rossumd076c731998-10-07 19:42:25 +0000323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324 n = PyList_Size(list);
325 for (i = 0; i < n; i++) {
326 v = PyInt_FromLong(i);
327 if (!v) {
328 Py_DECREF(dict);
329 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000330 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000331 k = PyList_GET_ITEM(list, i);
332 k = Py_BuildValue("(OO)", k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000333 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
334 Py_XDECREF(k);
335 Py_DECREF(v);
336 Py_DECREF(dict);
337 return NULL;
338 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000339 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342 return dict;
343}
344
345/* Return new dict containing names from src that match scope(s).
346
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000347src is a symbol table dictionary. If the scope of a name matches
348either scope_type or flag is set, insert it into the new dict. The
349values are integers, starting at offset and increasing by one for
350each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351*/
352
353static PyObject *
354dictbytype(PyObject *src, int scope_type, int flag, int offset)
355{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357 PyObject *k, *v, *dest = PyDict_New();
358
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000359 assert(offset >= 0);
360 if (dest == NULL)
361 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
363 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000364 /* XXX this should probably be a macro in symtable.h */
365 assert(PyInt_Check(v));
366 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000367
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000368 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
369 PyObject *tuple, *item = PyInt_FromLong(i);
370 if (item == NULL) {
371 Py_DECREF(dest);
372 return NULL;
373 }
374 i++;
375 tuple = Py_BuildValue("(OO)", k, k->ob_type);
376 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
377 Py_DECREF(item);
378 Py_DECREF(dest);
379 Py_XDECREF(tuple);
380 return NULL;
381 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000382 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000383 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000385 }
386 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000387}
388
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000389/* Begin: Peephole optimizations ----------------------------------------- */
390
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000391#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000392#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000393#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
394#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000395#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000396#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397#define ISBASICBLOCK(blocks, start, bytes) \
398 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000399
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000400/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000401 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000402 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000403 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000404 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000405 Bails out with no change if one or more of the LOAD_CONSTs is missing.
406 Also works for BUILD_LIST when followed by an "in" or "not in" test.
407*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000408static int
409tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
410{
411 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000413
414 /* Pre-conditions */
415 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000416 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000417 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000419 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000420
421 /* Buildup new tuple of constants */
422 newconst = PyTuple_New(n);
423 if (newconst == NULL)
424 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000425 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000426 for (i=0 ; i<n ; i++) {
427 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000428 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000429 constant = PyList_GET_ITEM(consts, arg);
430 Py_INCREF(constant);
431 PyTuple_SET_ITEM(newconst, i, constant);
432 }
433
434 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000435 if (PyList_Append(consts, newconst)) {
436 Py_DECREF(newconst);
437 return 0;
438 }
439 Py_DECREF(newconst);
440
441 /* Write NOPs over old LOAD_CONSTS and
442 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
443 memset(codestr, NOP, n*3);
444 codestr[n*3] = LOAD_CONST;
445 SETARG(codestr, (n*3), len_consts);
446 return 1;
447}
448
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000449/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000450 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000451 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000452 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000453 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000454 Abandons the transformation if the folding fails (i.e. 1+'a').
455 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456 is below a threshold value. That keeps pyc files from
457 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000458*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000459static int
460fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
461{
462 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000463 Py_ssize_t len_consts, size;
464 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000465
466 /* Pre-conditions */
467 assert(PyList_CheckExact(consts));
468 assert(codestr[0] == LOAD_CONST);
469 assert(codestr[3] == LOAD_CONST);
470
471 /* Create new constant */
472 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
473 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
474 opcode = codestr[6];
475 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000476 case BINARY_POWER:
477 newconst = PyNumber_Power(v, w, Py_None);
478 break;
479 case BINARY_MULTIPLY:
480 newconst = PyNumber_Multiply(v, w);
481 break;
482 case BINARY_DIVIDE:
483 /* Cannot fold this operation statically since
484 the result can depend on the run-time presence
485 of the -Qnew flag */
486 return 0;
487 case BINARY_TRUE_DIVIDE:
488 newconst = PyNumber_TrueDivide(v, w);
489 break;
490 case BINARY_FLOOR_DIVIDE:
491 newconst = PyNumber_FloorDivide(v, w);
492 break;
493 case BINARY_MODULO:
494 newconst = PyNumber_Remainder(v, w);
495 break;
496 case BINARY_ADD:
497 newconst = PyNumber_Add(v, w);
498 break;
499 case BINARY_SUBTRACT:
500 newconst = PyNumber_Subtract(v, w);
501 break;
502 case BINARY_SUBSCR:
503 newconst = PyObject_GetItem(v, w);
504 break;
505 case BINARY_LSHIFT:
506 newconst = PyNumber_Lshift(v, w);
507 break;
508 case BINARY_RSHIFT:
509 newconst = PyNumber_Rshift(v, w);
510 break;
511 case BINARY_AND:
512 newconst = PyNumber_And(v, w);
513 break;
514 case BINARY_XOR:
515 newconst = PyNumber_Xor(v, w);
516 break;
517 case BINARY_OR:
518 newconst = PyNumber_Or(v, w);
519 break;
520 default:
521 /* Called with an unknown opcode */
522 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000523 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000524 opcode);
525 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000526 }
527 if (newconst == NULL) {
528 PyErr_Clear();
529 return 0;
530 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000531 size = PyObject_Size(newconst);
532 if (size == -1)
533 PyErr_Clear();
534 else if (size > 20) {
535 Py_DECREF(newconst);
536 return 0;
537 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000538
539 /* Append folded constant into consts table */
540 len_consts = PyList_GET_SIZE(consts);
541 if (PyList_Append(consts, newconst)) {
542 Py_DECREF(newconst);
543 return 0;
544 }
545 Py_DECREF(newconst);
546
547 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
548 memset(codestr, NOP, 4);
549 codestr[4] = LOAD_CONST;
550 SETARG(codestr, 4, len_consts);
551 return 1;
552}
553
Raymond Hettinger80121492005-02-20 12:41:32 +0000554static int
555fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
556{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000557 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000558 Py_ssize_t len_consts;
559 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000560
561 /* Pre-conditions */
562 assert(PyList_CheckExact(consts));
563 assert(codestr[0] == LOAD_CONST);
564
565 /* Create new constant */
566 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
567 opcode = codestr[3];
568 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000569 case UNARY_NEGATIVE:
570 /* Preserve the sign of -0.0 */
571 if (PyObject_IsTrue(v) == 1)
572 newconst = PyNumber_Negative(v);
573 break;
574 case UNARY_CONVERT:
575 newconst = PyObject_Repr(v);
576 break;
577 case UNARY_INVERT:
578 newconst = PyNumber_Invert(v);
579 break;
580 default:
581 /* Called with an unknown opcode */
582 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000583 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000584 opcode);
585 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000586 }
587 if (newconst == NULL) {
588 PyErr_Clear();
589 return 0;
590 }
591
592 /* Append folded constant into consts table */
593 len_consts = PyList_GET_SIZE(consts);
594 if (PyList_Append(consts, newconst)) {
595 Py_DECREF(newconst);
596 return 0;
597 }
598 Py_DECREF(newconst);
599
600 /* Write NOP LOAD_CONST newconst */
601 codestr[0] = NOP;
602 codestr[1] = LOAD_CONST;
603 SETARG(codestr, 1, len_consts);
604 return 1;
605}
606
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000607static unsigned int *
608markblocks(unsigned char *code, int len)
609{
610 unsigned int *blocks = PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000611 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000612
613 if (blocks == NULL)
614 return NULL;
615 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000616
617 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000618 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
619 opcode = code[i];
620 switch (opcode) {
621 case FOR_ITER:
622 case JUMP_FORWARD:
623 case JUMP_IF_FALSE:
624 case JUMP_IF_TRUE:
625 case JUMP_ABSOLUTE:
626 case CONTINUE_LOOP:
627 case SETUP_LOOP:
628 case SETUP_EXCEPT:
629 case SETUP_FINALLY:
630 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000631 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000632 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000633 }
634 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000635 /* Build block numbers in the second pass */
636 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000637 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000638 blocks[i] = blockcnt;
639 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000640 return blocks;
641}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000642
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000643/* Perform basic peephole optimizations to components of a code object.
644 The consts object should still be in list form to allow new constants
645 to be appended.
646
647 To keep the optimizer simple, it bails out (does nothing) for code
648 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000649 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000650 the lineno table has complex encoding for gaps >= 255.
651
652 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000653 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000654 smaller. For those that reduce size, the gaps are initially filled with
655 NOPs. Later those NOPs are removed and the jump addresses retargeted in
656 a single pass. Line numbering is adjusted accordingly. */
657
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000658static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000659optimize_code(PyObject *code, PyObject* consts, PyObject *names,
660 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000661{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000662 Py_ssize_t i, j, codelen;
663 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000664 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000665 unsigned char *codestr = NULL;
666 unsigned char *lineno;
667 int *addrmap = NULL;
668 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000669 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000670 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000671 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000672
Raymond Hettingereffb3932004-10-30 08:55:08 +0000673 /* Bail out if an exception is set */
674 if (PyErr_Occurred())
675 goto exitUnchanged;
676
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000677 /* Bypass optimization when the lineno table is too complex */
678 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000679 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000680 tabsiz = PyString_GET_SIZE(lineno_obj);
681 if (memchr(lineno, 255, tabsiz) != NULL)
682 goto exitUnchanged;
683
Raymond Hettingera12fa142004-08-24 04:34:16 +0000684 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000685 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000686 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000687 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000688 goto exitUnchanged;
689
690 /* Make a modifiable copy of the code string */
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000691 codestr = PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000692 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000693 goto exitUnchanged;
694 codestr = memcpy(codestr, PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000695
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000696 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000697 the various transformation patterns to look ahead several
698 instructions without additional checks to make sure they are not
699 looking beyond the end of the code string.
700 */
701 if (codestr[codelen-1] != RETURN_VALUE)
702 goto exitUnchanged;
703
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000704 /* Mapping to new jump targets after NOPs are removed */
705 addrmap = PyMem_Malloc(codelen * sizeof(int));
706 if (addrmap == NULL)
707 goto exitUnchanged;
708
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000709 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000710 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000711 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000712 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000713
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000714 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000715 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000716
717 lastlc = cumlc;
718 cumlc = 0;
719
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000720 switch (opcode) {
721
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000722 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
723 with JUMP_IF_TRUE POP_TOP */
724 case UNARY_NOT:
725 if (codestr[i+1] != JUMP_IF_FALSE ||
726 codestr[i+4] != POP_TOP ||
727 !ISBASICBLOCK(blocks,i,5))
728 continue;
729 tgt = GETJUMPTGT(codestr, (i+1));
730 if (codestr[tgt] != POP_TOP)
731 continue;
732 j = GETARG(codestr, i+1) + 1;
733 codestr[i] = JUMP_IF_TRUE;
734 SETARG(codestr, i, j);
735 codestr[i+3] = POP_TOP;
736 codestr[i+4] = NOP;
737 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000738
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000739 /* not a is b --> a is not b
740 not a in b --> a not in b
741 not a is not b --> a is b
742 not a not in b --> a in b
743 */
744 case COMPARE_OP:
745 j = GETARG(codestr, i);
746 if (j < 6 || j > 9 ||
747 codestr[i+3] != UNARY_NOT ||
748 !ISBASICBLOCK(blocks,i,4))
749 continue;
750 SETARG(codestr, i, (j^1));
751 codestr[i+3] = NOP;
752 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000753
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000754 /* Replace LOAD_GLOBAL/LOAD_NAME None
755 with LOAD_CONST None */
756 case LOAD_NAME:
757 case LOAD_GLOBAL:
758 j = GETARG(codestr, i);
759 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
760 if (name == NULL || strcmp(name, "None") != 0)
761 continue;
762 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
763 if (PyList_GET_ITEM(consts, j) == Py_None) {
764 codestr[i] = LOAD_CONST;
765 SETARG(codestr, i, j);
766 cumlc = lastlc + 1;
767 break;
768 }
769 }
770 break;
771
772 /* Skip over LOAD_CONST trueconst
773 JUMP_IF_FALSE xx POP_TOP */
774 case LOAD_CONST:
775 cumlc = lastlc + 1;
776 j = GETARG(codestr, i);
777 if (codestr[i+3] != JUMP_IF_FALSE ||
778 codestr[i+6] != POP_TOP ||
779 !ISBASICBLOCK(blocks,i,7) ||
780 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
781 continue;
782 memset(codestr+i, NOP, 7);
783 cumlc = 0;
784 break;
785
786 /* Try to fold tuples of constants (includes a case for lists
787 which are only used for "in" and "not in" tests).
788 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
789 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
790 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
791 case BUILD_TUPLE:
792 case BUILD_LIST:
793 j = GETARG(codestr, i);
794 h = i - 3 * j;
795 if (h >= 0 &&
796 j <= lastlc &&
797 ((opcode == BUILD_TUPLE &&
798 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
799 (opcode == BUILD_LIST &&
800 codestr[i+3]==COMPARE_OP &&
801 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
802 (GETARG(codestr,i+3)==6 ||
803 GETARG(codestr,i+3)==7))) &&
804 tuple_of_constants(&codestr[h], j, consts)) {
805 assert(codestr[i] == LOAD_CONST);
806 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000807 break;
808 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000809 if (codestr[i+3] != UNPACK_SEQUENCE ||
810 !ISBASICBLOCK(blocks,i,6) ||
811 j != GETARG(codestr, i+3))
812 continue;
813 if (j == 1) {
814 memset(codestr+i, NOP, 6);
815 } else if (j == 2) {
816 codestr[i] = ROT_TWO;
817 memset(codestr+i+1, NOP, 5);
818 } else if (j == 3) {
819 codestr[i] = ROT_THREE;
820 codestr[i+1] = ROT_TWO;
821 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000822 }
823 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000824
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000825 /* Fold binary ops on constants.
826 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
827 case BINARY_POWER:
828 case BINARY_MULTIPLY:
829 case BINARY_TRUE_DIVIDE:
830 case BINARY_FLOOR_DIVIDE:
831 case BINARY_MODULO:
832 case BINARY_ADD:
833 case BINARY_SUBTRACT:
834 case BINARY_SUBSCR:
835 case BINARY_LSHIFT:
836 case BINARY_RSHIFT:
837 case BINARY_AND:
838 case BINARY_XOR:
839 case BINARY_OR:
840 if (lastlc >= 2 &&
841 ISBASICBLOCK(blocks, i-6, 7) &&
842 fold_binops_on_constants(&codestr[i-6], consts)) {
843 i -= 2;
844 assert(codestr[i] == LOAD_CONST);
845 cumlc = 1;
846 }
847 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000848
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000849 /* Fold unary ops on constants.
850 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
851 case UNARY_NEGATIVE:
852 case UNARY_CONVERT:
853 case UNARY_INVERT:
854 if (lastlc >= 1 &&
855 ISBASICBLOCK(blocks, i-3, 4) &&
856 fold_unaryops_on_constants(&codestr[i-3], consts)) {
857 i -= 2;
858 assert(codestr[i] == LOAD_CONST);
859 cumlc = 1;
860 }
861 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000862
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000863 /* Simplify conditional jump to conditional jump where the
864 result of the first test implies the success of a similar
865 test or the failure of the opposite test.
866 Arises in code like:
867 "if a and b:"
868 "if a or b:"
869 "a and b or c"
870 "(a and b) and c"
871 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
872 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
873 where y+3 is the instruction following the second test.
874 */
875 case JUMP_IF_FALSE:
876 case JUMP_IF_TRUE:
877 tgt = GETJUMPTGT(codestr, i);
878 j = codestr[tgt];
879 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
880 if (j == opcode) {
881 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
882 SETARG(codestr, i, tgttgt);
883 } else {
884 tgt -= i;
885 SETARG(codestr, i, tgt);
886 }
887 break;
888 }
889 /* Intentional fallthrough */
890
891 /* Replace jumps to unconditional jumps */
892 case FOR_ITER:
893 case JUMP_FORWARD:
894 case JUMP_ABSOLUTE:
895 case CONTINUE_LOOP:
896 case SETUP_LOOP:
897 case SETUP_EXCEPT:
898 case SETUP_FINALLY:
899 tgt = GETJUMPTGT(codestr, i);
900 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
901 continue;
902 tgttgt = GETJUMPTGT(codestr, tgt);
903 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
904 opcode = JUMP_ABSOLUTE;
905 if (!ABSOLUTE_JUMP(opcode))
906 tgttgt -= i + 3; /* Calc relative jump addr */
907 if (tgttgt < 0) /* No backward relative jumps */
908 continue;
909 codestr[i] = opcode;
910 SETARG(codestr, i, tgttgt);
911 break;
912
913 case EXTENDED_ARG:
914 goto exitUnchanged;
915
916 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
917 case RETURN_VALUE:
918 if (i+4 >= codelen ||
919 codestr[i+4] != RETURN_VALUE ||
920 !ISBASICBLOCK(blocks,i,5))
921 continue;
922 memset(codestr+i+1, NOP, 4);
923 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000924 }
925 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000926
927 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000928 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
929 addrmap[i] = i - nops;
930 if (codestr[i] == NOP)
931 nops++;
932 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000933 cum_orig_line = 0;
934 last_line = 0;
935 for (i=0 ; i < tabsiz ; i+=2) {
936 cum_orig_line += lineno[i];
937 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000938 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000939 lineno[i] =((unsigned char)(new_line - last_line));
940 last_line = new_line;
941 }
942
943 /* Remove NOPs and fixup jump targets */
944 for (i=0, h=0 ; i<codelen ; ) {
945 opcode = codestr[i];
946 switch (opcode) {
947 case NOP:
948 i++;
949 continue;
950
951 case JUMP_ABSOLUTE:
952 case CONTINUE_LOOP:
953 j = addrmap[GETARG(codestr, i)];
954 SETARG(codestr, i, j);
955 break;
956
957 case FOR_ITER:
958 case JUMP_FORWARD:
959 case JUMP_IF_FALSE:
960 case JUMP_IF_TRUE:
961 case SETUP_LOOP:
962 case SETUP_EXCEPT:
963 case SETUP_FINALLY:
964 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
965 SETARG(codestr, i, j);
966 break;
967 }
968 adj = CODESIZE(opcode);
969 while (adj--)
970 codestr[h++] = codestr[i++];
971 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000972 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000973
974 code = PyString_FromStringAndSize((char *)codestr, h);
975 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000976 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000977 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000978 return code;
979
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000980 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +0000981 if (blocks != NULL)
982 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000983 if (addrmap != NULL)
984 PyMem_Free(addrmap);
985 if (codestr != NULL)
986 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000987 Py_INCREF(code);
988 return code;
989}
990
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000991/* End: Peephole optimizations ----------------------------------------- */
992
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993/*
994
995Leave this debugging code for just a little longer.
996
997static void
998compiler_display_symbols(PyObject *name, PyObject *symbols)
999{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001000PyObject *key, *value;
1001int flags;
1002Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001003
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001004fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1005while (PyDict_Next(symbols, &pos, &key, &value)) {
1006flags = PyInt_AsLong(value);
1007fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1008if (flags & DEF_GLOBAL)
1009fprintf(stderr, " declared_global");
1010if (flags & DEF_LOCAL)
1011fprintf(stderr, " local");
1012if (flags & DEF_PARAM)
1013fprintf(stderr, " param");
1014if (flags & DEF_STAR)
1015fprintf(stderr, " stararg");
1016if (flags & DEF_DOUBLESTAR)
1017fprintf(stderr, " starstar");
1018if (flags & DEF_INTUPLE)
1019fprintf(stderr, " tuple");
1020if (flags & DEF_FREE)
1021fprintf(stderr, " free");
1022if (flags & DEF_FREE_GLOBAL)
1023fprintf(stderr, " global");
1024if (flags & DEF_FREE_CLASS)
1025fprintf(stderr, " free/class");
1026if (flags & DEF_IMPORT)
1027fprintf(stderr, " import");
1028fprintf(stderr, "\n");
1029}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030 fprintf(stderr, "\n");
1031}
1032*/
1033
1034static void
1035compiler_unit_check(struct compiler_unit *u)
1036{
1037 basicblock *block;
1038 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1039 assert(block != (void *)0xcbcbcbcb);
1040 assert(block != (void *)0xfbfbfbfb);
1041 assert(block != (void *)0xdbdbdbdb);
1042 if (block->b_instr != NULL) {
1043 assert(block->b_ialloc > 0);
1044 assert(block->b_iused > 0);
1045 assert(block->b_ialloc >= block->b_iused);
1046 }
1047 else {
1048 assert (block->b_iused == 0);
1049 assert (block->b_ialloc == 0);
1050 }
1051 }
1052}
1053
1054static void
1055compiler_unit_free(struct compiler_unit *u)
1056{
1057 basicblock *b, *next;
1058
1059 compiler_unit_check(u);
1060 b = u->u_blocks;
1061 while (b != NULL) {
1062 if (b->b_instr)
1063 PyObject_Free((void *)b->b_instr);
1064 next = b->b_list;
1065 PyObject_Free((void *)b);
1066 b = next;
1067 }
1068 Py_XDECREF(u->u_ste);
1069 Py_XDECREF(u->u_name);
1070 Py_XDECREF(u->u_consts);
1071 Py_XDECREF(u->u_names);
1072 Py_XDECREF(u->u_varnames);
1073 Py_XDECREF(u->u_freevars);
1074 Py_XDECREF(u->u_cellvars);
1075 Py_XDECREF(u->u_private);
1076 PyObject_Free(u);
1077}
1078
1079static int
1080compiler_enter_scope(struct compiler *c, identifier name, void *key,
1081 int lineno)
1082{
1083 struct compiler_unit *u;
1084
1085 u = PyObject_Malloc(sizeof(struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001086 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001087 PyErr_NoMemory();
1088 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001089 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001090 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001091 u->u_argcount = 0;
1092 u->u_ste = PySymtable_Lookup(c->c_st, key);
1093 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001094 compiler_unit_free(u);
1095 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001096 }
1097 Py_INCREF(name);
1098 u->u_name = name;
1099 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1100 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
1101 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001102 PyDict_Size(u->u_cellvars));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
1104 u->u_blocks = NULL;
1105 u->u_tmpname = 0;
1106 u->u_nfblocks = 0;
1107 u->u_firstlineno = lineno;
1108 u->u_lineno = 0;
1109 u->u_lineno_set = false;
1110 u->u_consts = PyDict_New();
1111 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001112 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113 return 0;
1114 }
1115 u->u_names = PyDict_New();
1116 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001117 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001118 return 0;
1119 }
1120
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001121 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001122
1123 /* Push the old compiler_unit on the stack. */
1124 if (c->u) {
1125 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
1126 if (PyList_Append(c->c_stack, wrapper) < 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001127 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001128 return 0;
1129 }
1130 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001131 u->u_private = c->u->u_private;
1132 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001133 }
1134 c->u = u;
1135
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001136 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001137 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001138 return 0;
1139
1140 return 1;
1141}
1142
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001143static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001144compiler_exit_scope(struct compiler *c)
1145{
1146 int n;
1147 PyObject *wrapper;
1148
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001149 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001150 compiler_unit_free(c->u);
1151 /* Restore c->u to the parent unit. */
1152 n = PyList_GET_SIZE(c->c_stack) - 1;
1153 if (n >= 0) {
1154 wrapper = PyList_GET_ITEM(c->c_stack, n);
1155 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001156 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001158 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159 compiler_unit_check(c->u);
1160 }
1161 else
1162 c->u = NULL;
1163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Guido van Rossumc2e20742006-02-27 22:32:47 +00001166/* Allocate a new "anonymous" local variable.
1167 Used by list comprehensions and with statements.
1168*/
1169
1170static PyObject *
1171compiler_new_tmpname(struct compiler *c)
1172{
1173 char tmpname[256];
1174 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1175 return PyString_FromString(tmpname);
1176}
1177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178/* Allocate a new block and return a pointer to it.
1179 Returns NULL on error.
1180*/
1181
1182static basicblock *
1183compiler_new_block(struct compiler *c)
1184{
1185 basicblock *b;
1186 struct compiler_unit *u;
1187
1188 u = c->u;
1189 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001190 if (b == NULL) {
1191 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001192 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001193 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001194 memset((void *)b, 0, sizeof(basicblock));
1195 assert (b->b_next == NULL);
1196 b->b_list = u->u_blocks;
1197 u->u_blocks = b;
1198 return b;
1199}
1200
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201static basicblock *
1202compiler_use_new_block(struct compiler *c)
1203{
1204 basicblock *block = compiler_new_block(c);
1205 if (block == NULL)
1206 return NULL;
1207 c->u->u_curblock = block;
1208 return block;
1209}
1210
1211static basicblock *
1212compiler_next_block(struct compiler *c)
1213{
1214 basicblock *block = compiler_new_block(c);
1215 if (block == NULL)
1216 return NULL;
1217 c->u->u_curblock->b_next = block;
1218 c->u->u_curblock = block;
1219 return block;
1220}
1221
1222static basicblock *
1223compiler_use_next_block(struct compiler *c, basicblock *block)
1224{
1225 assert(block != NULL);
1226 c->u->u_curblock->b_next = block;
1227 c->u->u_curblock = block;
1228 return block;
1229}
1230
1231/* Returns the offset of the next instruction in the current block's
1232 b_instr array. Resizes the b_instr as necessary.
1233 Returns -1 on failure.
1234 */
1235
1236static int
1237compiler_next_instr(struct compiler *c, basicblock *b)
1238{
1239 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001240 if (b->b_instr == NULL) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001241 b->b_instr = PyObject_Malloc(sizeof(struct instr) *
1242 DEFAULT_BLOCK_SIZE);
1243 if (b->b_instr == NULL) {
1244 PyErr_NoMemory();
1245 return -1;
1246 }
1247 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1248 memset((char *)b->b_instr, 0,
1249 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001250 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001251 else if (b->b_iused == b->b_ialloc) {
1252 size_t oldsize, newsize;
1253 oldsize = b->b_ialloc * sizeof(struct instr);
1254 newsize = oldsize << 1;
1255 if (newsize == 0) {
1256 PyErr_NoMemory();
1257 return -1;
1258 }
1259 b->b_ialloc <<= 1;
1260 b->b_instr = PyObject_Realloc((void *)b->b_instr, newsize);
1261 if (b->b_instr == NULL)
1262 return -1;
1263 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1264 }
1265 return b->b_iused++;
1266}
1267
1268static void
1269compiler_set_lineno(struct compiler *c, int off)
1270{
1271 basicblock *b;
1272 if (c->u->u_lineno_set)
1273 return;
1274 c->u->u_lineno_set = true;
1275 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001276 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277}
1278
1279static int
1280opcode_stack_effect(int opcode, int oparg)
1281{
1282 switch (opcode) {
1283 case POP_TOP:
1284 return -1;
1285 case ROT_TWO:
1286 case ROT_THREE:
1287 return 0;
1288 case DUP_TOP:
1289 return 1;
1290 case ROT_FOUR:
1291 return 0;
1292
1293 case UNARY_POSITIVE:
1294 case UNARY_NEGATIVE:
1295 case UNARY_NOT:
1296 case UNARY_CONVERT:
1297 case UNARY_INVERT:
1298 return 0;
1299
1300 case BINARY_POWER:
1301 case BINARY_MULTIPLY:
1302 case BINARY_DIVIDE:
1303 case BINARY_MODULO:
1304 case BINARY_ADD:
1305 case BINARY_SUBTRACT:
1306 case BINARY_SUBSCR:
1307 case BINARY_FLOOR_DIVIDE:
1308 case BINARY_TRUE_DIVIDE:
1309 return -1;
1310 case INPLACE_FLOOR_DIVIDE:
1311 case INPLACE_TRUE_DIVIDE:
1312 return -1;
1313
1314 case SLICE+0:
1315 return 1;
1316 case SLICE+1:
1317 return 0;
1318 case SLICE+2:
1319 return 0;
1320 case SLICE+3:
1321 return -1;
1322
1323 case STORE_SLICE+0:
1324 return -2;
1325 case STORE_SLICE+1:
1326 return -3;
1327 case STORE_SLICE+2:
1328 return -3;
1329 case STORE_SLICE+3:
1330 return -4;
1331
1332 case DELETE_SLICE+0:
1333 return -1;
1334 case DELETE_SLICE+1:
1335 return -2;
1336 case DELETE_SLICE+2:
1337 return -2;
1338 case DELETE_SLICE+3:
1339 return -3;
1340
1341 case INPLACE_ADD:
1342 case INPLACE_SUBTRACT:
1343 case INPLACE_MULTIPLY:
1344 case INPLACE_DIVIDE:
1345 case INPLACE_MODULO:
1346 return -1;
1347 case STORE_SUBSCR:
1348 return -3;
1349 case DELETE_SUBSCR:
1350 return -2;
1351
1352 case BINARY_LSHIFT:
1353 case BINARY_RSHIFT:
1354 case BINARY_AND:
1355 case BINARY_XOR:
1356 case BINARY_OR:
1357 return -1;
1358 case INPLACE_POWER:
1359 return -1;
1360 case GET_ITER:
1361 return 0;
1362
1363 case PRINT_EXPR:
1364 return -1;
1365 case PRINT_ITEM:
1366 return -1;
1367 case PRINT_NEWLINE:
1368 return 0;
1369 case PRINT_ITEM_TO:
1370 return -2;
1371 case PRINT_NEWLINE_TO:
1372 return -1;
1373 case INPLACE_LSHIFT:
1374 case INPLACE_RSHIFT:
1375 case INPLACE_AND:
1376 case INPLACE_XOR:
1377 case INPLACE_OR:
1378 return -1;
1379 case BREAK_LOOP:
1380 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001381 case WITH_CLEANUP:
1382 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 case LOAD_LOCALS:
1384 return 1;
1385 case RETURN_VALUE:
1386 return -1;
1387 case IMPORT_STAR:
1388 return -1;
1389 case EXEC_STMT:
1390 return -3;
1391 case YIELD_VALUE:
1392 return 0;
1393
1394 case POP_BLOCK:
1395 return 0;
1396 case END_FINALLY:
1397 return -1; /* or -2 or -3 if exception occurred */
1398 case BUILD_CLASS:
1399 return -2;
1400
1401 case STORE_NAME:
1402 return -1;
1403 case DELETE_NAME:
1404 return 0;
1405 case UNPACK_SEQUENCE:
1406 return oparg-1;
1407 case FOR_ITER:
1408 return 1;
1409
1410 case STORE_ATTR:
1411 return -2;
1412 case DELETE_ATTR:
1413 return -1;
1414 case STORE_GLOBAL:
1415 return -1;
1416 case DELETE_GLOBAL:
1417 return 0;
1418 case DUP_TOPX:
1419 return oparg;
1420 case LOAD_CONST:
1421 return 1;
1422 case LOAD_NAME:
1423 return 1;
1424 case BUILD_TUPLE:
1425 case BUILD_LIST:
1426 return 1-oparg;
1427 case BUILD_MAP:
1428 return 1;
1429 case LOAD_ATTR:
1430 return 0;
1431 case COMPARE_OP:
1432 return -1;
1433 case IMPORT_NAME:
1434 return 0;
1435 case IMPORT_FROM:
1436 return 1;
1437
1438 case JUMP_FORWARD:
1439 case JUMP_IF_FALSE:
1440 case JUMP_IF_TRUE:
1441 case JUMP_ABSOLUTE:
1442 return 0;
1443
1444 case LOAD_GLOBAL:
1445 return 1;
1446
1447 case CONTINUE_LOOP:
1448 return 0;
1449 case SETUP_LOOP:
1450 return 0;
1451 case SETUP_EXCEPT:
1452 case SETUP_FINALLY:
1453 return 3; /* actually pushed by an exception */
1454
1455 case LOAD_FAST:
1456 return 1;
1457 case STORE_FAST:
1458 return -1;
1459 case DELETE_FAST:
1460 return 0;
1461
1462 case RAISE_VARARGS:
1463 return -oparg;
1464#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1465 case CALL_FUNCTION:
1466 return -NARGS(oparg);
1467 case CALL_FUNCTION_VAR:
1468 case CALL_FUNCTION_KW:
1469 return -NARGS(oparg)-1;
1470 case CALL_FUNCTION_VAR_KW:
1471 return -NARGS(oparg)-2;
1472#undef NARGS
1473 case MAKE_FUNCTION:
1474 return -oparg;
1475 case BUILD_SLICE:
1476 if (oparg == 3)
1477 return -2;
1478 else
1479 return -1;
1480
1481 case MAKE_CLOSURE:
1482 return -oparg;
1483 case LOAD_CLOSURE:
1484 return 1;
1485 case LOAD_DEREF:
1486 return 1;
1487 case STORE_DEREF:
1488 return -1;
1489 default:
1490 fprintf(stderr, "opcode = %d\n", opcode);
1491 Py_FatalError("opcode_stack_effect()");
1492
1493 }
1494 return 0; /* not reachable */
1495}
1496
1497/* Add an opcode with no argument.
1498 Returns 0 on failure, 1 on success.
1499*/
1500
1501static int
1502compiler_addop(struct compiler *c, int opcode)
1503{
1504 basicblock *b;
1505 struct instr *i;
1506 int off;
1507 off = compiler_next_instr(c, c->u->u_curblock);
1508 if (off < 0)
1509 return 0;
1510 b = c->u->u_curblock;
1511 i = &b->b_instr[off];
1512 i->i_opcode = opcode;
1513 i->i_hasarg = 0;
1514 if (opcode == RETURN_VALUE)
1515 b->b_return = 1;
1516 compiler_set_lineno(c, off);
1517 return 1;
1518}
1519
1520static int
1521compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1522{
1523 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001524 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001526 /* necessary to make sure types aren't coerced (e.g., int and long) */
1527 t = PyTuple_Pack(2, o, o->ob_type);
1528 if (t == NULL)
1529 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530
1531 v = PyDict_GetItem(dict, t);
1532 if (!v) {
1533 arg = PyDict_Size(dict);
1534 v = PyInt_FromLong(arg);
1535 if (!v) {
1536 Py_DECREF(t);
1537 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539 if (PyDict_SetItem(dict, t, v) < 0) {
1540 Py_DECREF(t);
1541 Py_DECREF(v);
1542 return -1;
1543 }
1544 Py_DECREF(v);
1545 }
1546 else
1547 arg = PyInt_AsLong(v);
1548 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001549 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001550}
1551
1552static int
1553compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1554 PyObject *o)
1555{
1556 int arg = compiler_add_o(c, dict, o);
1557 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001558 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559 return compiler_addop_i(c, opcode, arg);
1560}
1561
1562static int
1563compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001564 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565{
1566 int arg;
1567 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1568 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001569 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570 arg = compiler_add_o(c, dict, mangled);
1571 Py_DECREF(mangled);
1572 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001573 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001574 return compiler_addop_i(c, opcode, arg);
1575}
1576
1577/* Add an opcode with an integer argument.
1578 Returns 0 on failure, 1 on success.
1579*/
1580
1581static int
1582compiler_addop_i(struct compiler *c, int opcode, int oparg)
1583{
1584 struct instr *i;
1585 int off;
1586 off = compiler_next_instr(c, c->u->u_curblock);
1587 if (off < 0)
1588 return 0;
1589 i = &c->u->u_curblock->b_instr[off];
1590 i->i_opcode = opcode;
1591 i->i_oparg = oparg;
1592 i->i_hasarg = 1;
1593 compiler_set_lineno(c, off);
1594 return 1;
1595}
1596
1597static int
1598compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1599{
1600 struct instr *i;
1601 int off;
1602
1603 assert(b != NULL);
1604 off = compiler_next_instr(c, c->u->u_curblock);
1605 if (off < 0)
1606 return 0;
1607 compiler_set_lineno(c, off);
1608 i = &c->u->u_curblock->b_instr[off];
1609 i->i_opcode = opcode;
1610 i->i_target = b;
1611 i->i_hasarg = 1;
1612 if (absolute)
1613 i->i_jabs = 1;
1614 else
1615 i->i_jrel = 1;
1616 return 1;
1617}
1618
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001619/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1620 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621 it as the current block. NEXT_BLOCK() also creates an implicit jump
1622 from the current block to the new block.
1623*/
1624
1625/* XXX The returns inside these macros make it impossible to decref
1626 objects created in the local function.
1627*/
1628
1629
1630#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001631 if (compiler_use_new_block((C)) == NULL) \
1632 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633}
1634
1635#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001636 if (compiler_next_block((C)) == NULL) \
1637 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638}
1639
1640#define ADDOP(C, OP) { \
1641 if (!compiler_addop((C), (OP))) \
1642 return 0; \
1643}
1644
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001645#define ADDOP_IN_SCOPE(C, OP) { \
1646 if (!compiler_addop((C), (OP))) { \
1647 compiler_exit_scope(c); \
1648 return 0; \
1649 } \
1650}
1651
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652#define ADDOP_O(C, OP, O, TYPE) { \
1653 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1654 return 0; \
1655}
1656
1657#define ADDOP_NAME(C, OP, O, TYPE) { \
1658 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1659 return 0; \
1660}
1661
1662#define ADDOP_I(C, OP, O) { \
1663 if (!compiler_addop_i((C), (OP), (O))) \
1664 return 0; \
1665}
1666
1667#define ADDOP_JABS(C, OP, O) { \
1668 if (!compiler_addop_j((C), (OP), (O), 1)) \
1669 return 0; \
1670}
1671
1672#define ADDOP_JREL(C, OP, O) { \
1673 if (!compiler_addop_j((C), (OP), (O), 0)) \
1674 return 0; \
1675}
1676
1677/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1678 the ASDL name to synthesize the name of the C type and the visit function.
1679*/
1680
1681#define VISIT(C, TYPE, V) {\
1682 if (!compiler_visit_ ## TYPE((C), (V))) \
1683 return 0; \
1684}
1685
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001686#define VISIT_IN_SCOPE(C, TYPE, V) {\
1687 if (!compiler_visit_ ## TYPE((C), (V))) { \
1688 compiler_exit_scope(c); \
1689 return 0; \
1690 } \
1691}
1692
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693#define VISIT_SLICE(C, V, CTX) {\
1694 if (!compiler_visit_slice((C), (V), (CTX))) \
1695 return 0; \
1696}
1697
1698#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001699 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001701 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1702 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703 if (!compiler_visit_ ## TYPE((C), elt)) \
1704 return 0; \
1705 } \
1706}
1707
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001708#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001709 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001710 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001711 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1712 TYPE ## _ty elt = asdl_seq_GET(seq, _i); \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001713 if (!compiler_visit_ ## TYPE((C), elt)) { \
1714 compiler_exit_scope(c); \
1715 return 0; \
1716 } \
1717 } \
1718}
1719
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720static int
1721compiler_isdocstring(stmt_ty s)
1722{
1723 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001724 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725 return s->v.Expr.value->kind == Str_kind;
1726}
1727
1728/* Compile a sequence of statements, checking for a docstring. */
1729
1730static int
1731compiler_body(struct compiler *c, asdl_seq *stmts)
1732{
1733 int i = 0;
1734 stmt_ty st;
1735
1736 if (!asdl_seq_LEN(stmts))
1737 return 1;
1738 st = asdl_seq_GET(stmts, 0);
1739 if (compiler_isdocstring(st)) {
1740 i = 1;
1741 VISIT(c, expr, st->v.Expr.value);
1742 if (!compiler_nameop(c, __doc__, Store))
1743 return 0;
1744 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001745 for (; i < asdl_seq_LEN(stmts); i++)
1746 VISIT(c, stmt, asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747 return 1;
1748}
1749
1750static PyCodeObject *
1751compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001752{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001753 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001754 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001755 static PyObject *module;
1756 if (!module) {
1757 module = PyString_FromString("<module>");
1758 if (!module)
1759 return NULL;
1760 }
1761 if (!compiler_enter_scope(c, module, mod, 1))
Guido van Rossumd076c731998-10-07 19:42:25 +00001762 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001763 switch (mod->kind) {
1764 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001765 if (!compiler_body(c, mod->v.Module.body)) {
1766 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001767 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001768 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769 break;
1770 case Interactive_kind:
1771 c->c_interactive = 1;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001772 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 break;
1774 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001775 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001776 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777 break;
1778 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001779 PyErr_SetString(PyExc_SystemError,
1780 "suite should not be possible");
1781 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001782 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001783 PyErr_Format(PyExc_SystemError,
1784 "module kind %d should not be possible",
1785 mod->kind);
1786 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001787 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788 co = assemble(c, addNone);
1789 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001790 return co;
1791}
1792
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793/* The test for LOCAL must come before the test for FREE in order to
1794 handle classes where name is both local and free. The local var is
1795 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001796*/
1797
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798static int
1799get_ref_type(struct compiler *c, PyObject *name)
1800{
1801 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001802 if (scope == 0) {
1803 char buf[350];
1804 PyOS_snprintf(buf, sizeof(buf),
1805 "unknown scope for %.100s in %.100s(%s) in %s\n"
1806 "symbols: %s\nlocals: %s\nglobals: %s\n",
1807 PyString_AS_STRING(name),
1808 PyString_AS_STRING(c->u->u_name),
1809 PyObject_REPR(c->u->u_ste->ste_id),
1810 c->c_filename,
1811 PyObject_REPR(c->u->u_ste->ste_symbols),
1812 PyObject_REPR(c->u->u_varnames),
1813 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001815 Py_FatalError(buf);
1816 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001817
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001818 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819}
1820
1821static int
1822compiler_lookup_arg(PyObject *dict, PyObject *name)
1823{
1824 PyObject *k, *v;
1825 k = Py_BuildValue("(OO)", name, name->ob_type);
1826 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001827 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001829 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001831 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001832 return PyInt_AS_LONG(v);
1833}
1834
1835static int
1836compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1837{
1838 int i, free = PyCode_GetNumFree(co);
1839 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001840 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1841 ADDOP_I(c, MAKE_FUNCTION, args);
1842 return 1;
1843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 for (i = 0; i < free; ++i) {
1845 /* Bypass com_addop_varname because it will generate
1846 LOAD_DEREF but LOAD_CLOSURE is needed.
1847 */
1848 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1849 int arg, reftype;
1850
1851 /* Special case: If a class contains a method with a
1852 free variable that has the same name as a method,
1853 the name will be considered free *and* local in the
1854 class. It should be handled by the closure, as
1855 well as by the normal name loookup logic.
1856 */
1857 reftype = get_ref_type(c, name);
1858 if (reftype == CELL)
1859 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1860 else /* (reftype == FREE) */
1861 arg = compiler_lookup_arg(c->u->u_freevars, name);
1862 if (arg == -1) {
1863 printf("lookup %s in %s %d %d\n"
1864 "freevars of %s: %s\n",
1865 PyObject_REPR(name),
1866 PyString_AS_STRING(c->u->u_name),
1867 reftype, arg,
1868 PyString_AS_STRING(co->co_name),
1869 PyObject_REPR(co->co_freevars));
1870 Py_FatalError("compiler_make_closure()");
1871 }
1872 ADDOP_I(c, LOAD_CLOSURE, arg);
1873 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001874 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001875 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001876 ADDOP_I(c, MAKE_CLOSURE, args);
1877 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878}
1879
1880static int
1881compiler_decorators(struct compiler *c, asdl_seq* decos)
1882{
1883 int i;
1884
1885 if (!decos)
1886 return 1;
1887
1888 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1889 VISIT(c, expr, asdl_seq_GET(decos, i));
1890 }
1891 return 1;
1892}
1893
1894static int
1895compiler_arguments(struct compiler *c, arguments_ty args)
1896{
1897 int i;
1898 int n = asdl_seq_LEN(args->args);
1899 /* Correctly handle nested argument lists */
1900 for (i = 0; i < n; i++) {
1901 expr_ty arg = asdl_seq_GET(args->args, i);
1902 if (arg->kind == Tuple_kind) {
1903 PyObject *id = PyString_FromFormat(".%d", i);
1904 if (id == NULL) {
1905 return 0;
1906 }
1907 if (!compiler_nameop(c, id, Load)) {
1908 Py_DECREF(id);
1909 return 0;
1910 }
1911 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001912 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913 }
1914 }
1915 return 1;
1916}
1917
1918static int
1919compiler_function(struct compiler *c, stmt_ty s)
1920{
1921 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001922 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923 arguments_ty args = s->v.FunctionDef.args;
1924 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001925 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926 int i, n, docstring;
1927
1928 assert(s->kind == FunctionDef_kind);
1929
1930 if (!compiler_decorators(c, decos))
1931 return 0;
1932 if (args->defaults)
1933 VISIT_SEQ(c, expr, args->defaults);
1934 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
1935 s->lineno))
1936 return 0;
1937
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001938 st = asdl_seq_GET(s->v.FunctionDef.body, 0);
1939 docstring = compiler_isdocstring(st);
1940 if (docstring)
1941 first_const = st->v.Expr.value->v.Str.s;
1942 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001943 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001944 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001945 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001946
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001947 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948 compiler_arguments(c, args);
1949
1950 c->u->u_argcount = asdl_seq_LEN(args->args);
1951 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001952 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001953 for (i = docstring; i < n; i++) {
1954 stmt_ty s2 = asdl_seq_GET(s->v.FunctionDef.body, i);
1955 if (i == 0 && s2->kind == Expr_kind &&
1956 s2->v.Expr.value->kind == Str_kind)
1957 continue;
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001958 VISIT_IN_SCOPE(c, stmt, s2);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001959 }
1960 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001961 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962 if (co == NULL)
1963 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001965 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00001966 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967
1968 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1969 ADDOP_I(c, CALL_FUNCTION, 1);
1970 }
1971
1972 return compiler_nameop(c, s->v.FunctionDef.name, Store);
1973}
1974
1975static int
1976compiler_class(struct compiler *c, stmt_ty s)
1977{
1978 int n;
1979 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001980 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 /* push class name on stack, needed by BUILD_CLASS */
1982 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
1983 /* push the tuple of base classes on the stack */
1984 n = asdl_seq_LEN(s->v.ClassDef.bases);
1985 if (n > 0)
1986 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
1987 ADDOP_I(c, BUILD_TUPLE, n);
1988 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
1989 s->lineno))
1990 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001991 c->u->u_private = s->v.ClassDef.name;
1992 Py_INCREF(c->u->u_private);
1993 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001994 if (!str || !compiler_nameop(c, str, Load)) {
1995 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001996 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001997 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001998 }
1999
2000 Py_DECREF(str);
2001 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 if (!str || !compiler_nameop(c, str, Store)) {
2003 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002004 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002005 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002006 }
2007 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002008
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002009 if (!compiler_body(c, s->v.ClassDef.body)) {
2010 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002011 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002012 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002013
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002014 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2015 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002016 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002017 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002018 if (co == NULL)
2019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002021 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002022 Py_DECREF(co);
2023
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 ADDOP_I(c, CALL_FUNCTION, 0);
2025 ADDOP(c, BUILD_CLASS);
2026 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2027 return 0;
2028 return 1;
2029}
2030
2031static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002032compiler_ifexp(struct compiler *c, expr_ty e)
2033{
2034 basicblock *end, *next;
2035
2036 assert(e->kind == IfExp_kind);
2037 end = compiler_new_block(c);
2038 if (end == NULL)
2039 return 0;
2040 next = compiler_new_block(c);
2041 if (next == NULL)
2042 return 0;
2043 VISIT(c, expr, e->v.IfExp.test);
2044 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2045 ADDOP(c, POP_TOP);
2046 VISIT(c, expr, e->v.IfExp.body);
2047 ADDOP_JREL(c, JUMP_FORWARD, end);
2048 compiler_use_next_block(c, next);
2049 ADDOP(c, POP_TOP);
2050 VISIT(c, expr, e->v.IfExp.orelse);
2051 compiler_use_next_block(c, end);
2052 return 1;
2053}
2054
2055static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056compiler_lambda(struct compiler *c, expr_ty e)
2057{
2058 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002059 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 arguments_ty args = e->v.Lambda.args;
2061 assert(e->kind == Lambda_kind);
2062
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002063 if (!name) {
2064 name = PyString_InternFromString("<lambda>");
2065 if (!name)
2066 return 0;
2067 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068
2069 if (args->defaults)
2070 VISIT_SEQ(c, expr, args->defaults);
2071 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2072 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002073
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002074 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075 compiler_arguments(c, args);
2076
2077 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002078 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2079 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002081 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082 if (co == NULL)
2083 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002084
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002085 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002086 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087
2088 return 1;
2089}
2090
2091static int
2092compiler_print(struct compiler *c, stmt_ty s)
2093{
2094 int i, n;
2095 bool dest;
2096
2097 assert(s->kind == Print_kind);
2098 n = asdl_seq_LEN(s->v.Print.values);
2099 dest = false;
2100 if (s->v.Print.dest) {
2101 VISIT(c, expr, s->v.Print.dest);
2102 dest = true;
2103 }
2104 for (i = 0; i < n; i++) {
2105 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2106 if (dest) {
2107 ADDOP(c, DUP_TOP);
2108 VISIT(c, expr, e);
2109 ADDOP(c, ROT_TWO);
2110 ADDOP(c, PRINT_ITEM_TO);
2111 }
2112 else {
2113 VISIT(c, expr, e);
2114 ADDOP(c, PRINT_ITEM);
2115 }
2116 }
2117 if (s->v.Print.nl) {
2118 if (dest)
2119 ADDOP(c, PRINT_NEWLINE_TO)
2120 else
2121 ADDOP(c, PRINT_NEWLINE)
2122 }
2123 else if (dest)
2124 ADDOP(c, POP_TOP);
2125 return 1;
2126}
2127
2128static int
2129compiler_if(struct compiler *c, stmt_ty s)
2130{
2131 basicblock *end, *next;
2132
2133 assert(s->kind == If_kind);
2134 end = compiler_new_block(c);
2135 if (end == NULL)
2136 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002137 next = compiler_new_block(c);
2138 if (next == NULL)
2139 return 0;
2140 VISIT(c, expr, s->v.If.test);
2141 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2142 ADDOP(c, POP_TOP);
2143 VISIT_SEQ(c, stmt, s->v.If.body);
2144 ADDOP_JREL(c, JUMP_FORWARD, end);
2145 compiler_use_next_block(c, next);
2146 ADDOP(c, POP_TOP);
2147 if (s->v.If.orelse)
2148 VISIT_SEQ(c, stmt, s->v.If.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 compiler_use_next_block(c, end);
2150 return 1;
2151}
2152
2153static int
2154compiler_for(struct compiler *c, stmt_ty s)
2155{
2156 basicblock *start, *cleanup, *end;
2157
2158 start = compiler_new_block(c);
2159 cleanup = compiler_new_block(c);
2160 end = compiler_new_block(c);
2161 if (start == NULL || end == NULL || cleanup == NULL)
2162 return 0;
2163 ADDOP_JREL(c, SETUP_LOOP, end);
2164 if (!compiler_push_fblock(c, LOOP, start))
2165 return 0;
2166 VISIT(c, expr, s->v.For.iter);
2167 ADDOP(c, GET_ITER);
2168 compiler_use_next_block(c, start);
2169 ADDOP_JREL(c, FOR_ITER, cleanup);
2170 VISIT(c, expr, s->v.For.target);
2171 VISIT_SEQ(c, stmt, s->v.For.body);
2172 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2173 compiler_use_next_block(c, cleanup);
2174 ADDOP(c, POP_BLOCK);
2175 compiler_pop_fblock(c, LOOP, start);
2176 VISIT_SEQ(c, stmt, s->v.For.orelse);
2177 compiler_use_next_block(c, end);
2178 return 1;
2179}
2180
2181static int
2182compiler_while(struct compiler *c, stmt_ty s)
2183{
2184 basicblock *loop, *orelse, *end, *anchor = NULL;
2185 int constant = expr_constant(s->v.While.test);
2186
2187 if (constant == 0)
2188 return 1;
2189 loop = compiler_new_block(c);
2190 end = compiler_new_block(c);
2191 if (constant == -1) {
2192 anchor = compiler_new_block(c);
2193 if (anchor == NULL)
2194 return 0;
2195 }
2196 if (loop == NULL || end == NULL)
2197 return 0;
2198 if (s->v.While.orelse) {
2199 orelse = compiler_new_block(c);
2200 if (orelse == NULL)
2201 return 0;
2202 }
2203 else
2204 orelse = NULL;
2205
2206 ADDOP_JREL(c, SETUP_LOOP, end);
2207 compiler_use_next_block(c, loop);
2208 if (!compiler_push_fblock(c, LOOP, loop))
2209 return 0;
2210 if (constant == -1) {
2211 VISIT(c, expr, s->v.While.test);
2212 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2213 ADDOP(c, POP_TOP);
2214 }
2215 VISIT_SEQ(c, stmt, s->v.While.body);
2216 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2217
2218 /* XXX should the two POP instructions be in a separate block
2219 if there is no else clause ?
2220 */
2221
2222 if (constant == -1) {
2223 compiler_use_next_block(c, anchor);
2224 ADDOP(c, POP_TOP);
2225 ADDOP(c, POP_BLOCK);
2226 }
2227 compiler_pop_fblock(c, LOOP, loop);
2228 if (orelse != NULL)
2229 VISIT_SEQ(c, stmt, s->v.While.orelse);
2230 compiler_use_next_block(c, end);
2231
2232 return 1;
2233}
2234
2235static int
2236compiler_continue(struct compiler *c)
2237{
2238 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
2239 int i;
2240
2241 if (!c->u->u_nfblocks)
2242 return compiler_error(c, LOOP_ERROR_MSG);
2243 i = c->u->u_nfblocks - 1;
2244 switch (c->u->u_fblock[i].fb_type) {
2245 case LOOP:
2246 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2247 break;
2248 case EXCEPT:
2249 case FINALLY_TRY:
2250 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP)
2251 ;
2252 if (i == -1)
2253 return compiler_error(c, LOOP_ERROR_MSG);
2254 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2255 break;
2256 case FINALLY_END:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002257 return compiler_error(c,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 "'continue' not supported inside 'finally' clause");
2259 }
2260
2261 return 1;
2262}
2263
2264/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2265
2266 SETUP_FINALLY L
2267 <code for body>
2268 POP_BLOCK
2269 LOAD_CONST <None>
2270 L: <code for finalbody>
2271 END_FINALLY
2272
2273 The special instructions use the block stack. Each block
2274 stack entry contains the instruction that created it (here
2275 SETUP_FINALLY), the level of the value stack at the time the
2276 block stack entry was created, and a label (here L).
2277
2278 SETUP_FINALLY:
2279 Pushes the current value stack level and the label
2280 onto the block stack.
2281 POP_BLOCK:
2282 Pops en entry from the block stack, and pops the value
2283 stack until its level is the same as indicated on the
2284 block stack. (The label is ignored.)
2285 END_FINALLY:
2286 Pops a variable number of entries from the *value* stack
2287 and re-raises the exception they specify. The number of
2288 entries popped depends on the (pseudo) exception type.
2289
2290 The block stack is unwound when an exception is raised:
2291 when a SETUP_FINALLY entry is found, the exception is pushed
2292 onto the value stack (and the exception condition is cleared),
2293 and the interpreter jumps to the label gotten from the block
2294 stack.
2295*/
2296
2297static int
2298compiler_try_finally(struct compiler *c, stmt_ty s)
2299{
2300 basicblock *body, *end;
2301 body = compiler_new_block(c);
2302 end = compiler_new_block(c);
2303 if (body == NULL || end == NULL)
2304 return 0;
2305
2306 ADDOP_JREL(c, SETUP_FINALLY, end);
2307 compiler_use_next_block(c, body);
2308 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2309 return 0;
2310 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
2311 ADDOP(c, POP_BLOCK);
2312 compiler_pop_fblock(c, FINALLY_TRY, body);
2313
2314 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2315 compiler_use_next_block(c, end);
2316 if (!compiler_push_fblock(c, FINALLY_END, end))
2317 return 0;
2318 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
2319 ADDOP(c, END_FINALLY);
2320 compiler_pop_fblock(c, FINALLY_END, end);
2321
2322 return 1;
2323}
2324
2325/*
2326 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2327 (The contents of the value stack is shown in [], with the top
2328 at the right; 'tb' is trace-back info, 'val' the exception's
2329 associated value, and 'exc' the exception.)
2330
2331 Value stack Label Instruction Argument
2332 [] SETUP_EXCEPT L1
2333 [] <code for S>
2334 [] POP_BLOCK
2335 [] JUMP_FORWARD L0
2336
2337 [tb, val, exc] L1: DUP )
2338 [tb, val, exc, exc] <evaluate E1> )
2339 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2340 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2341 [tb, val, exc, 1] POP )
2342 [tb, val, exc] POP
2343 [tb, val] <assign to V1> (or POP if no V1)
2344 [tb] POP
2345 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002346 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002347
2348 [tb, val, exc, 0] L2: POP
2349 [tb, val, exc] DUP
2350 .............................etc.......................
2351
2352 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002353 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354
2355 [] L0: <next statement>
2356
2357 Of course, parts are not generated if Vi or Ei is not present.
2358*/
2359static int
2360compiler_try_except(struct compiler *c, stmt_ty s)
2361{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002362 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363 int i, n;
2364
2365 body = compiler_new_block(c);
2366 except = compiler_new_block(c);
2367 orelse = compiler_new_block(c);
2368 end = compiler_new_block(c);
2369 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2370 return 0;
2371 ADDOP_JREL(c, SETUP_EXCEPT, except);
2372 compiler_use_next_block(c, body);
2373 if (!compiler_push_fblock(c, EXCEPT, body))
2374 return 0;
2375 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
2376 ADDOP(c, POP_BLOCK);
2377 compiler_pop_fblock(c, EXCEPT, body);
2378 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2379 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2380 compiler_use_next_block(c, except);
2381 for (i = 0; i < n; i++) {
2382 excepthandler_ty handler = asdl_seq_GET(
2383 s->v.TryExcept.handlers, i);
2384 if (!handler->type && i < n-1)
2385 return compiler_error(c, "default 'except:' must be last");
2386 except = compiler_new_block(c);
2387 if (except == NULL)
2388 return 0;
2389 if (handler->type) {
2390 ADDOP(c, DUP_TOP);
2391 VISIT(c, expr, handler->type);
2392 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2393 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2394 ADDOP(c, POP_TOP);
2395 }
2396 ADDOP(c, POP_TOP);
2397 if (handler->name) {
2398 VISIT(c, expr, handler->name);
2399 }
2400 else {
2401 ADDOP(c, POP_TOP);
2402 }
2403 ADDOP(c, POP_TOP);
2404 VISIT_SEQ(c, stmt, handler->body);
2405 ADDOP_JREL(c, JUMP_FORWARD, end);
2406 compiler_use_next_block(c, except);
2407 if (handler->type)
2408 ADDOP(c, POP_TOP);
2409 }
2410 ADDOP(c, END_FINALLY);
2411 compiler_use_next_block(c, orelse);
2412 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
2413 compiler_use_next_block(c, end);
2414 return 1;
2415}
2416
2417static int
2418compiler_import_as(struct compiler *c, identifier name, identifier asname)
2419{
2420 /* The IMPORT_NAME opcode was already generated. This function
2421 merely needs to bind the result to a name.
2422
2423 If there is a dot in name, we need to split it and emit a
2424 LOAD_ATTR for each name.
2425 */
2426 const char *src = PyString_AS_STRING(name);
2427 const char *dot = strchr(src, '.');
2428 if (dot) {
2429 /* Consume the base module name to get the first attribute */
2430 src = dot + 1;
2431 while (dot) {
2432 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002433 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002434 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002435 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002436 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002437 if (!attr)
2438 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002440 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441 src = dot + 1;
2442 }
2443 }
2444 return compiler_nameop(c, asname, Store);
2445}
2446
2447static int
2448compiler_import(struct compiler *c, stmt_ty s)
2449{
2450 /* The Import node stores a module name like a.b.c as a single
2451 string. This is convenient for all cases except
2452 import a.b.c as d
2453 where we need to parse that string to extract the individual
2454 module names.
2455 XXX Perhaps change the representation to make this case simpler?
2456 */
2457 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002458
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002459 for (i = 0; i < n; i++) {
2460 alias_ty alias = asdl_seq_GET(s->v.Import.names, i);
2461 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002462 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002463
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002464 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2465 level = PyInt_FromLong(0);
2466 else
2467 level = PyInt_FromLong(-1);
2468
2469 if (level == NULL)
2470 return 0;
2471
2472 ADDOP_O(c, LOAD_CONST, level, consts);
2473 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002474 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2475 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2476
2477 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002478 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002479 if (!r)
2480 return r;
2481 }
2482 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483 identifier tmp = alias->name;
2484 const char *base = PyString_AS_STRING(alias->name);
2485 char *dot = strchr(base, '.');
2486 if (dot)
2487 tmp = PyString_FromStringAndSize(base,
2488 dot - base);
2489 r = compiler_nameop(c, tmp, Store);
2490 if (dot) {
2491 Py_DECREF(tmp);
2492 }
2493 if (!r)
2494 return r;
2495 }
2496 }
2497 return 1;
2498}
2499
2500static int
2501compiler_from_import(struct compiler *c, stmt_ty s)
2502{
2503 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002504
2505 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002506 PyObject *level;
2507
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 if (!names)
2509 return 0;
2510
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002511 if (s->v.ImportFrom.level == 0 && c->c_flags &&
2512 !(c->c_flags->cf_flags & CO_FUTURE_ABSIMPORT))
2513 level = PyInt_FromLong(-1);
2514 else
2515 level = PyInt_FromLong(s->v.ImportFrom.level);
2516
2517 if (!level) {
2518 Py_DECREF(names);
2519 return 0;
2520 }
2521
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002522 /* build up the names */
2523 for (i = 0; i < n; i++) {
2524 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2525 Py_INCREF(alias->name);
2526 PyTuple_SET_ITEM(names, i, alias->name);
2527 }
2528
2529 if (s->lineno > c->c_future->ff_lineno) {
2530 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2531 "__future__")) {
2532 Py_DECREF(names);
2533 return compiler_error(c,
2534 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002535 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002536
2537 }
2538 }
2539
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002540 ADDOP_O(c, LOAD_CONST, level, consts);
2541 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002543 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2545 for (i = 0; i < n; i++) {
2546 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2547 identifier store_name;
2548
2549 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2550 assert(n == 1);
2551 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002552 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002553 }
2554
2555 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2556 store_name = alias->name;
2557 if (alias->asname)
2558 store_name = alias->asname;
2559
2560 if (!compiler_nameop(c, store_name, Store)) {
2561 Py_DECREF(names);
2562 return 0;
2563 }
2564 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002565 /* remove imported module */
2566 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002567 return 1;
2568}
2569
2570static int
2571compiler_assert(struct compiler *c, stmt_ty s)
2572{
2573 static PyObject *assertion_error = NULL;
2574 basicblock *end;
2575
2576 if (Py_OptimizeFlag)
2577 return 1;
2578 if (assertion_error == NULL) {
2579 assertion_error = PyString_FromString("AssertionError");
2580 if (assertion_error == NULL)
2581 return 0;
2582 }
2583 VISIT(c, expr, s->v.Assert.test);
2584 end = compiler_new_block(c);
2585 if (end == NULL)
2586 return 0;
2587 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2588 ADDOP(c, POP_TOP);
2589 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2590 if (s->v.Assert.msg) {
2591 VISIT(c, expr, s->v.Assert.msg);
2592 ADDOP_I(c, RAISE_VARARGS, 2);
2593 }
2594 else {
2595 ADDOP_I(c, RAISE_VARARGS, 1);
2596 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002597 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002598 ADDOP(c, POP_TOP);
2599 return 1;
2600}
2601
2602static int
2603compiler_visit_stmt(struct compiler *c, stmt_ty s)
2604{
2605 int i, n;
2606
2607 c->u->u_lineno = s->lineno;
2608 c->u->u_lineno_set = false;
2609 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002610 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002612 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002613 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002614 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615 if (c->u->u_ste->ste_type != FunctionBlock)
2616 return compiler_error(c, "'return' outside function");
2617 if (s->v.Return.value) {
2618 if (c->u->u_ste->ste_generator) {
2619 return compiler_error(c,
2620 "'return' with argument inside generator");
2621 }
2622 VISIT(c, expr, s->v.Return.value);
2623 }
2624 else
2625 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2626 ADDOP(c, RETURN_VALUE);
2627 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002628 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629 VISIT_SEQ(c, expr, s->v.Delete.targets)
2630 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002631 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632 n = asdl_seq_LEN(s->v.Assign.targets);
2633 VISIT(c, expr, s->v.Assign.value);
2634 for (i = 0; i < n; i++) {
2635 if (i < n - 1)
2636 ADDOP(c, DUP_TOP);
2637 VISIT(c, expr,
2638 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2639 }
2640 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002641 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002643 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002644 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002645 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002647 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002649 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002650 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002651 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002652 n = 0;
2653 if (s->v.Raise.type) {
2654 VISIT(c, expr, s->v.Raise.type);
2655 n++;
2656 if (s->v.Raise.inst) {
2657 VISIT(c, expr, s->v.Raise.inst);
2658 n++;
2659 if (s->v.Raise.tback) {
2660 VISIT(c, expr, s->v.Raise.tback);
2661 n++;
2662 }
2663 }
2664 }
2665 ADDOP_I(c, RAISE_VARARGS, n);
2666 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002667 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002668 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002669 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002671 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002673 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002675 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002677 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678 VISIT(c, expr, s->v.Exec.body);
2679 if (s->v.Exec.globals) {
2680 VISIT(c, expr, s->v.Exec.globals);
2681 if (s->v.Exec.locals) {
2682 VISIT(c, expr, s->v.Exec.locals);
2683 } else {
2684 ADDOP(c, DUP_TOP);
2685 }
2686 } else {
2687 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2688 ADDOP(c, DUP_TOP);
2689 }
2690 ADDOP(c, EXEC_STMT);
2691 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002692 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002694 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695 VISIT(c, expr, s->v.Expr.value);
2696 if (c->c_interactive && c->c_nestlevel <= 1) {
2697 ADDOP(c, PRINT_EXPR);
2698 }
2699 else {
2700 ADDOP(c, POP_TOP);
2701 }
2702 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002703 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002705 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706 if (!c->u->u_nfblocks)
2707 return compiler_error(c, "'break' outside loop");
2708 ADDOP(c, BREAK_LOOP);
2709 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002710 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002712 case With_kind:
2713 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002714 }
2715 return 1;
2716}
2717
2718static int
2719unaryop(unaryop_ty op)
2720{
2721 switch (op) {
2722 case Invert:
2723 return UNARY_INVERT;
2724 case Not:
2725 return UNARY_NOT;
2726 case UAdd:
2727 return UNARY_POSITIVE;
2728 case USub:
2729 return UNARY_NEGATIVE;
2730 }
2731 return 0;
2732}
2733
2734static int
2735binop(struct compiler *c, operator_ty op)
2736{
2737 switch (op) {
2738 case Add:
2739 return BINARY_ADD;
2740 case Sub:
2741 return BINARY_SUBTRACT;
2742 case Mult:
2743 return BINARY_MULTIPLY;
2744 case Div:
2745 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2746 return BINARY_TRUE_DIVIDE;
2747 else
2748 return BINARY_DIVIDE;
2749 case Mod:
2750 return BINARY_MODULO;
2751 case Pow:
2752 return BINARY_POWER;
2753 case LShift:
2754 return BINARY_LSHIFT;
2755 case RShift:
2756 return BINARY_RSHIFT;
2757 case BitOr:
2758 return BINARY_OR;
2759 case BitXor:
2760 return BINARY_XOR;
2761 case BitAnd:
2762 return BINARY_AND;
2763 case FloorDiv:
2764 return BINARY_FLOOR_DIVIDE;
2765 }
2766 return 0;
2767}
2768
2769static int
2770cmpop(cmpop_ty op)
2771{
2772 switch (op) {
2773 case Eq:
2774 return PyCmp_EQ;
2775 case NotEq:
2776 return PyCmp_NE;
2777 case Lt:
2778 return PyCmp_LT;
2779 case LtE:
2780 return PyCmp_LE;
2781 case Gt:
2782 return PyCmp_GT;
2783 case GtE:
2784 return PyCmp_GE;
2785 case Is:
2786 return PyCmp_IS;
2787 case IsNot:
2788 return PyCmp_IS_NOT;
2789 case In:
2790 return PyCmp_IN;
2791 case NotIn:
2792 return PyCmp_NOT_IN;
2793 }
2794 return PyCmp_BAD;
2795}
2796
2797static int
2798inplace_binop(struct compiler *c, operator_ty op)
2799{
2800 switch (op) {
2801 case Add:
2802 return INPLACE_ADD;
2803 case Sub:
2804 return INPLACE_SUBTRACT;
2805 case Mult:
2806 return INPLACE_MULTIPLY;
2807 case Div:
2808 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2809 return INPLACE_TRUE_DIVIDE;
2810 else
2811 return INPLACE_DIVIDE;
2812 case Mod:
2813 return INPLACE_MODULO;
2814 case Pow:
2815 return INPLACE_POWER;
2816 case LShift:
2817 return INPLACE_LSHIFT;
2818 case RShift:
2819 return INPLACE_RSHIFT;
2820 case BitOr:
2821 return INPLACE_OR;
2822 case BitXor:
2823 return INPLACE_XOR;
2824 case BitAnd:
2825 return INPLACE_AND;
2826 case FloorDiv:
2827 return INPLACE_FLOOR_DIVIDE;
2828 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002829 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002830 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831 return 0;
2832}
2833
2834static int
2835compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2836{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002837 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2839
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002840 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002841 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842 /* XXX AugStore isn't used anywhere! */
2843
2844 /* First check for assignment to __debug__. Param? */
2845 if ((ctx == Store || ctx == AugStore || ctx == Del)
2846 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2847 return compiler_error(c, "can not assign to __debug__");
2848 }
2849
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002850 mangled = _Py_Mangle(c->u->u_private, name);
2851 if (!mangled)
2852 return 0;
2853
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854 op = 0;
2855 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002856 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002857 switch (scope) {
2858 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002859 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002860 optype = OP_DEREF;
2861 break;
2862 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002863 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002864 optype = OP_DEREF;
2865 break;
2866 case LOCAL:
2867 if (c->u->u_ste->ste_type == FunctionBlock)
2868 optype = OP_FAST;
2869 break;
2870 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002871 if (c->u->u_ste->ste_type == FunctionBlock &&
2872 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002873 optype = OP_GLOBAL;
2874 break;
2875 case GLOBAL_EXPLICIT:
2876 optype = OP_GLOBAL;
2877 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002878 default:
2879 /* scope can be 0 */
2880 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002881 }
2882
2883 /* XXX Leave assert here, but handle __doc__ and the like better */
2884 assert(scope || PyString_AS_STRING(name)[0] == '_');
2885
2886 switch (optype) {
2887 case OP_DEREF:
2888 switch (ctx) {
2889 case Load: op = LOAD_DEREF; break;
2890 case Store: op = STORE_DEREF; break;
2891 case AugLoad:
2892 case AugStore:
2893 break;
2894 case Del:
2895 PyErr_Format(PyExc_SyntaxError,
2896 "can not delete variable '%s' referenced "
2897 "in nested scope",
2898 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002899 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002900 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002902 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002903 PyErr_SetString(PyExc_SystemError,
2904 "param invalid for deref variable");
2905 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906 }
2907 break;
2908 case OP_FAST:
2909 switch (ctx) {
2910 case Load: op = LOAD_FAST; break;
2911 case Store: op = STORE_FAST; break;
2912 case Del: op = DELETE_FAST; 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 local variable");
2920 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002922 ADDOP_O(c, op, mangled, varnames);
2923 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924 return 1;
2925 case OP_GLOBAL:
2926 switch (ctx) {
2927 case Load: op = LOAD_GLOBAL; break;
2928 case Store: op = STORE_GLOBAL; break;
2929 case Del: op = DELETE_GLOBAL; break;
2930 case AugLoad:
2931 case AugStore:
2932 break;
2933 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002934 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002935 PyErr_SetString(PyExc_SystemError,
2936 "param invalid for global variable");
2937 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002938 }
2939 break;
2940 case OP_NAME:
2941 switch (ctx) {
2942 case Load: op = LOAD_NAME; break;
2943 case Store: op = STORE_NAME; break;
2944 case Del: op = DELETE_NAME; break;
2945 case AugLoad:
2946 case AugStore:
2947 break;
2948 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002949 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002950 PyErr_SetString(PyExc_SystemError,
2951 "param invalid for name variable");
2952 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 }
2954 break;
2955 }
2956
2957 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002958 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002959 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002960 if (arg < 0)
2961 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002962 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963}
2964
2965static int
2966compiler_boolop(struct compiler *c, expr_ty e)
2967{
2968 basicblock *end;
2969 int jumpi, i, n;
2970 asdl_seq *s;
2971
2972 assert(e->kind == BoolOp_kind);
2973 if (e->v.BoolOp.op == And)
2974 jumpi = JUMP_IF_FALSE;
2975 else
2976 jumpi = JUMP_IF_TRUE;
2977 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002978 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979 return 0;
2980 s = e->v.BoolOp.values;
2981 n = asdl_seq_LEN(s) - 1;
2982 for (i = 0; i < n; ++i) {
2983 VISIT(c, expr, asdl_seq_GET(s, i));
2984 ADDOP_JREL(c, jumpi, end);
2985 ADDOP(c, POP_TOP)
2986 }
2987 VISIT(c, expr, asdl_seq_GET(s, n));
2988 compiler_use_next_block(c, end);
2989 return 1;
2990}
2991
2992static int
2993compiler_list(struct compiler *c, expr_ty e)
2994{
2995 int n = asdl_seq_LEN(e->v.List.elts);
2996 if (e->v.List.ctx == Store) {
2997 ADDOP_I(c, UNPACK_SEQUENCE, n);
2998 }
2999 VISIT_SEQ(c, expr, e->v.List.elts);
3000 if (e->v.List.ctx == Load) {
3001 ADDOP_I(c, BUILD_LIST, n);
3002 }
3003 return 1;
3004}
3005
3006static int
3007compiler_tuple(struct compiler *c, expr_ty e)
3008{
3009 int n = asdl_seq_LEN(e->v.Tuple.elts);
3010 if (e->v.Tuple.ctx == Store) {
3011 ADDOP_I(c, UNPACK_SEQUENCE, n);
3012 }
3013 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3014 if (e->v.Tuple.ctx == Load) {
3015 ADDOP_I(c, BUILD_TUPLE, n);
3016 }
3017 return 1;
3018}
3019
3020static int
3021compiler_compare(struct compiler *c, expr_ty e)
3022{
3023 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003024 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025
3026 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3027 VISIT(c, expr, e->v.Compare.left);
3028 n = asdl_seq_LEN(e->v.Compare.ops);
3029 assert(n > 0);
3030 if (n > 1) {
3031 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003032 if (cleanup == NULL)
3033 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003034 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3035 }
3036 for (i = 1; i < n; i++) {
3037 ADDOP(c, DUP_TOP);
3038 ADDOP(c, ROT_THREE);
3039 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3040 ADDOP_I(c, COMPARE_OP,
3041 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3042 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3043 NEXT_BLOCK(c);
3044 ADDOP(c, POP_TOP);
3045 if (i < (n - 1))
3046 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3047 }
3048 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3049 ADDOP_I(c, COMPARE_OP,
3050 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3051 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3052 if (n > 1) {
3053 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003054 if (end == NULL)
3055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003056 ADDOP_JREL(c, JUMP_FORWARD, end);
3057 compiler_use_next_block(c, cleanup);
3058 ADDOP(c, ROT_TWO);
3059 ADDOP(c, POP_TOP);
3060 compiler_use_next_block(c, end);
3061 }
3062 return 1;
3063}
3064
3065static int
3066compiler_call(struct compiler *c, expr_ty e)
3067{
3068 int n, code = 0;
3069
3070 VISIT(c, expr, e->v.Call.func);
3071 n = asdl_seq_LEN(e->v.Call.args);
3072 VISIT_SEQ(c, expr, e->v.Call.args);
3073 if (e->v.Call.keywords) {
3074 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3075 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3076 }
3077 if (e->v.Call.starargs) {
3078 VISIT(c, expr, e->v.Call.starargs);
3079 code |= 1;
3080 }
3081 if (e->v.Call.kwargs) {
3082 VISIT(c, expr, e->v.Call.kwargs);
3083 code |= 2;
3084 }
3085 switch (code) {
3086 case 0:
3087 ADDOP_I(c, CALL_FUNCTION, n);
3088 break;
3089 case 1:
3090 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3091 break;
3092 case 2:
3093 ADDOP_I(c, CALL_FUNCTION_KW, n);
3094 break;
3095 case 3:
3096 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3097 break;
3098 }
3099 return 1;
3100}
3101
3102static int
3103compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003104 asdl_seq *generators, int gen_index,
3105 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003106{
3107 /* generate code for the iterator, then each of the ifs,
3108 and then write to the element */
3109
3110 comprehension_ty l;
3111 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003112 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003113
3114 start = compiler_new_block(c);
3115 skip = compiler_new_block(c);
3116 if_cleanup = compiler_new_block(c);
3117 anchor = compiler_new_block(c);
3118
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003119 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3120 anchor == NULL)
3121 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122
3123 l = asdl_seq_GET(generators, gen_index);
3124 VISIT(c, expr, l->iter);
3125 ADDOP(c, GET_ITER);
3126 compiler_use_next_block(c, start);
3127 ADDOP_JREL(c, FOR_ITER, anchor);
3128 NEXT_BLOCK(c);
3129 VISIT(c, expr, l->target);
3130
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003131 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003132 n = asdl_seq_LEN(l->ifs);
3133 for (i = 0; i < n; i++) {
3134 expr_ty e = asdl_seq_GET(l->ifs, i);
3135 VISIT(c, expr, e);
3136 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3137 NEXT_BLOCK(c);
3138 ADDOP(c, POP_TOP);
3139 }
3140
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003141 if (++gen_index < asdl_seq_LEN(generators))
3142 if (!compiler_listcomp_generator(c, tmpname,
3143 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003144 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003146 /* only append after the last for generator */
3147 if (gen_index >= asdl_seq_LEN(generators)) {
3148 if (!compiler_nameop(c, tmpname, Load))
3149 return 0;
3150 VISIT(c, expr, elt);
3151 ADDOP_I(c, CALL_FUNCTION, 1);
3152 ADDOP(c, POP_TOP);
3153
3154 compiler_use_next_block(c, skip);
3155 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 for (i = 0; i < n; i++) {
3157 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003158 if (i == 0)
3159 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003160 ADDOP(c, POP_TOP);
3161 }
3162 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3163 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003164 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003166 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167 return 0;
3168
3169 return 1;
3170}
3171
3172static int
3173compiler_listcomp(struct compiler *c, expr_ty e)
3174{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003175 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003176 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177 static identifier append;
3178 asdl_seq *generators = e->v.ListComp.generators;
3179
3180 assert(e->kind == ListComp_kind);
3181 if (!append) {
3182 append = PyString_InternFromString("append");
3183 if (!append)
3184 return 0;
3185 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003186 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003187 if (!tmp)
3188 return 0;
3189 ADDOP_I(c, BUILD_LIST, 0);
3190 ADDOP(c, DUP_TOP);
3191 ADDOP_O(c, LOAD_ATTR, append, names);
3192 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003193 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3194 e->v.ListComp.elt);
3195 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003196 return rc;
3197}
3198
3199static int
3200compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003201 asdl_seq *generators, int gen_index,
3202 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003203{
3204 /* generate code for the iterator, then each of the ifs,
3205 and then write to the element */
3206
3207 comprehension_ty ge;
3208 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003209 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210
3211 start = compiler_new_block(c);
3212 skip = compiler_new_block(c);
3213 if_cleanup = compiler_new_block(c);
3214 anchor = compiler_new_block(c);
3215 end = compiler_new_block(c);
3216
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003217 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218 anchor == NULL || end == NULL)
3219 return 0;
3220
3221 ge = asdl_seq_GET(generators, gen_index);
3222 ADDOP_JREL(c, SETUP_LOOP, end);
3223 if (!compiler_push_fblock(c, LOOP, start))
3224 return 0;
3225
3226 if (gen_index == 0) {
3227 /* Receive outermost iter as an implicit argument */
3228 c->u->u_argcount = 1;
3229 ADDOP_I(c, LOAD_FAST, 0);
3230 }
3231 else {
3232 /* Sub-iter - calculate on the fly */
3233 VISIT(c, expr, ge->iter);
3234 ADDOP(c, GET_ITER);
3235 }
3236 compiler_use_next_block(c, start);
3237 ADDOP_JREL(c, FOR_ITER, anchor);
3238 NEXT_BLOCK(c);
3239 VISIT(c, expr, ge->target);
3240
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003241 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242 n = asdl_seq_LEN(ge->ifs);
3243 for (i = 0; i < n; i++) {
3244 expr_ty e = asdl_seq_GET(ge->ifs, i);
3245 VISIT(c, expr, e);
3246 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3247 NEXT_BLOCK(c);
3248 ADDOP(c, POP_TOP);
3249 }
3250
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003251 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3253 return 0;
3254
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003255 /* only append after the last 'for' generator */
3256 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257 VISIT(c, expr, elt);
3258 ADDOP(c, YIELD_VALUE);
3259 ADDOP(c, POP_TOP);
3260
3261 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003263 for (i = 0; i < n; i++) {
3264 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003265 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 compiler_use_next_block(c, if_cleanup);
3267
3268 ADDOP(c, POP_TOP);
3269 }
3270 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3271 compiler_use_next_block(c, anchor);
3272 ADDOP(c, POP_BLOCK);
3273 compiler_pop_fblock(c, LOOP, start);
3274 compiler_use_next_block(c, end);
3275
3276 return 1;
3277}
3278
3279static int
3280compiler_genexp(struct compiler *c, expr_ty e)
3281{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003282 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283 PyCodeObject *co;
3284 expr_ty outermost_iter = ((comprehension_ty)
3285 (asdl_seq_GET(e->v.GeneratorExp.generators,
3286 0)))->iter;
3287
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003288 if (!name) {
3289 name = PyString_FromString("<genexpr>");
3290 if (!name)
3291 return 0;
3292 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293
3294 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3295 return 0;
3296 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3297 e->v.GeneratorExp.elt);
3298 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003299 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003300 if (co == NULL)
3301 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003303 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003304 Py_DECREF(co);
3305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003306 VISIT(c, expr, outermost_iter);
3307 ADDOP(c, GET_ITER);
3308 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
3310 return 1;
3311}
3312
3313static int
3314compiler_visit_keyword(struct compiler *c, keyword_ty k)
3315{
3316 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3317 VISIT(c, expr, k->value);
3318 return 1;
3319}
3320
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003321/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003322 whether they are true or false.
3323
3324 Return values: 1 for true, 0 for false, -1 for non-constant.
3325 */
3326
3327static int
3328expr_constant(expr_ty e)
3329{
3330 switch (e->kind) {
3331 case Num_kind:
3332 return PyObject_IsTrue(e->v.Num.n);
3333 case Str_kind:
3334 return PyObject_IsTrue(e->v.Str.s);
3335 default:
3336 return -1;
3337 }
3338}
3339
Guido van Rossumc2e20742006-02-27 22:32:47 +00003340/*
3341 Implements the with statement from PEP 343.
3342
3343 The semantics outlined in that PEP are as follows:
3344
3345 with EXPR as VAR:
3346 BLOCK
3347
3348 It is implemented roughly as:
3349
3350 context = (EXPR).__context__()
3351 exit = context.__exit__ # not calling it
3352 value = context.__enter__()
3353 try:
3354 VAR = value # if VAR present in the syntax
3355 BLOCK
3356 finally:
3357 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003358 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003359 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003360 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003361 exit(*exc)
3362 */
3363static int
3364compiler_with(struct compiler *c, stmt_ty s)
3365{
3366 static identifier context_attr, enter_attr, exit_attr;
3367 basicblock *block, *finally;
3368 identifier tmpexit, tmpvalue = NULL;
3369
3370 assert(s->kind == With_kind);
3371
3372 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003373 context_attr = PyString_InternFromString("__context__");
3374 if (!context_attr)
3375 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003376 }
3377 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003378 enter_attr = PyString_InternFromString("__enter__");
3379 if (!enter_attr)
3380 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003381 }
3382 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003383 exit_attr = PyString_InternFromString("__exit__");
3384 if (!exit_attr)
3385 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003386 }
3387
3388 block = compiler_new_block(c);
3389 finally = compiler_new_block(c);
3390 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003391 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003392
3393 /* Create a temporary variable to hold context.__exit__ */
3394 tmpexit = compiler_new_tmpname(c);
3395 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003396 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003397 PyArena_AddPyObject(c->c_arena, tmpexit);
3398
3399 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003400 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003401 We need to do this rather than preserving it on the stack
3402 because SETUP_FINALLY remembers the stack level.
3403 We need to do the assignment *inside* the try/finally
3404 so that context.__exit__() is called when the assignment
3405 fails. But we need to call context.__enter__() *before*
3406 the try/finally so that if it fails we won't call
3407 context.__exit__().
3408 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003409 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003410 if (tmpvalue == NULL)
3411 return 0;
3412 PyArena_AddPyObject(c->c_arena, tmpvalue);
3413 }
3414
3415 /* Evaluate (EXPR).__context__() */
3416 VISIT(c, expr, s->v.With.context_expr);
3417 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3418 ADDOP_I(c, CALL_FUNCTION, 0);
3419
3420 /* Squirrel away context.__exit__ */
3421 ADDOP(c, DUP_TOP);
3422 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3423 if (!compiler_nameop(c, tmpexit, Store))
3424 return 0;
3425
3426 /* Call context.__enter__() */
3427 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3428 ADDOP_I(c, CALL_FUNCTION, 0);
3429
3430 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003431 /* Store it in tmpvalue */
3432 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003433 return 0;
3434 }
3435 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003436 /* Discard result from context.__enter__() */
3437 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003438 }
3439
3440 /* Start the try block */
3441 ADDOP_JREL(c, SETUP_FINALLY, finally);
3442
3443 compiler_use_next_block(c, block);
3444 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003445 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003446 }
3447
3448 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003449 /* Bind saved result of context.__enter__() to VAR */
3450 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003451 !compiler_nameop(c, tmpvalue, Del))
3452 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003453 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003454 }
3455
3456 /* BLOCK code */
3457 VISIT_SEQ(c, stmt, s->v.With.body);
3458
3459 /* End of try block; start the finally block */
3460 ADDOP(c, POP_BLOCK);
3461 compiler_pop_fblock(c, FINALLY_TRY, block);
3462
3463 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3464 compiler_use_next_block(c, finally);
3465 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003466 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003467
3468 /* Finally block starts; push tmpexit and issue our magic opcode. */
3469 if (!compiler_nameop(c, tmpexit, Load) ||
3470 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003471 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003472 ADDOP(c, WITH_CLEANUP);
3473 ADDOP_I(c, CALL_FUNCTION, 3);
3474 ADDOP(c, POP_TOP);
3475
3476 /* Finally block ends. */
3477 ADDOP(c, END_FINALLY);
3478 compiler_pop_fblock(c, FINALLY_END, finally);
3479 return 1;
3480}
3481
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482static int
3483compiler_visit_expr(struct compiler *c, expr_ty e)
3484{
3485 int i, n;
3486
3487 if (e->lineno > c->u->u_lineno) {
3488 c->u->u_lineno = e->lineno;
3489 c->u->u_lineno_set = false;
3490 }
3491 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003492 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003494 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495 VISIT(c, expr, e->v.BinOp.left);
3496 VISIT(c, expr, e->v.BinOp.right);
3497 ADDOP(c, binop(c, e->v.BinOp.op));
3498 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003499 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500 VISIT(c, expr, e->v.UnaryOp.operand);
3501 ADDOP(c, unaryop(e->v.UnaryOp.op));
3502 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003503 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003505 case IfExp_kind:
3506 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003508 /* XXX get rid of arg? */
3509 ADDOP_I(c, BUILD_MAP, 0);
3510 n = asdl_seq_LEN(e->v.Dict.values);
3511 /* We must arrange things just right for STORE_SUBSCR.
3512 It wants the stack to look like (value) (dict) (key) */
3513 for (i = 0; i < n; i++) {
3514 ADDOP(c, DUP_TOP);
3515 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3516 ADDOP(c, ROT_TWO);
3517 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3518 ADDOP(c, STORE_SUBSCR);
3519 }
3520 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003521 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003523 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003524 return compiler_genexp(c, e);
3525 case Yield_kind:
3526 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003527 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003528 /*
3529 for (i = 0; i < c->u->u_nfblocks; i++) {
3530 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3531 return compiler_error(
3532 c, "'yield' not allowed in a 'try' "
3533 "block with a 'finally' clause");
3534 }
3535 */
3536 if (e->v.Yield.value) {
3537 VISIT(c, expr, e->v.Yield.value);
3538 }
3539 else {
3540 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3541 }
3542 ADDOP(c, YIELD_VALUE);
3543 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003544 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003545 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003546 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003548 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003549 VISIT(c, expr, e->v.Repr.value);
3550 ADDOP(c, UNARY_CONVERT);
3551 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003552 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003553 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3554 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003555 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003556 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3557 break;
3558 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003559 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560 if (e->v.Attribute.ctx != AugStore)
3561 VISIT(c, expr, e->v.Attribute.value);
3562 switch (e->v.Attribute.ctx) {
3563 case AugLoad:
3564 ADDOP(c, DUP_TOP);
3565 /* Fall through to load */
3566 case Load:
3567 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3568 break;
3569 case AugStore:
3570 ADDOP(c, ROT_TWO);
3571 /* Fall through to save */
3572 case Store:
3573 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3574 break;
3575 case Del:
3576 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3577 break;
3578 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003579 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003580 PyErr_SetString(PyExc_SystemError,
3581 "param invalid in attribute expression");
3582 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583 }
3584 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003585 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586 switch (e->v.Subscript.ctx) {
3587 case AugLoad:
3588 VISIT(c, expr, e->v.Subscript.value);
3589 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3590 break;
3591 case Load:
3592 VISIT(c, expr, e->v.Subscript.value);
3593 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3594 break;
3595 case AugStore:
3596 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3597 break;
3598 case Store:
3599 VISIT(c, expr, e->v.Subscript.value);
3600 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3601 break;
3602 case Del:
3603 VISIT(c, expr, e->v.Subscript.value);
3604 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3605 break;
3606 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003607 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003608 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003609 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003610 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003611 }
3612 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003613 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3615 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003616 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003618 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619 return compiler_tuple(c, e);
3620 }
3621 return 1;
3622}
3623
3624static int
3625compiler_augassign(struct compiler *c, stmt_ty s)
3626{
3627 expr_ty e = s->v.AugAssign.target;
3628 expr_ty auge;
3629
3630 assert(s->kind == AugAssign_kind);
3631
3632 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003633 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003635 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003636 if (auge == NULL)
3637 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003638 VISIT(c, expr, auge);
3639 VISIT(c, expr, s->v.AugAssign.value);
3640 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3641 auge->v.Attribute.ctx = AugStore;
3642 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003643 break;
3644 case Subscript_kind:
3645 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003646 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003647 if (auge == NULL)
3648 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649 VISIT(c, expr, auge);
3650 VISIT(c, expr, s->v.AugAssign.value);
3651 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003652 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 case Name_kind:
3656 VISIT(c, expr, s->v.AugAssign.target);
3657 VISIT(c, expr, s->v.AugAssign.value);
3658 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3659 return compiler_nameop(c, e->v.Name.id, Store);
3660 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003661 PyErr_Format(PyExc_SystemError,
3662 "invalid node type (%d) for augmented assignment",
3663 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003664 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003665 }
3666 return 1;
3667}
3668
3669static int
3670compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3671{
3672 struct fblockinfo *f;
3673 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3674 return 0;
3675 f = &c->u->u_fblock[c->u->u_nfblocks++];
3676 f->fb_type = t;
3677 f->fb_block = b;
3678 return 1;
3679}
3680
3681static void
3682compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3683{
3684 struct compiler_unit *u = c->u;
3685 assert(u->u_nfblocks > 0);
3686 u->u_nfblocks--;
3687 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3688 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3689}
3690
3691/* Raises a SyntaxError and returns 0.
3692 If something goes wrong, a different exception may be raised.
3693*/
3694
3695static int
3696compiler_error(struct compiler *c, const char *errstr)
3697{
3698 PyObject *loc;
3699 PyObject *u = NULL, *v = NULL;
3700
3701 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3702 if (!loc) {
3703 Py_INCREF(Py_None);
3704 loc = Py_None;
3705 }
3706 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3707 Py_None, loc);
3708 if (!u)
3709 goto exit;
3710 v = Py_BuildValue("(zO)", errstr, u);
3711 if (!v)
3712 goto exit;
3713 PyErr_SetObject(PyExc_SyntaxError, v);
3714 exit:
3715 Py_DECREF(loc);
3716 Py_XDECREF(u);
3717 Py_XDECREF(v);
3718 return 0;
3719}
3720
3721static int
3722compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003723 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003724{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003725 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003726
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003727 /* XXX this code is duplicated */
3728 switch (ctx) {
3729 case AugLoad: /* fall through to Load */
3730 case Load: op = BINARY_SUBSCR; break;
3731 case AugStore:/* fall through to Store */
3732 case Store: op = STORE_SUBSCR; break;
3733 case Del: op = DELETE_SUBSCR; break;
3734 case Param:
3735 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003736 "invalid %s kind %d in subscript\n",
3737 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003738 return 0;
3739 }
3740 if (ctx == AugLoad) {
3741 ADDOP_I(c, DUP_TOPX, 2);
3742 }
3743 else if (ctx == AugStore) {
3744 ADDOP(c, ROT_THREE);
3745 }
3746 ADDOP(c, op);
3747 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003748}
3749
3750static int
3751compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3752{
3753 int n = 2;
3754 assert(s->kind == Slice_kind);
3755
3756 /* only handles the cases where BUILD_SLICE is emitted */
3757 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003758 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003759 }
3760 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003761 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003762 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003764 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003765 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 }
3767 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003768 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769 }
3770
3771 if (s->v.Slice.step) {
3772 n++;
3773 VISIT(c, expr, s->v.Slice.step);
3774 }
3775 ADDOP_I(c, BUILD_SLICE, n);
3776 return 1;
3777}
3778
3779static int
3780compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3781{
3782 int op = 0, slice_offset = 0, stack_count = 0;
3783
3784 assert(s->v.Slice.step == NULL);
3785 if (s->v.Slice.lower) {
3786 slice_offset++;
3787 stack_count++;
3788 if (ctx != AugStore)
3789 VISIT(c, expr, s->v.Slice.lower);
3790 }
3791 if (s->v.Slice.upper) {
3792 slice_offset += 2;
3793 stack_count++;
3794 if (ctx != AugStore)
3795 VISIT(c, expr, s->v.Slice.upper);
3796 }
3797
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003798 if (ctx == AugLoad) {
3799 switch (stack_count) {
3800 case 0: ADDOP(c, DUP_TOP); break;
3801 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3802 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3803 }
3804 }
3805 else if (ctx == AugStore) {
3806 switch (stack_count) {
3807 case 0: ADDOP(c, ROT_TWO); break;
3808 case 1: ADDOP(c, ROT_THREE); break;
3809 case 2: ADDOP(c, ROT_FOUR); break;
3810 }
3811 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812
3813 switch (ctx) {
3814 case AugLoad: /* fall through to Load */
3815 case Load: op = SLICE; break;
3816 case AugStore:/* fall through to Store */
3817 case Store: op = STORE_SLICE; break;
3818 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003819 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003820 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003821 PyErr_SetString(PyExc_SystemError,
3822 "param invalid in simple slice");
3823 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003824 }
3825
3826 ADDOP(c, op + slice_offset);
3827 return 1;
3828}
3829
3830static int
3831compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3832 expr_context_ty ctx)
3833{
3834 switch (s->kind) {
3835 case Ellipsis_kind:
3836 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3837 break;
3838 case Slice_kind:
3839 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003840 case Index_kind:
3841 VISIT(c, expr, s->v.Index.value);
3842 break;
3843 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003844 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003845 PyErr_SetString(PyExc_SystemError,
3846 "extended slice invalid in nested slice");
3847 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848 }
3849 return 1;
3850}
3851
3852
3853static int
3854compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3855{
3856 switch (s->kind) {
3857 case Ellipsis_kind:
3858 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3859 break;
3860 case Slice_kind:
3861 if (!s->v.Slice.step)
3862 return compiler_simple_slice(c, s, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003863 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003864 return 0;
3865 if (ctx == AugLoad) {
3866 ADDOP_I(c, DUP_TOPX, 2);
3867 }
3868 else if (ctx == AugStore) {
3869 ADDOP(c, ROT_THREE);
3870 }
3871 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003872 case ExtSlice_kind: {
3873 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3874 for (i = 0; i < n; i++) {
3875 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3876 if (!compiler_visit_nested_slice(c, sub, ctx))
3877 return 0;
3878 }
3879 ADDOP_I(c, BUILD_TUPLE, n);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003880 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 }
3882 case Index_kind:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003883 if (ctx != AugStore)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 VISIT(c, expr, s->v.Index.value);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003885 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003886 default:
3887 PyErr_Format(PyExc_SystemError,
3888 "invalid slice %d", s->kind);
3889 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003890 }
3891 return 1;
3892}
3893
3894/* do depth-first search of basic block graph, starting with block.
3895 post records the block indices in post-order.
3896
3897 XXX must handle implicit jumps from one block to next
3898*/
3899
3900static void
3901dfs(struct compiler *c, basicblock *b, struct assembler *a)
3902{
3903 int i;
3904 struct instr *instr = NULL;
3905
3906 if (b->b_seen)
3907 return;
3908 b->b_seen = 1;
3909 if (b->b_next != NULL)
3910 dfs(c, b->b_next, a);
3911 for (i = 0; i < b->b_iused; i++) {
3912 instr = &b->b_instr[i];
3913 if (instr->i_jrel || instr->i_jabs)
3914 dfs(c, instr->i_target, a);
3915 }
3916 a->a_postorder[a->a_nblocks++] = b;
3917}
3918
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003919static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3921{
3922 int i;
3923 struct instr *instr;
3924 if (b->b_seen || b->b_startdepth >= depth)
3925 return maxdepth;
3926 b->b_seen = 1;
3927 b->b_startdepth = depth;
3928 for (i = 0; i < b->b_iused; i++) {
3929 instr = &b->b_instr[i];
3930 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3931 if (depth > maxdepth)
3932 maxdepth = depth;
3933 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3934 if (instr->i_jrel || instr->i_jabs) {
3935 maxdepth = stackdepth_walk(c, instr->i_target,
3936 depth, maxdepth);
3937 if (instr->i_opcode == JUMP_ABSOLUTE ||
3938 instr->i_opcode == JUMP_FORWARD) {
3939 goto out; /* remaining code is dead */
3940 }
3941 }
3942 }
3943 if (b->b_next)
3944 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3945out:
3946 b->b_seen = 0;
3947 return maxdepth;
3948}
3949
3950/* Find the flow path that needs the largest stack. We assume that
3951 * cycles in the flow graph have no net effect on the stack depth.
3952 */
3953static int
3954stackdepth(struct compiler *c)
3955{
3956 basicblock *b, *entryblock;
3957 entryblock = NULL;
3958 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3959 b->b_seen = 0;
3960 b->b_startdepth = INT_MIN;
3961 entryblock = b;
3962 }
3963 return stackdepth_walk(c, entryblock, 0, 0);
3964}
3965
3966static int
3967assemble_init(struct assembler *a, int nblocks, int firstlineno)
3968{
3969 memset(a, 0, sizeof(struct assembler));
3970 a->a_lineno = firstlineno;
3971 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3972 if (!a->a_bytecode)
3973 return 0;
3974 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3975 if (!a->a_lnotab)
3976 return 0;
3977 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003978 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003979 if (!a->a_postorder) {
3980 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003981 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003982 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003983 return 1;
3984}
3985
3986static void
3987assemble_free(struct assembler *a)
3988{
3989 Py_XDECREF(a->a_bytecode);
3990 Py_XDECREF(a->a_lnotab);
3991 if (a->a_postorder)
3992 PyObject_Free(a->a_postorder);
3993}
3994
3995/* Return the size of a basic block in bytes. */
3996
3997static int
3998instrsize(struct instr *instr)
3999{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004000 if (!instr->i_hasarg)
4001 return 1;
4002 if (instr->i_oparg > 0xffff)
4003 return 6;
4004 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004005}
4006
4007static int
4008blocksize(basicblock *b)
4009{
4010 int i;
4011 int size = 0;
4012
4013 for (i = 0; i < b->b_iused; i++)
4014 size += instrsize(&b->b_instr[i]);
4015 return size;
4016}
4017
4018/* All about a_lnotab.
4019
4020c_lnotab is an array of unsigned bytes disguised as a Python string.
4021It is used to map bytecode offsets to source code line #s (when needed
4022for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004023
Tim Peters2a7f3842001-06-09 09:26:21 +00004024The array is conceptually a list of
4025 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004026pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004027
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004028 byte code offset source code line number
4029 0 1
4030 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004031 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004032 350 307
4033 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004034
4035The first trick is that these numbers aren't stored, only the increments
4036from one row to the next (this doesn't really work, but it's a start):
4037
4038 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4039
4040The second trick is that an unsigned byte can't hold negative values, or
4041values larger than 255, so (a) there's a deep assumption that byte code
4042offsets and their corresponding line #s both increase monotonically, and (b)
4043if at least one column jumps by more than 255 from one row to the next, more
4044than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004045from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004046part. A user of c_lnotab desiring to find the source line number
4047corresponding to a bytecode address A should do something like this
4048
4049 lineno = addr = 0
4050 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004051 addr += addr_incr
4052 if addr > A:
4053 return lineno
4054 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004055
4056In order for this to work, when the addr field increments by more than 255,
4057the line # increment in each pair generated must be 0 until the remaining addr
4058increment is < 256. So, in the example above, com_set_lineno should not (as
4059was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004060255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004061*/
4062
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004063static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004065{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066 int d_bytecode, d_lineno;
4067 int len;
4068 char *lnotab;
4069
4070 d_bytecode = a->a_offset - a->a_lineno_off;
4071 d_lineno = i->i_lineno - a->a_lineno;
4072
4073 assert(d_bytecode >= 0);
4074 assert(d_lineno >= 0);
4075
4076 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004077 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004078
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004079 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004080 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004081 nbytes = a->a_lnotab_off + 2 * ncodes;
4082 len = PyString_GET_SIZE(a->a_lnotab);
4083 if (nbytes >= len) {
4084 if (len * 2 < nbytes)
4085 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004086 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004087 len *= 2;
4088 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4089 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004090 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004092 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093 *lnotab++ = 255;
4094 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004095 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096 d_bytecode -= ncodes * 255;
4097 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004098 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004099 assert(d_bytecode <= 255);
4100 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004101 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004102 nbytes = a->a_lnotab_off + 2 * ncodes;
4103 len = PyString_GET_SIZE(a->a_lnotab);
4104 if (nbytes >= len) {
4105 if (len * 2 < nbytes)
4106 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004107 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004108 len *= 2;
4109 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4110 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004111 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004112 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4113 *lnotab++ = 255;
4114 *lnotab++ = d_bytecode;
4115 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004116 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 *lnotab++ = 255;
4118 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004119 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004120 d_lineno -= ncodes * 255;
4121 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004122 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004123
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004124 len = PyString_GET_SIZE(a->a_lnotab);
4125 if (a->a_lnotab_off + 2 >= len) {
4126 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004127 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004128 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004129 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004131 a->a_lnotab_off += 2;
4132 if (d_bytecode) {
4133 *lnotab++ = d_bytecode;
4134 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004135 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004136 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004137 *lnotab++ = 0;
4138 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004139 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004140 a->a_lineno = i->i_lineno;
4141 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004142 return 1;
4143}
4144
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004145/* assemble_emit()
4146 Extend the bytecode with a new instruction.
4147 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004148*/
4149
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004150static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004152{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004153 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004154 int len = PyString_GET_SIZE(a->a_bytecode);
4155 char *code;
4156
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004157 size = instrsize(i);
4158 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004159 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004160 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004161 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004162 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004163 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004164 if (a->a_offset + size >= len) {
4165 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004166 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004167 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004168 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4169 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004170 if (size == 6) {
4171 assert(i->i_hasarg);
4172 *code++ = (char)EXTENDED_ARG;
4173 *code++ = ext & 0xff;
4174 *code++ = ext >> 8;
4175 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004176 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004178 if (i->i_hasarg) {
4179 assert(size == 3 || size == 6);
4180 *code++ = arg & 0xff;
4181 *code++ = arg >> 8;
4182 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004183 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004184}
4185
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004186static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004187assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004188{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004189 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004190 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004191 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004192
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004193 /* Compute the size of each block and fixup jump args.
4194 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004195start:
4196 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004197 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004198 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199 bsize = blocksize(b);
4200 b->b_offset = totsize;
4201 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004202 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004203 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4205 bsize = b->b_offset;
4206 for (i = 0; i < b->b_iused; i++) {
4207 struct instr *instr = &b->b_instr[i];
4208 /* Relative jumps are computed relative to
4209 the instruction pointer after fetching
4210 the jump instruction.
4211 */
4212 bsize += instrsize(instr);
4213 if (instr->i_jabs)
4214 instr->i_oparg = instr->i_target->b_offset;
4215 else if (instr->i_jrel) {
4216 int delta = instr->i_target->b_offset - bsize;
4217 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004218 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004219 else
4220 continue;
4221 if (instr->i_oparg > 0xffff)
4222 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004223 }
4224 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004225
4226 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004227 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004228 with a better solution.
4229
4230 In the meantime, should the goto be dropped in favor
4231 of a loop?
4232
4233 The issue is that in the first loop blocksize() is called
4234 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004235 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004236 i_oparg is calculated in the second loop above.
4237
4238 So we loop until we stop seeing new EXTENDED_ARGs.
4239 The only EXTENDED_ARGs that could be popping up are
4240 ones in jump instructions. So this should converge
4241 fairly quickly.
4242 */
4243 if (last_extended_arg_count != extended_arg_count) {
4244 last_extended_arg_count = extended_arg_count;
4245 goto start;
4246 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004247}
4248
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004249static PyObject *
4250dict_keys_inorder(PyObject *dict, int offset)
4251{
4252 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004253 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004254
4255 tuple = PyTuple_New(size);
4256 if (tuple == NULL)
4257 return NULL;
4258 while (PyDict_Next(dict, &pos, &k, &v)) {
4259 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004260 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004261 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004262 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004263 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004264 PyTuple_SET_ITEM(tuple, i - offset, k);
4265 }
4266 return tuple;
4267}
4268
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004269static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004270compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004271{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004272 PySTEntryObject *ste = c->u->u_ste;
4273 int flags = 0, n;
4274 if (ste->ste_type != ModuleBlock)
4275 flags |= CO_NEWLOCALS;
4276 if (ste->ste_type == FunctionBlock) {
4277 if (!ste->ste_unoptimized)
4278 flags |= CO_OPTIMIZED;
4279 if (ste->ste_nested)
4280 flags |= CO_NESTED;
4281 if (ste->ste_generator)
4282 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004283 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284 if (ste->ste_varargs)
4285 flags |= CO_VARARGS;
4286 if (ste->ste_varkeywords)
4287 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004288 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004289 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004290
4291 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004292 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004293
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004294 n = PyDict_Size(c->u->u_freevars);
4295 if (n < 0)
4296 return -1;
4297 if (n == 0) {
4298 n = PyDict_Size(c->u->u_cellvars);
4299 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004300 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301 if (n == 0) {
4302 flags |= CO_NOFREE;
4303 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004304 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004305
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004306 return flags;
4307}
4308
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004309static PyCodeObject *
4310makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004311{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004312 PyObject *tmp;
4313 PyCodeObject *co = NULL;
4314 PyObject *consts = NULL;
4315 PyObject *names = NULL;
4316 PyObject *varnames = NULL;
4317 PyObject *filename = NULL;
4318 PyObject *name = NULL;
4319 PyObject *freevars = NULL;
4320 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004321 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004322 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004324 tmp = dict_keys_inorder(c->u->u_consts, 0);
4325 if (!tmp)
4326 goto error;
4327 consts = PySequence_List(tmp); /* optimize_code requires a list */
4328 Py_DECREF(tmp);
4329
4330 names = dict_keys_inorder(c->u->u_names, 0);
4331 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4332 if (!consts || !names || !varnames)
4333 goto error;
4334
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004335 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4336 if (!cellvars)
4337 goto error;
4338 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4339 if (!freevars)
4340 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004341 filename = PyString_FromString(c->c_filename);
4342 if (!filename)
4343 goto error;
4344
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004345 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004346 flags = compute_code_flags(c);
4347 if (flags < 0)
4348 goto error;
4349
4350 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4351 if (!bytecode)
4352 goto error;
4353
4354 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4355 if (!tmp)
4356 goto error;
4357 Py_DECREF(consts);
4358 consts = tmp;
4359
4360 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4361 bytecode, consts, names, varnames,
4362 freevars, cellvars,
4363 filename, c->u->u_name,
4364 c->u->u_firstlineno,
4365 a->a_lnotab);
4366 error:
4367 Py_XDECREF(consts);
4368 Py_XDECREF(names);
4369 Py_XDECREF(varnames);
4370 Py_XDECREF(filename);
4371 Py_XDECREF(name);
4372 Py_XDECREF(freevars);
4373 Py_XDECREF(cellvars);
4374 Py_XDECREF(bytecode);
4375 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004376}
4377
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378static PyCodeObject *
4379assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004380{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381 basicblock *b, *entryblock;
4382 struct assembler a;
4383 int i, j, nblocks;
4384 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004385
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004386 /* Make sure every block that falls off the end returns None.
4387 XXX NEXT_BLOCK() isn't quite right, because if the last
4388 block ends with a jump or return b_next shouldn't set.
4389 */
4390 if (!c->u->u_curblock->b_return) {
4391 NEXT_BLOCK(c);
4392 if (addNone)
4393 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4394 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004395 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004396
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004397 nblocks = 0;
4398 entryblock = NULL;
4399 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4400 nblocks++;
4401 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004402 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004403
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4405 goto error;
4406 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004407
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004408 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004409 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411 /* Emit code in reverse postorder from dfs. */
4412 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004413 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414 for (j = 0; j < b->b_iused; j++)
4415 if (!assemble_emit(&a, &b->b_instr[j]))
4416 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004417 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004418
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4420 goto error;
4421 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4422 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004423
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004424 co = makecode(c, &a);
4425 error:
4426 assemble_free(&a);
4427 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004428}