blob: 7abc11777dc8056a71eb2e622116abf88191e29c [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__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002532 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002533 Py_DECREF(names);
2534 return compiler_error(c,
2535 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002536 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537
2538 }
2539 }
2540
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002541 ADDOP_O(c, LOAD_CONST, level, consts);
2542 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002543 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002544 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2546 for (i = 0; i < n; i++) {
2547 alias_ty alias = asdl_seq_GET(s->v.ImportFrom.names, i);
2548 identifier store_name;
2549
2550 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2551 assert(n == 1);
2552 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002553 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002554 }
2555
2556 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2557 store_name = alias->name;
2558 if (alias->asname)
2559 store_name = alias->asname;
2560
2561 if (!compiler_nameop(c, store_name, Store)) {
2562 Py_DECREF(names);
2563 return 0;
2564 }
2565 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002566 /* remove imported module */
2567 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002568 return 1;
2569}
2570
2571static int
2572compiler_assert(struct compiler *c, stmt_ty s)
2573{
2574 static PyObject *assertion_error = NULL;
2575 basicblock *end;
2576
2577 if (Py_OptimizeFlag)
2578 return 1;
2579 if (assertion_error == NULL) {
2580 assertion_error = PyString_FromString("AssertionError");
2581 if (assertion_error == NULL)
2582 return 0;
2583 }
2584 VISIT(c, expr, s->v.Assert.test);
2585 end = compiler_new_block(c);
2586 if (end == NULL)
2587 return 0;
2588 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2589 ADDOP(c, POP_TOP);
2590 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2591 if (s->v.Assert.msg) {
2592 VISIT(c, expr, s->v.Assert.msg);
2593 ADDOP_I(c, RAISE_VARARGS, 2);
2594 }
2595 else {
2596 ADDOP_I(c, RAISE_VARARGS, 1);
2597 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002598 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002599 ADDOP(c, POP_TOP);
2600 return 1;
2601}
2602
2603static int
2604compiler_visit_stmt(struct compiler *c, stmt_ty s)
2605{
2606 int i, n;
2607
2608 c->u->u_lineno = s->lineno;
2609 c->u->u_lineno_set = false;
2610 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002611 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002612 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002613 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002615 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616 if (c->u->u_ste->ste_type != FunctionBlock)
2617 return compiler_error(c, "'return' outside function");
2618 if (s->v.Return.value) {
2619 if (c->u->u_ste->ste_generator) {
2620 return compiler_error(c,
2621 "'return' with argument inside generator");
2622 }
2623 VISIT(c, expr, s->v.Return.value);
2624 }
2625 else
2626 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2627 ADDOP(c, RETURN_VALUE);
2628 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002629 case Delete_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630 VISIT_SEQ(c, expr, s->v.Delete.targets)
2631 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002632 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633 n = asdl_seq_LEN(s->v.Assign.targets);
2634 VISIT(c, expr, s->v.Assign.value);
2635 for (i = 0; i < n; i++) {
2636 if (i < n - 1)
2637 ADDOP(c, DUP_TOP);
2638 VISIT(c, expr,
2639 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2640 }
2641 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002642 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002644 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002646 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002648 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002650 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002652 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653 n = 0;
2654 if (s->v.Raise.type) {
2655 VISIT(c, expr, s->v.Raise.type);
2656 n++;
2657 if (s->v.Raise.inst) {
2658 VISIT(c, expr, s->v.Raise.inst);
2659 n++;
2660 if (s->v.Raise.tback) {
2661 VISIT(c, expr, s->v.Raise.tback);
2662 n++;
2663 }
2664 }
2665 }
2666 ADDOP_I(c, RAISE_VARARGS, n);
2667 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002668 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002670 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002672 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002674 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002676 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002677 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002678 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679 VISIT(c, expr, s->v.Exec.body);
2680 if (s->v.Exec.globals) {
2681 VISIT(c, expr, s->v.Exec.globals);
2682 if (s->v.Exec.locals) {
2683 VISIT(c, expr, s->v.Exec.locals);
2684 } else {
2685 ADDOP(c, DUP_TOP);
2686 }
2687 } else {
2688 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2689 ADDOP(c, DUP_TOP);
2690 }
2691 ADDOP(c, EXEC_STMT);
2692 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002693 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002694 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002695 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696 VISIT(c, expr, s->v.Expr.value);
2697 if (c->c_interactive && c->c_nestlevel <= 1) {
2698 ADDOP(c, PRINT_EXPR);
2699 }
2700 else {
2701 ADDOP(c, POP_TOP);
2702 }
2703 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002704 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002705 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002706 case Break_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002707 if (!c->u->u_nfblocks)
2708 return compiler_error(c, "'break' outside loop");
2709 ADDOP(c, BREAK_LOOP);
2710 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002711 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002713 case With_kind:
2714 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 }
2716 return 1;
2717}
2718
2719static int
2720unaryop(unaryop_ty op)
2721{
2722 switch (op) {
2723 case Invert:
2724 return UNARY_INVERT;
2725 case Not:
2726 return UNARY_NOT;
2727 case UAdd:
2728 return UNARY_POSITIVE;
2729 case USub:
2730 return UNARY_NEGATIVE;
2731 }
2732 return 0;
2733}
2734
2735static int
2736binop(struct compiler *c, operator_ty op)
2737{
2738 switch (op) {
2739 case Add:
2740 return BINARY_ADD;
2741 case Sub:
2742 return BINARY_SUBTRACT;
2743 case Mult:
2744 return BINARY_MULTIPLY;
2745 case Div:
2746 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2747 return BINARY_TRUE_DIVIDE;
2748 else
2749 return BINARY_DIVIDE;
2750 case Mod:
2751 return BINARY_MODULO;
2752 case Pow:
2753 return BINARY_POWER;
2754 case LShift:
2755 return BINARY_LSHIFT;
2756 case RShift:
2757 return BINARY_RSHIFT;
2758 case BitOr:
2759 return BINARY_OR;
2760 case BitXor:
2761 return BINARY_XOR;
2762 case BitAnd:
2763 return BINARY_AND;
2764 case FloorDiv:
2765 return BINARY_FLOOR_DIVIDE;
2766 }
2767 return 0;
2768}
2769
2770static int
2771cmpop(cmpop_ty op)
2772{
2773 switch (op) {
2774 case Eq:
2775 return PyCmp_EQ;
2776 case NotEq:
2777 return PyCmp_NE;
2778 case Lt:
2779 return PyCmp_LT;
2780 case LtE:
2781 return PyCmp_LE;
2782 case Gt:
2783 return PyCmp_GT;
2784 case GtE:
2785 return PyCmp_GE;
2786 case Is:
2787 return PyCmp_IS;
2788 case IsNot:
2789 return PyCmp_IS_NOT;
2790 case In:
2791 return PyCmp_IN;
2792 case NotIn:
2793 return PyCmp_NOT_IN;
2794 }
2795 return PyCmp_BAD;
2796}
2797
2798static int
2799inplace_binop(struct compiler *c, operator_ty op)
2800{
2801 switch (op) {
2802 case Add:
2803 return INPLACE_ADD;
2804 case Sub:
2805 return INPLACE_SUBTRACT;
2806 case Mult:
2807 return INPLACE_MULTIPLY;
2808 case Div:
2809 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2810 return INPLACE_TRUE_DIVIDE;
2811 else
2812 return INPLACE_DIVIDE;
2813 case Mod:
2814 return INPLACE_MODULO;
2815 case Pow:
2816 return INPLACE_POWER;
2817 case LShift:
2818 return INPLACE_LSHIFT;
2819 case RShift:
2820 return INPLACE_RSHIFT;
2821 case BitOr:
2822 return INPLACE_OR;
2823 case BitXor:
2824 return INPLACE_XOR;
2825 case BitAnd:
2826 return INPLACE_AND;
2827 case FloorDiv:
2828 return INPLACE_FLOOR_DIVIDE;
2829 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002830 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002831 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832 return 0;
2833}
2834
2835static int
2836compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2837{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002838 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2840
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002841 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002842 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843 /* XXX AugStore isn't used anywhere! */
2844
2845 /* First check for assignment to __debug__. Param? */
2846 if ((ctx == Store || ctx == AugStore || ctx == Del)
2847 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2848 return compiler_error(c, "can not assign to __debug__");
2849 }
2850
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002851 mangled = _Py_Mangle(c->u->u_private, name);
2852 if (!mangled)
2853 return 0;
2854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855 op = 0;
2856 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002857 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858 switch (scope) {
2859 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002860 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002861 optype = OP_DEREF;
2862 break;
2863 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002864 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002865 optype = OP_DEREF;
2866 break;
2867 case LOCAL:
2868 if (c->u->u_ste->ste_type == FunctionBlock)
2869 optype = OP_FAST;
2870 break;
2871 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002872 if (c->u->u_ste->ste_type == FunctionBlock &&
2873 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874 optype = OP_GLOBAL;
2875 break;
2876 case GLOBAL_EXPLICIT:
2877 optype = OP_GLOBAL;
2878 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002879 default:
2880 /* scope can be 0 */
2881 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882 }
2883
2884 /* XXX Leave assert here, but handle __doc__ and the like better */
2885 assert(scope || PyString_AS_STRING(name)[0] == '_');
2886
2887 switch (optype) {
2888 case OP_DEREF:
2889 switch (ctx) {
2890 case Load: op = LOAD_DEREF; break;
2891 case Store: op = STORE_DEREF; break;
2892 case AugLoad:
2893 case AugStore:
2894 break;
2895 case Del:
2896 PyErr_Format(PyExc_SyntaxError,
2897 "can not delete variable '%s' referenced "
2898 "in nested scope",
2899 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002900 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002901 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002902 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002903 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002904 PyErr_SetString(PyExc_SystemError,
2905 "param invalid for deref variable");
2906 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002907 }
2908 break;
2909 case OP_FAST:
2910 switch (ctx) {
2911 case Load: op = LOAD_FAST; break;
2912 case Store: op = STORE_FAST; break;
2913 case Del: op = DELETE_FAST; break;
2914 case AugLoad:
2915 case AugStore:
2916 break;
2917 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002918 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002919 PyErr_SetString(PyExc_SystemError,
2920 "param invalid for local variable");
2921 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002923 ADDOP_O(c, op, mangled, varnames);
2924 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 return 1;
2926 case OP_GLOBAL:
2927 switch (ctx) {
2928 case Load: op = LOAD_GLOBAL; break;
2929 case Store: op = STORE_GLOBAL; break;
2930 case Del: op = DELETE_GLOBAL; break;
2931 case AugLoad:
2932 case AugStore:
2933 break;
2934 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002935 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002936 PyErr_SetString(PyExc_SystemError,
2937 "param invalid for global variable");
2938 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 }
2940 break;
2941 case OP_NAME:
2942 switch (ctx) {
2943 case Load: op = LOAD_NAME; break;
2944 case Store: op = STORE_NAME; break;
2945 case Del: op = DELETE_NAME; break;
2946 case AugLoad:
2947 case AugStore:
2948 break;
2949 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002950 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00002951 PyErr_SetString(PyExc_SystemError,
2952 "param invalid for name variable");
2953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002954 }
2955 break;
2956 }
2957
2958 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002959 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00002960 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002961 if (arg < 0)
2962 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002963 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964}
2965
2966static int
2967compiler_boolop(struct compiler *c, expr_ty e)
2968{
2969 basicblock *end;
2970 int jumpi, i, n;
2971 asdl_seq *s;
2972
2973 assert(e->kind == BoolOp_kind);
2974 if (e->v.BoolOp.op == And)
2975 jumpi = JUMP_IF_FALSE;
2976 else
2977 jumpi = JUMP_IF_TRUE;
2978 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00002979 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 return 0;
2981 s = e->v.BoolOp.values;
2982 n = asdl_seq_LEN(s) - 1;
2983 for (i = 0; i < n; ++i) {
2984 VISIT(c, expr, asdl_seq_GET(s, i));
2985 ADDOP_JREL(c, jumpi, end);
2986 ADDOP(c, POP_TOP)
2987 }
2988 VISIT(c, expr, asdl_seq_GET(s, n));
2989 compiler_use_next_block(c, end);
2990 return 1;
2991}
2992
2993static int
2994compiler_list(struct compiler *c, expr_ty e)
2995{
2996 int n = asdl_seq_LEN(e->v.List.elts);
2997 if (e->v.List.ctx == Store) {
2998 ADDOP_I(c, UNPACK_SEQUENCE, n);
2999 }
3000 VISIT_SEQ(c, expr, e->v.List.elts);
3001 if (e->v.List.ctx == Load) {
3002 ADDOP_I(c, BUILD_LIST, n);
3003 }
3004 return 1;
3005}
3006
3007static int
3008compiler_tuple(struct compiler *c, expr_ty e)
3009{
3010 int n = asdl_seq_LEN(e->v.Tuple.elts);
3011 if (e->v.Tuple.ctx == Store) {
3012 ADDOP_I(c, UNPACK_SEQUENCE, n);
3013 }
3014 VISIT_SEQ(c, expr, e->v.Tuple.elts);
3015 if (e->v.Tuple.ctx == Load) {
3016 ADDOP_I(c, BUILD_TUPLE, n);
3017 }
3018 return 1;
3019}
3020
3021static int
3022compiler_compare(struct compiler *c, expr_ty e)
3023{
3024 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003025 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003026
3027 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3028 VISIT(c, expr, e->v.Compare.left);
3029 n = asdl_seq_LEN(e->v.Compare.ops);
3030 assert(n > 0);
3031 if (n > 1) {
3032 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003033 if (cleanup == NULL)
3034 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003035 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, 0));
3036 }
3037 for (i = 1; i < n; i++) {
3038 ADDOP(c, DUP_TOP);
3039 ADDOP(c, ROT_THREE);
3040 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3041 ADDOP_I(c, COMPARE_OP,
3042 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i - 1)));
3043 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3044 NEXT_BLOCK(c);
3045 ADDOP(c, POP_TOP);
3046 if (i < (n - 1))
3047 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, i));
3048 }
3049 VISIT(c, expr, asdl_seq_GET(e->v.Compare.comparators, n - 1));
3050 ADDOP_I(c, COMPARE_OP,
3051 /* XXX We're casting a void* to cmpop_ty in the next stmt. */
3052 cmpop((cmpop_ty)asdl_seq_GET(e->v.Compare.ops, n - 1)));
3053 if (n > 1) {
3054 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003055 if (end == NULL)
3056 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 ADDOP_JREL(c, JUMP_FORWARD, end);
3058 compiler_use_next_block(c, cleanup);
3059 ADDOP(c, ROT_TWO);
3060 ADDOP(c, POP_TOP);
3061 compiler_use_next_block(c, end);
3062 }
3063 return 1;
3064}
3065
3066static int
3067compiler_call(struct compiler *c, expr_ty e)
3068{
3069 int n, code = 0;
3070
3071 VISIT(c, expr, e->v.Call.func);
3072 n = asdl_seq_LEN(e->v.Call.args);
3073 VISIT_SEQ(c, expr, e->v.Call.args);
3074 if (e->v.Call.keywords) {
3075 VISIT_SEQ(c, keyword, e->v.Call.keywords);
3076 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3077 }
3078 if (e->v.Call.starargs) {
3079 VISIT(c, expr, e->v.Call.starargs);
3080 code |= 1;
3081 }
3082 if (e->v.Call.kwargs) {
3083 VISIT(c, expr, e->v.Call.kwargs);
3084 code |= 2;
3085 }
3086 switch (code) {
3087 case 0:
3088 ADDOP_I(c, CALL_FUNCTION, n);
3089 break;
3090 case 1:
3091 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3092 break;
3093 case 2:
3094 ADDOP_I(c, CALL_FUNCTION_KW, n);
3095 break;
3096 case 3:
3097 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3098 break;
3099 }
3100 return 1;
3101}
3102
3103static int
3104compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003105 asdl_seq *generators, int gen_index,
3106 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003107{
3108 /* generate code for the iterator, then each of the ifs,
3109 and then write to the element */
3110
3111 comprehension_ty l;
3112 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003113 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003114
3115 start = compiler_new_block(c);
3116 skip = compiler_new_block(c);
3117 if_cleanup = compiler_new_block(c);
3118 anchor = compiler_new_block(c);
3119
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003120 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3121 anchor == NULL)
3122 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003123
3124 l = asdl_seq_GET(generators, gen_index);
3125 VISIT(c, expr, l->iter);
3126 ADDOP(c, GET_ITER);
3127 compiler_use_next_block(c, start);
3128 ADDOP_JREL(c, FOR_ITER, anchor);
3129 NEXT_BLOCK(c);
3130 VISIT(c, expr, l->target);
3131
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003132 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003133 n = asdl_seq_LEN(l->ifs);
3134 for (i = 0; i < n; i++) {
3135 expr_ty e = asdl_seq_GET(l->ifs, i);
3136 VISIT(c, expr, e);
3137 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3138 NEXT_BLOCK(c);
3139 ADDOP(c, POP_TOP);
3140 }
3141
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003142 if (++gen_index < asdl_seq_LEN(generators))
3143 if (!compiler_listcomp_generator(c, tmpname,
3144 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003146
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003147 /* only append after the last for generator */
3148 if (gen_index >= asdl_seq_LEN(generators)) {
3149 if (!compiler_nameop(c, tmpname, Load))
3150 return 0;
3151 VISIT(c, expr, elt);
3152 ADDOP_I(c, CALL_FUNCTION, 1);
3153 ADDOP(c, POP_TOP);
3154
3155 compiler_use_next_block(c, skip);
3156 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157 for (i = 0; i < n; i++) {
3158 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003159 if (i == 0)
3160 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161 ADDOP(c, POP_TOP);
3162 }
3163 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3164 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003165 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003166 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003167 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003168 return 0;
3169
3170 return 1;
3171}
3172
3173static int
3174compiler_listcomp(struct compiler *c, expr_ty e)
3175{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003177 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003178 static identifier append;
3179 asdl_seq *generators = e->v.ListComp.generators;
3180
3181 assert(e->kind == ListComp_kind);
3182 if (!append) {
3183 append = PyString_InternFromString("append");
3184 if (!append)
3185 return 0;
3186 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003187 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188 if (!tmp)
3189 return 0;
3190 ADDOP_I(c, BUILD_LIST, 0);
3191 ADDOP(c, DUP_TOP);
3192 ADDOP_O(c, LOAD_ATTR, append, names);
3193 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003194 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3195 e->v.ListComp.elt);
3196 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197 return rc;
3198}
3199
3200static int
3201compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003202 asdl_seq *generators, int gen_index,
3203 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003204{
3205 /* generate code for the iterator, then each of the ifs,
3206 and then write to the element */
3207
3208 comprehension_ty ge;
3209 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003210 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003211
3212 start = compiler_new_block(c);
3213 skip = compiler_new_block(c);
3214 if_cleanup = compiler_new_block(c);
3215 anchor = compiler_new_block(c);
3216 end = compiler_new_block(c);
3217
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003218 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003219 anchor == NULL || end == NULL)
3220 return 0;
3221
3222 ge = asdl_seq_GET(generators, gen_index);
3223 ADDOP_JREL(c, SETUP_LOOP, end);
3224 if (!compiler_push_fblock(c, LOOP, start))
3225 return 0;
3226
3227 if (gen_index == 0) {
3228 /* Receive outermost iter as an implicit argument */
3229 c->u->u_argcount = 1;
3230 ADDOP_I(c, LOAD_FAST, 0);
3231 }
3232 else {
3233 /* Sub-iter - calculate on the fly */
3234 VISIT(c, expr, ge->iter);
3235 ADDOP(c, GET_ITER);
3236 }
3237 compiler_use_next_block(c, start);
3238 ADDOP_JREL(c, FOR_ITER, anchor);
3239 NEXT_BLOCK(c);
3240 VISIT(c, expr, ge->target);
3241
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003242 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003243 n = asdl_seq_LEN(ge->ifs);
3244 for (i = 0; i < n; i++) {
3245 expr_ty e = asdl_seq_GET(ge->ifs, i);
3246 VISIT(c, expr, e);
3247 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3248 NEXT_BLOCK(c);
3249 ADDOP(c, POP_TOP);
3250 }
3251
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003252 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003253 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3254 return 0;
3255
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003256 /* only append after the last 'for' generator */
3257 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258 VISIT(c, expr, elt);
3259 ADDOP(c, YIELD_VALUE);
3260 ADDOP(c, POP_TOP);
3261
3262 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003263 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264 for (i = 0; i < n; i++) {
3265 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003266 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267 compiler_use_next_block(c, if_cleanup);
3268
3269 ADDOP(c, POP_TOP);
3270 }
3271 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3272 compiler_use_next_block(c, anchor);
3273 ADDOP(c, POP_BLOCK);
3274 compiler_pop_fblock(c, LOOP, start);
3275 compiler_use_next_block(c, end);
3276
3277 return 1;
3278}
3279
3280static int
3281compiler_genexp(struct compiler *c, expr_ty e)
3282{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003283 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284 PyCodeObject *co;
3285 expr_ty outermost_iter = ((comprehension_ty)
3286 (asdl_seq_GET(e->v.GeneratorExp.generators,
3287 0)))->iter;
3288
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003289 if (!name) {
3290 name = PyString_FromString("<genexpr>");
3291 if (!name)
3292 return 0;
3293 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294
3295 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3296 return 0;
3297 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3298 e->v.GeneratorExp.elt);
3299 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003300 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 if (co == NULL)
3302 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003304 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003305 Py_DECREF(co);
3306
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307 VISIT(c, expr, outermost_iter);
3308 ADDOP(c, GET_ITER);
3309 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310
3311 return 1;
3312}
3313
3314static int
3315compiler_visit_keyword(struct compiler *c, keyword_ty k)
3316{
3317 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3318 VISIT(c, expr, k->value);
3319 return 1;
3320}
3321
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003322/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 whether they are true or false.
3324
3325 Return values: 1 for true, 0 for false, -1 for non-constant.
3326 */
3327
3328static int
3329expr_constant(expr_ty e)
3330{
3331 switch (e->kind) {
3332 case Num_kind:
3333 return PyObject_IsTrue(e->v.Num.n);
3334 case Str_kind:
3335 return PyObject_IsTrue(e->v.Str.s);
3336 default:
3337 return -1;
3338 }
3339}
3340
Guido van Rossumc2e20742006-02-27 22:32:47 +00003341/*
3342 Implements the with statement from PEP 343.
3343
3344 The semantics outlined in that PEP are as follows:
3345
3346 with EXPR as VAR:
3347 BLOCK
3348
3349 It is implemented roughly as:
3350
3351 context = (EXPR).__context__()
3352 exit = context.__exit__ # not calling it
3353 value = context.__enter__()
3354 try:
3355 VAR = value # if VAR present in the syntax
3356 BLOCK
3357 finally:
3358 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003359 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003360 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003361 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003362 exit(*exc)
3363 */
3364static int
3365compiler_with(struct compiler *c, stmt_ty s)
3366{
3367 static identifier context_attr, enter_attr, exit_attr;
3368 basicblock *block, *finally;
3369 identifier tmpexit, tmpvalue = NULL;
3370
3371 assert(s->kind == With_kind);
3372
3373 if (!context_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003374 context_attr = PyString_InternFromString("__context__");
3375 if (!context_attr)
3376 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003377 }
3378 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003379 enter_attr = PyString_InternFromString("__enter__");
3380 if (!enter_attr)
3381 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003382 }
3383 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003384 exit_attr = PyString_InternFromString("__exit__");
3385 if (!exit_attr)
3386 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003387 }
3388
3389 block = compiler_new_block(c);
3390 finally = compiler_new_block(c);
3391 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003392 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003393
3394 /* Create a temporary variable to hold context.__exit__ */
3395 tmpexit = compiler_new_tmpname(c);
3396 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003397 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003398 PyArena_AddPyObject(c->c_arena, tmpexit);
3399
3400 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003401 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003402 We need to do this rather than preserving it on the stack
3403 because SETUP_FINALLY remembers the stack level.
3404 We need to do the assignment *inside* the try/finally
3405 so that context.__exit__() is called when the assignment
3406 fails. But we need to call context.__enter__() *before*
3407 the try/finally so that if it fails we won't call
3408 context.__exit__().
3409 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003410 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003411 if (tmpvalue == NULL)
3412 return 0;
3413 PyArena_AddPyObject(c->c_arena, tmpvalue);
3414 }
3415
3416 /* Evaluate (EXPR).__context__() */
3417 VISIT(c, expr, s->v.With.context_expr);
3418 ADDOP_O(c, LOAD_ATTR, context_attr, names);
3419 ADDOP_I(c, CALL_FUNCTION, 0);
3420
3421 /* Squirrel away context.__exit__ */
3422 ADDOP(c, DUP_TOP);
3423 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3424 if (!compiler_nameop(c, tmpexit, Store))
3425 return 0;
3426
3427 /* Call context.__enter__() */
3428 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3429 ADDOP_I(c, CALL_FUNCTION, 0);
3430
3431 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003432 /* Store it in tmpvalue */
3433 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003434 return 0;
3435 }
3436 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003437 /* Discard result from context.__enter__() */
3438 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003439 }
3440
3441 /* Start the try block */
3442 ADDOP_JREL(c, SETUP_FINALLY, finally);
3443
3444 compiler_use_next_block(c, block);
3445 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003446 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003447 }
3448
3449 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003450 /* Bind saved result of context.__enter__() to VAR */
3451 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003452 !compiler_nameop(c, tmpvalue, Del))
3453 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003454 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003455 }
3456
3457 /* BLOCK code */
3458 VISIT_SEQ(c, stmt, s->v.With.body);
3459
3460 /* End of try block; start the finally block */
3461 ADDOP(c, POP_BLOCK);
3462 compiler_pop_fblock(c, FINALLY_TRY, block);
3463
3464 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3465 compiler_use_next_block(c, finally);
3466 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003467 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003468
3469 /* Finally block starts; push tmpexit and issue our magic opcode. */
3470 if (!compiler_nameop(c, tmpexit, Load) ||
3471 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003472 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003473 ADDOP(c, WITH_CLEANUP);
3474 ADDOP_I(c, CALL_FUNCTION, 3);
3475 ADDOP(c, POP_TOP);
3476
3477 /* Finally block ends. */
3478 ADDOP(c, END_FINALLY);
3479 compiler_pop_fblock(c, FINALLY_END, finally);
3480 return 1;
3481}
3482
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483static int
3484compiler_visit_expr(struct compiler *c, expr_ty e)
3485{
3486 int i, n;
3487
3488 if (e->lineno > c->u->u_lineno) {
3489 c->u->u_lineno = e->lineno;
3490 c->u->u_lineno_set = false;
3491 }
3492 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003493 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003495 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003496 VISIT(c, expr, e->v.BinOp.left);
3497 VISIT(c, expr, e->v.BinOp.right);
3498 ADDOP(c, binop(c, e->v.BinOp.op));
3499 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003500 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003501 VISIT(c, expr, e->v.UnaryOp.operand);
3502 ADDOP(c, unaryop(e->v.UnaryOp.op));
3503 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003504 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003505 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003506 case IfExp_kind:
3507 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003508 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003509 /* XXX get rid of arg? */
3510 ADDOP_I(c, BUILD_MAP, 0);
3511 n = asdl_seq_LEN(e->v.Dict.values);
3512 /* We must arrange things just right for STORE_SUBSCR.
3513 It wants the stack to look like (value) (dict) (key) */
3514 for (i = 0; i < n; i++) {
3515 ADDOP(c, DUP_TOP);
3516 VISIT(c, expr, asdl_seq_GET(e->v.Dict.values, i));
3517 ADDOP(c, ROT_TWO);
3518 VISIT(c, expr, asdl_seq_GET(e->v.Dict.keys, i));
3519 ADDOP(c, STORE_SUBSCR);
3520 }
3521 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003522 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003524 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525 return compiler_genexp(c, e);
3526 case Yield_kind:
3527 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003528 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003529 /*
3530 for (i = 0; i < c->u->u_nfblocks; i++) {
3531 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3532 return compiler_error(
3533 c, "'yield' not allowed in a 'try' "
3534 "block with a 'finally' clause");
3535 }
3536 */
3537 if (e->v.Yield.value) {
3538 VISIT(c, expr, e->v.Yield.value);
3539 }
3540 else {
3541 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3542 }
3543 ADDOP(c, YIELD_VALUE);
3544 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003545 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003546 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003547 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003548 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003549 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003550 VISIT(c, expr, e->v.Repr.value);
3551 ADDOP(c, UNARY_CONVERT);
3552 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003553 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3555 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003556 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003557 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3558 break;
3559 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003560 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003561 if (e->v.Attribute.ctx != AugStore)
3562 VISIT(c, expr, e->v.Attribute.value);
3563 switch (e->v.Attribute.ctx) {
3564 case AugLoad:
3565 ADDOP(c, DUP_TOP);
3566 /* Fall through to load */
3567 case Load:
3568 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3569 break;
3570 case AugStore:
3571 ADDOP(c, ROT_TWO);
3572 /* Fall through to save */
3573 case Store:
3574 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3575 break;
3576 case Del:
3577 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3578 break;
3579 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003580 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003581 PyErr_SetString(PyExc_SystemError,
3582 "param invalid in attribute expression");
3583 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584 }
3585 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003586 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587 switch (e->v.Subscript.ctx) {
3588 case AugLoad:
3589 VISIT(c, expr, e->v.Subscript.value);
3590 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3591 break;
3592 case Load:
3593 VISIT(c, expr, e->v.Subscript.value);
3594 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3595 break;
3596 case AugStore:
3597 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3598 break;
3599 case Store:
3600 VISIT(c, expr, e->v.Subscript.value);
3601 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3602 break;
3603 case Del:
3604 VISIT(c, expr, e->v.Subscript.value);
3605 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3606 break;
3607 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003608 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003609 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003610 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003611 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003612 }
3613 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003614 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003615 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3616 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003617 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003618 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003619 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620 return compiler_tuple(c, e);
3621 }
3622 return 1;
3623}
3624
3625static int
3626compiler_augassign(struct compiler *c, stmt_ty s)
3627{
3628 expr_ty e = s->v.AugAssign.target;
3629 expr_ty auge;
3630
3631 assert(s->kind == AugAssign_kind);
3632
3633 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003634 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003636 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003637 if (auge == NULL)
3638 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639 VISIT(c, expr, auge);
3640 VISIT(c, expr, s->v.AugAssign.value);
3641 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3642 auge->v.Attribute.ctx = AugStore;
3643 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003644 break;
3645 case Subscript_kind:
3646 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003647 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003648 if (auge == NULL)
3649 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003650 VISIT(c, expr, auge);
3651 VISIT(c, expr, s->v.AugAssign.value);
3652 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003653 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003655 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003656 case Name_kind:
3657 VISIT(c, expr, s->v.AugAssign.target);
3658 VISIT(c, expr, s->v.AugAssign.value);
3659 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3660 return compiler_nameop(c, e->v.Name.id, Store);
3661 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003662 PyErr_Format(PyExc_SystemError,
3663 "invalid node type (%d) for augmented assignment",
3664 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003665 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003666 }
3667 return 1;
3668}
3669
3670static int
3671compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3672{
3673 struct fblockinfo *f;
3674 if (c->u->u_nfblocks >= CO_MAXBLOCKS)
3675 return 0;
3676 f = &c->u->u_fblock[c->u->u_nfblocks++];
3677 f->fb_type = t;
3678 f->fb_block = b;
3679 return 1;
3680}
3681
3682static void
3683compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3684{
3685 struct compiler_unit *u = c->u;
3686 assert(u->u_nfblocks > 0);
3687 u->u_nfblocks--;
3688 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3689 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3690}
3691
3692/* Raises a SyntaxError and returns 0.
3693 If something goes wrong, a different exception may be raised.
3694*/
3695
3696static int
3697compiler_error(struct compiler *c, const char *errstr)
3698{
3699 PyObject *loc;
3700 PyObject *u = NULL, *v = NULL;
3701
3702 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3703 if (!loc) {
3704 Py_INCREF(Py_None);
3705 loc = Py_None;
3706 }
3707 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3708 Py_None, loc);
3709 if (!u)
3710 goto exit;
3711 v = Py_BuildValue("(zO)", errstr, u);
3712 if (!v)
3713 goto exit;
3714 PyErr_SetObject(PyExc_SyntaxError, v);
3715 exit:
3716 Py_DECREF(loc);
3717 Py_XDECREF(u);
3718 Py_XDECREF(v);
3719 return 0;
3720}
3721
3722static int
3723compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003724 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003726 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003728 /* XXX this code is duplicated */
3729 switch (ctx) {
3730 case AugLoad: /* fall through to Load */
3731 case Load: op = BINARY_SUBSCR; break;
3732 case AugStore:/* fall through to Store */
3733 case Store: op = STORE_SUBSCR; break;
3734 case Del: op = DELETE_SUBSCR; break;
3735 case Param:
3736 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003737 "invalid %s kind %d in subscript\n",
3738 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003739 return 0;
3740 }
3741 if (ctx == AugLoad) {
3742 ADDOP_I(c, DUP_TOPX, 2);
3743 }
3744 else if (ctx == AugStore) {
3745 ADDOP(c, ROT_THREE);
3746 }
3747 ADDOP(c, op);
3748 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003749}
3750
3751static int
3752compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3753{
3754 int n = 2;
3755 assert(s->kind == Slice_kind);
3756
3757 /* only handles the cases where BUILD_SLICE is emitted */
3758 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003759 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003760 }
3761 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003762 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003764
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003766 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003767 }
3768 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003769 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770 }
3771
3772 if (s->v.Slice.step) {
3773 n++;
3774 VISIT(c, expr, s->v.Slice.step);
3775 }
3776 ADDOP_I(c, BUILD_SLICE, n);
3777 return 1;
3778}
3779
3780static int
3781compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3782{
3783 int op = 0, slice_offset = 0, stack_count = 0;
3784
3785 assert(s->v.Slice.step == NULL);
3786 if (s->v.Slice.lower) {
3787 slice_offset++;
3788 stack_count++;
3789 if (ctx != AugStore)
3790 VISIT(c, expr, s->v.Slice.lower);
3791 }
3792 if (s->v.Slice.upper) {
3793 slice_offset += 2;
3794 stack_count++;
3795 if (ctx != AugStore)
3796 VISIT(c, expr, s->v.Slice.upper);
3797 }
3798
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003799 if (ctx == AugLoad) {
3800 switch (stack_count) {
3801 case 0: ADDOP(c, DUP_TOP); break;
3802 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3803 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3804 }
3805 }
3806 else if (ctx == AugStore) {
3807 switch (stack_count) {
3808 case 0: ADDOP(c, ROT_TWO); break;
3809 case 1: ADDOP(c, ROT_THREE); break;
3810 case 2: ADDOP(c, ROT_FOUR); break;
3811 }
3812 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813
3814 switch (ctx) {
3815 case AugLoad: /* fall through to Load */
3816 case Load: op = SLICE; break;
3817 case AugStore:/* fall through to Store */
3818 case Store: op = STORE_SLICE; break;
3819 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003820 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003821 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003822 PyErr_SetString(PyExc_SystemError,
3823 "param invalid in simple slice");
3824 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003825 }
3826
3827 ADDOP(c, op + slice_offset);
3828 return 1;
3829}
3830
3831static int
3832compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3833 expr_context_ty ctx)
3834{
3835 switch (s->kind) {
3836 case Ellipsis_kind:
3837 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3838 break;
3839 case Slice_kind:
3840 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003841 case Index_kind:
3842 VISIT(c, expr, s->v.Index.value);
3843 break;
3844 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003845 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003846 PyErr_SetString(PyExc_SystemError,
3847 "extended slice invalid in nested slice");
3848 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003849 }
3850 return 1;
3851}
3852
3853
3854static int
3855compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3856{
3857 switch (s->kind) {
3858 case Ellipsis_kind:
3859 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3860 break;
3861 case Slice_kind:
3862 if (!s->v.Slice.step)
3863 return compiler_simple_slice(c, s, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003864 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003865 return 0;
3866 if (ctx == AugLoad) {
3867 ADDOP_I(c, DUP_TOPX, 2);
3868 }
3869 else if (ctx == AugStore) {
3870 ADDOP(c, ROT_THREE);
3871 }
3872 return compiler_handle_subscr(c, "slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003873 case ExtSlice_kind: {
3874 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
3875 for (i = 0; i < n; i++) {
3876 slice_ty sub = asdl_seq_GET(s->v.ExtSlice.dims, i);
3877 if (!compiler_visit_nested_slice(c, sub, ctx))
3878 return 0;
3879 }
3880 ADDOP_I(c, BUILD_TUPLE, n);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003881 return compiler_handle_subscr(c, "extended slice", ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003882 }
3883 case Index_kind:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003884 if (ctx != AugStore)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003885 VISIT(c, expr, s->v.Index.value);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003886 return compiler_handle_subscr(c, "index", ctx);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003887 default:
3888 PyErr_Format(PyExc_SystemError,
3889 "invalid slice %d", s->kind);
3890 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 }
3892 return 1;
3893}
3894
3895/* do depth-first search of basic block graph, starting with block.
3896 post records the block indices in post-order.
3897
3898 XXX must handle implicit jumps from one block to next
3899*/
3900
3901static void
3902dfs(struct compiler *c, basicblock *b, struct assembler *a)
3903{
3904 int i;
3905 struct instr *instr = NULL;
3906
3907 if (b->b_seen)
3908 return;
3909 b->b_seen = 1;
3910 if (b->b_next != NULL)
3911 dfs(c, b->b_next, a);
3912 for (i = 0; i < b->b_iused; i++) {
3913 instr = &b->b_instr[i];
3914 if (instr->i_jrel || instr->i_jabs)
3915 dfs(c, instr->i_target, a);
3916 }
3917 a->a_postorder[a->a_nblocks++] = b;
3918}
3919
Neal Norwitz2744c6c2005-11-13 01:08:38 +00003920static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003921stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
3922{
3923 int i;
3924 struct instr *instr;
3925 if (b->b_seen || b->b_startdepth >= depth)
3926 return maxdepth;
3927 b->b_seen = 1;
3928 b->b_startdepth = depth;
3929 for (i = 0; i < b->b_iused; i++) {
3930 instr = &b->b_instr[i];
3931 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
3932 if (depth > maxdepth)
3933 maxdepth = depth;
3934 assert(depth >= 0); /* invalid code or bug in stackdepth() */
3935 if (instr->i_jrel || instr->i_jabs) {
3936 maxdepth = stackdepth_walk(c, instr->i_target,
3937 depth, maxdepth);
3938 if (instr->i_opcode == JUMP_ABSOLUTE ||
3939 instr->i_opcode == JUMP_FORWARD) {
3940 goto out; /* remaining code is dead */
3941 }
3942 }
3943 }
3944 if (b->b_next)
3945 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
3946out:
3947 b->b_seen = 0;
3948 return maxdepth;
3949}
3950
3951/* Find the flow path that needs the largest stack. We assume that
3952 * cycles in the flow graph have no net effect on the stack depth.
3953 */
3954static int
3955stackdepth(struct compiler *c)
3956{
3957 basicblock *b, *entryblock;
3958 entryblock = NULL;
3959 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
3960 b->b_seen = 0;
3961 b->b_startdepth = INT_MIN;
3962 entryblock = b;
3963 }
3964 return stackdepth_walk(c, entryblock, 0, 0);
3965}
3966
3967static int
3968assemble_init(struct assembler *a, int nblocks, int firstlineno)
3969{
3970 memset(a, 0, sizeof(struct assembler));
3971 a->a_lineno = firstlineno;
3972 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
3973 if (!a->a_bytecode)
3974 return 0;
3975 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
3976 if (!a->a_lnotab)
3977 return 0;
3978 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003979 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00003980 if (!a->a_postorder) {
3981 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003982 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00003983 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003984 return 1;
3985}
3986
3987static void
3988assemble_free(struct assembler *a)
3989{
3990 Py_XDECREF(a->a_bytecode);
3991 Py_XDECREF(a->a_lnotab);
3992 if (a->a_postorder)
3993 PyObject_Free(a->a_postorder);
3994}
3995
3996/* Return the size of a basic block in bytes. */
3997
3998static int
3999instrsize(struct instr *instr)
4000{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004001 if (!instr->i_hasarg)
4002 return 1;
4003 if (instr->i_oparg > 0xffff)
4004 return 6;
4005 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004006}
4007
4008static int
4009blocksize(basicblock *b)
4010{
4011 int i;
4012 int size = 0;
4013
4014 for (i = 0; i < b->b_iused; i++)
4015 size += instrsize(&b->b_instr[i]);
4016 return size;
4017}
4018
4019/* All about a_lnotab.
4020
4021c_lnotab is an array of unsigned bytes disguised as a Python string.
4022It is used to map bytecode offsets to source code line #s (when needed
4023for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004024
Tim Peters2a7f3842001-06-09 09:26:21 +00004025The array is conceptually a list of
4026 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004027pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004028
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004029 byte code offset source code line number
4030 0 1
4031 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004032 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004033 350 307
4034 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004035
4036The first trick is that these numbers aren't stored, only the increments
4037from one row to the next (this doesn't really work, but it's a start):
4038
4039 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4040
4041The second trick is that an unsigned byte can't hold negative values, or
4042values larger than 255, so (a) there's a deep assumption that byte code
4043offsets and their corresponding line #s both increase monotonically, and (b)
4044if at least one column jumps by more than 255 from one row to the next, more
4045than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004046from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004047part. A user of c_lnotab desiring to find the source line number
4048corresponding to a bytecode address A should do something like this
4049
4050 lineno = addr = 0
4051 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004052 addr += addr_incr
4053 if addr > A:
4054 return lineno
4055 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004056
4057In order for this to work, when the addr field increments by more than 255,
4058the line # increment in each pair generated must be 0 until the remaining addr
4059increment is < 256. So, in the example above, com_set_lineno should not (as
4060was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004061255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004062*/
4063
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004064static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004065assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004066{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004067 int d_bytecode, d_lineno;
4068 int len;
4069 char *lnotab;
4070
4071 d_bytecode = a->a_offset - a->a_lineno_off;
4072 d_lineno = i->i_lineno - a->a_lineno;
4073
4074 assert(d_bytecode >= 0);
4075 assert(d_lineno >= 0);
4076
4077 if (d_lineno == 0)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004078 return 1;
Guido van Rossum4bad92c1991-07-27 21:34:52 +00004079
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004080 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004081 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004082 nbytes = a->a_lnotab_off + 2 * ncodes;
4083 len = PyString_GET_SIZE(a->a_lnotab);
4084 if (nbytes >= len) {
4085 if (len * 2 < nbytes)
4086 len = nbytes;
Phillip J. Eby0d6615f2005-08-02 00:46:46 +00004087 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088 len *= 2;
4089 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4090 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004091 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004092 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004093 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004094 *lnotab++ = 255;
4095 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004096 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004097 d_bytecode -= ncodes * 255;
4098 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004099 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004100 assert(d_bytecode <= 255);
4101 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004102 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004103 nbytes = a->a_lnotab_off + 2 * ncodes;
4104 len = PyString_GET_SIZE(a->a_lnotab);
4105 if (nbytes >= len) {
4106 if (len * 2 < nbytes)
4107 len = nbytes;
Guido van Rossum635abd21997-01-06 22:56:52 +00004108 else
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004109 len *= 2;
4110 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4111 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004112 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004113 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
4114 *lnotab++ = 255;
4115 *lnotab++ = d_bytecode;
4116 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004117 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004118 *lnotab++ = 255;
4119 *lnotab++ = 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004120 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004121 d_lineno -= ncodes * 255;
4122 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004123 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004124
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004125 len = PyString_GET_SIZE(a->a_lnotab);
4126 if (a->a_lnotab_off + 2 >= len) {
4127 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004128 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004129 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004130 lnotab = PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004131
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132 a->a_lnotab_off += 2;
4133 if (d_bytecode) {
4134 *lnotab++ = d_bytecode;
4135 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004136 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004137 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004138 *lnotab++ = 0;
4139 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004140 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004141 a->a_lineno = i->i_lineno;
4142 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004143 return 1;
4144}
4145
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004146/* assemble_emit()
4147 Extend the bytecode with a new instruction.
4148 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004149*/
4150
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004151static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004152assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004153{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004154 int size, arg = 0, ext = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004155 int len = PyString_GET_SIZE(a->a_bytecode);
4156 char *code;
4157
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004158 size = instrsize(i);
4159 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004160 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004161 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004162 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004163 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004164 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004165 if (a->a_offset + size >= len) {
4166 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004167 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004168 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004169 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4170 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004171 if (size == 6) {
4172 assert(i->i_hasarg);
4173 *code++ = (char)EXTENDED_ARG;
4174 *code++ = ext & 0xff;
4175 *code++ = ext >> 8;
4176 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004177 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004178 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004179 if (i->i_hasarg) {
4180 assert(size == 3 || size == 6);
4181 *code++ = arg & 0xff;
4182 *code++ = arg >> 8;
4183 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004184 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004185}
4186
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004187static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004188assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004189{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004190 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004191 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004192 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004193
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004194 /* Compute the size of each block and fixup jump args.
4195 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004196start:
4197 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004198 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004199 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004200 bsize = blocksize(b);
4201 b->b_offset = totsize;
4202 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004203 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004204 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004205 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4206 bsize = b->b_offset;
4207 for (i = 0; i < b->b_iused; i++) {
4208 struct instr *instr = &b->b_instr[i];
4209 /* Relative jumps are computed relative to
4210 the instruction pointer after fetching
4211 the jump instruction.
4212 */
4213 bsize += instrsize(instr);
4214 if (instr->i_jabs)
4215 instr->i_oparg = instr->i_target->b_offset;
4216 else if (instr->i_jrel) {
4217 int delta = instr->i_target->b_offset - bsize;
4218 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004219 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004220 else
4221 continue;
4222 if (instr->i_oparg > 0xffff)
4223 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004224 }
4225 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004226
4227 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004228 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004229 with a better solution.
4230
4231 In the meantime, should the goto be dropped in favor
4232 of a loop?
4233
4234 The issue is that in the first loop blocksize() is called
4235 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004236 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004237 i_oparg is calculated in the second loop above.
4238
4239 So we loop until we stop seeing new EXTENDED_ARGs.
4240 The only EXTENDED_ARGs that could be popping up are
4241 ones in jump instructions. So this should converge
4242 fairly quickly.
4243 */
4244 if (last_extended_arg_count != extended_arg_count) {
4245 last_extended_arg_count = extended_arg_count;
4246 goto start;
4247 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004248}
4249
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004250static PyObject *
4251dict_keys_inorder(PyObject *dict, int offset)
4252{
4253 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004254 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004255
4256 tuple = PyTuple_New(size);
4257 if (tuple == NULL)
4258 return NULL;
4259 while (PyDict_Next(dict, &pos, &k, &v)) {
4260 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004261 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004262 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004263 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004264 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004265 PyTuple_SET_ITEM(tuple, i - offset, k);
4266 }
4267 return tuple;
4268}
4269
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004270static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004271compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004272{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004273 PySTEntryObject *ste = c->u->u_ste;
4274 int flags = 0, n;
4275 if (ste->ste_type != ModuleBlock)
4276 flags |= CO_NEWLOCALS;
4277 if (ste->ste_type == FunctionBlock) {
4278 if (!ste->ste_unoptimized)
4279 flags |= CO_OPTIMIZED;
4280 if (ste->ste_nested)
4281 flags |= CO_NESTED;
4282 if (ste->ste_generator)
4283 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004285 if (ste->ste_varargs)
4286 flags |= CO_VARARGS;
4287 if (ste->ste_varkeywords)
4288 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004289 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004290 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004291
4292 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004293 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004294
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004295 n = PyDict_Size(c->u->u_freevars);
4296 if (n < 0)
4297 return -1;
4298 if (n == 0) {
4299 n = PyDict_Size(c->u->u_cellvars);
4300 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004301 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004302 if (n == 0) {
4303 flags |= CO_NOFREE;
4304 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004305 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004306
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004307 return flags;
4308}
4309
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310static PyCodeObject *
4311makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004312{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004313 PyObject *tmp;
4314 PyCodeObject *co = NULL;
4315 PyObject *consts = NULL;
4316 PyObject *names = NULL;
4317 PyObject *varnames = NULL;
4318 PyObject *filename = NULL;
4319 PyObject *name = NULL;
4320 PyObject *freevars = NULL;
4321 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004322 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004323 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 tmp = dict_keys_inorder(c->u->u_consts, 0);
4326 if (!tmp)
4327 goto error;
4328 consts = PySequence_List(tmp); /* optimize_code requires a list */
4329 Py_DECREF(tmp);
4330
4331 names = dict_keys_inorder(c->u->u_names, 0);
4332 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4333 if (!consts || !names || !varnames)
4334 goto error;
4335
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004336 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4337 if (!cellvars)
4338 goto error;
4339 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4340 if (!freevars)
4341 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004342 filename = PyString_FromString(c->c_filename);
4343 if (!filename)
4344 goto error;
4345
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004346 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347 flags = compute_code_flags(c);
4348 if (flags < 0)
4349 goto error;
4350
4351 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4352 if (!bytecode)
4353 goto error;
4354
4355 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4356 if (!tmp)
4357 goto error;
4358 Py_DECREF(consts);
4359 consts = tmp;
4360
4361 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4362 bytecode, consts, names, varnames,
4363 freevars, cellvars,
4364 filename, c->u->u_name,
4365 c->u->u_firstlineno,
4366 a->a_lnotab);
4367 error:
4368 Py_XDECREF(consts);
4369 Py_XDECREF(names);
4370 Py_XDECREF(varnames);
4371 Py_XDECREF(filename);
4372 Py_XDECREF(name);
4373 Py_XDECREF(freevars);
4374 Py_XDECREF(cellvars);
4375 Py_XDECREF(bytecode);
4376 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004377}
4378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004379static PyCodeObject *
4380assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004381{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382 basicblock *b, *entryblock;
4383 struct assembler a;
4384 int i, j, nblocks;
4385 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004386
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387 /* Make sure every block that falls off the end returns None.
4388 XXX NEXT_BLOCK() isn't quite right, because if the last
4389 block ends with a jump or return b_next shouldn't set.
4390 */
4391 if (!c->u->u_curblock->b_return) {
4392 NEXT_BLOCK(c);
4393 if (addNone)
4394 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4395 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004396 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398 nblocks = 0;
4399 entryblock = NULL;
4400 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4401 nblocks++;
4402 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004403 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004404
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004405 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4406 goto error;
4407 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004408
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004409 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004410 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004411
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004412 /* Emit code in reverse postorder from dfs. */
4413 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004414 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415 for (j = 0; j < b->b_iused; j++)
4416 if (!assemble_emit(&a, &b->b_instr[j]))
4417 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004418 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004419
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004420 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4421 goto error;
4422 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4423 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425 co = makecode(c, &a);
4426 error:
4427 assemble_free(&a);
4428 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004429}