blob: d40357c42979ca12429c207af4f80e9c97970ec6 [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_ {
Jeremy Hylton12603c42006-04-01 16:18:02 +000061 /* Each basicblock in a compilation unit is linked via b_list in the
62 reverse order that the block are allocated. b_list points to the next
63 block, not to be confused with b_next, which is next by control flow. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 struct basicblock_ *b_list;
65 /* number of instructions used */
66 int b_iused;
67 /* length of instruction array (b_instr) */
68 int b_ialloc;
69 /* pointer to an array of instructions, initially NULL */
70 struct instr *b_instr;
71 /* If b_next is non-NULL, it is a pointer to the next
72 block reached by normal control flow. */
73 struct basicblock_ *b_next;
74 /* b_seen is used to perform a DFS of basicblocks. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000075 unsigned b_seen : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076 /* b_return is true if a RETURN_VALUE opcode is inserted. */
Neal Norwitz08b401f2006-01-07 21:24:09 +000077 unsigned b_return : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078 /* depth of stack upon entry of block, computed by stackdepth() */
79 int b_startdepth;
80 /* instruction offset for block, computed by assemble_jump_offsets() */
Jeremy Hyltone9357b22006-03-01 15:47:05 +000081 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082} basicblock;
83
84/* fblockinfo tracks the current frame block.
85
Jeremy Hyltone9357b22006-03-01 15:47:05 +000086A frame block is used to handle loops, try/except, and try/finally.
87It's called a frame block to distinguish it from a basic block in the
88compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089*/
90
91enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
92
93struct fblockinfo {
Jeremy Hyltone9357b22006-03-01 15:47:05 +000094 enum fblocktype fb_type;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095 basicblock *fb_block;
96};
97
98/* The following items change on entry and exit of code blocks.
99 They must be saved and restored when returning to a block.
100*/
101struct compiler_unit {
102 PySTEntryObject *u_ste;
103
104 PyObject *u_name;
105 /* The following fields are dicts that map objects to
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000106 the index of them in co_XXX. The index is used as
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107 the argument for opcodes that refer to those collections.
108 */
109 PyObject *u_consts; /* all constants */
110 PyObject *u_names; /* all names */
111 PyObject *u_varnames; /* local variables */
112 PyObject *u_cellvars; /* cell variables */
113 PyObject *u_freevars; /* free variables */
114
115 PyObject *u_private; /* for private name mangling */
116
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000117 int u_argcount; /* number of arguments for block */
Jeremy Hylton12603c42006-04-01 16:18:02 +0000118 /* Pointer to the most recently allocated block. By following b_list
119 members, you can reach all early allocated blocks. */
120 basicblock *u_blocks;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121 basicblock *u_curblock; /* pointer to current block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000122 int u_tmpname; /* temporary variables for list comps */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
124 int u_nfblocks;
125 struct fblockinfo u_fblock[CO_MAXBLOCKS];
126
127 int u_firstlineno; /* the first lineno of the block */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000128 int u_lineno; /* the lineno for the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129 bool u_lineno_set; /* boolean to indicate whether instr
130 has been generated with current lineno */
131};
132
133/* This struct captures the global state of a compilation.
134
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000135The u pointer points to the current compilation unit, while units
136for enclosing blocks are stored in c_stack. The u and c_stack are
137managed by compiler_enter_scope() and compiler_exit_scope().
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138*/
139
140struct compiler {
141 const char *c_filename;
142 struct symtable *c_st;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000143 PyFutureFeatures *c_future; /* pointer to module's __future__ */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144 PyCompilerFlags *c_flags;
145
Neal Norwitz4ffedad2006-08-04 04:58:47 +0000146 int c_interactive; /* true if in interactive mode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000147 int c_nestlevel;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000149 struct compiler_unit *u; /* compiler state for current block */
150 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000151 char *c_encoding; /* source encoding (a borrowed reference) */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000152 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
155struct assembler {
156 PyObject *a_bytecode; /* string containing bytecode */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000157 int a_offset; /* offset into bytecode */
158 int a_nblocks; /* number of reachable blocks */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159 basicblock **a_postorder; /* list of blocks in dfs postorder */
160 PyObject *a_lnotab; /* string containing lnotab */
161 int a_lnotab_off; /* offset into lnotab */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000162 int a_lineno; /* last lineno of emitted instruction */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000163 int a_lineno_off; /* bytecode offset of last lineno */
164};
165
166static int compiler_enter_scope(struct compiler *, identifier, void *, int);
167static void compiler_free(struct compiler *);
168static basicblock *compiler_new_block(struct compiler *);
169static int compiler_next_instr(struct compiler *, basicblock *);
170static int compiler_addop(struct compiler *, int);
171static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *);
172static int compiler_addop_i(struct compiler *, int, int);
173static int compiler_addop_j(struct compiler *, int, basicblock *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174static basicblock *compiler_use_new_block(struct compiler *);
175static int compiler_error(struct compiler *, const char *);
176static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
177
178static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
179static int compiler_visit_stmt(struct compiler *, stmt_ty);
180static int compiler_visit_keyword(struct compiler *, keyword_ty);
181static int compiler_visit_expr(struct compiler *, expr_ty);
182static int compiler_augassign(struct compiler *, stmt_ty);
183static int compiler_visit_slice(struct compiler *, slice_ty,
184 expr_context_ty);
185
186static int compiler_push_fblock(struct compiler *, enum fblocktype,
187 basicblock *);
188static void compiler_pop_fblock(struct compiler *, enum fblocktype,
189 basicblock *);
Georg Brandla5fe3ef2006-10-08 07:12:23 +0000190/* Returns true if there is a loop on the fblock stack. */
191static int compiler_in_loop(struct compiler *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
193static int inplace_binop(struct compiler *, operator_ty);
194static int expr_constant(expr_ty e);
195
Guido van Rossumc2e20742006-02-27 22:32:47 +0000196static int compiler_with(struct compiler *, stmt_ty);
197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198static PyCodeObject *assemble(struct compiler *, int addNone);
199static PyObject *__doc__;
200
201PyObject *
Anthony Baxter7b782b62006-04-11 12:01:56 +0000202_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000203{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204 /* Name mangling: __private becomes _classname__private.
205 This is independent from how the name is used. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206 const char *p, *name = PyString_AsString(ident);
207 char *buffer;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208 size_t nlen, plen;
Neal Norwitz84167d02006-08-12 01:45:47 +0000209 if (privateobj == NULL || !PyString_Check(privateobj) ||
210 name == NULL || name[0] != '_' || name[1] != '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000211 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212 return ident;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000213 }
Anthony Baxter7b782b62006-04-11 12:01:56 +0000214 p = PyString_AsString(privateobj);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215 nlen = strlen(name);
216 if (name[nlen-1] == '_' && name[nlen-2] == '_') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000217 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218 return ident; /* Don't mangle __whatever__ */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000219 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220 /* Strip leading underscores from class name */
221 while (*p == '_')
222 p++;
223 if (*p == '\0') {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000224 Py_INCREF(ident);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225 return ident; /* Don't mangle if class is just underscores */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227 plen = strlen(p);
Martin v. Löwis73c01d42008-02-14 11:26:18 +0000228
229 assert(1 <= PY_SSIZE_T_MAX - nlen);
230 assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
231
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000232 ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
233 if (!ident)
234 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000236 buffer = PyString_AS_STRING(ident);
237 buffer[0] = '_';
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000238 strncpy(buffer+1, p, plen);
239 strcpy(buffer+1+plen, name);
240 return ident;
Michael W. Hudson60934622004-08-12 17:56:29 +0000241}
242
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000243static int
244compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000245{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000246 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000247
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000248 c->c_stack = PyList_New(0);
249 if (!c->c_stack)
250 return 0;
251
252 return 1;
253}
254
255PyCodeObject *
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000256PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000257 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000258{
259 struct compiler c;
260 PyCodeObject *co = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000261 PyCompilerFlags local_flags;
262 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000264 if (!__doc__) {
265 __doc__ = PyString_InternFromString("__doc__");
266 if (!__doc__)
267 return NULL;
268 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000269
270 if (!compiler_init(&c))
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000271 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000272 c.c_filename = filename;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000273 c.c_arena = arena;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000274 c.c_future = PyFuture_FromAST(mod, filename);
275 if (c.c_future == NULL)
Thomas Wouters1175c432006-02-27 22:49:54 +0000276 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277 if (!flags) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000278 local_flags.cf_flags = 0;
279 flags = &local_flags;
280 }
281 merged = c.c_future->ff_features | flags->cf_flags;
282 c.c_future->ff_features = merged;
283 flags->cf_flags = merged;
284 c.c_flags = flags;
285 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000286
287 c.c_st = PySymtable_Build(mod, filename, c.c_future);
288 if (c.c_st == NULL) {
289 if (!PyErr_Occurred())
290 PyErr_SetString(PyExc_SystemError, "no symtable");
Thomas Wouters1175c432006-02-27 22:49:54 +0000291 goto finally;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000292 }
293
294 /* XXX initialize to NULL for now, need to handle */
295 c.c_encoding = NULL;
296
297 co = compiler_mod(&c, mod);
298
Thomas Wouters1175c432006-02-27 22:49:54 +0000299 finally:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000300 compiler_free(&c);
Thomas Woutersbfe51ea2006-02-27 22:48:55 +0000301 assert(co || PyErr_Occurred());
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000302 return co;
303}
304
305PyCodeObject *
306PyNode_Compile(struct _node *n, const char *filename)
307{
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000308 PyCodeObject *co = NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000309 mod_ty mod;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000310 PyArena *arena = PyArena_New();
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000311 if (!arena)
312 return NULL;
313 mod = PyAST_FromNode(n, NULL, filename, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000314 if (mod)
315 co = PyAST_Compile(mod, filename, NULL, arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000316 PyArena_Free(arena);
Raymond Hettinger37a724d2003-09-15 21:43:16 +0000317 return co;
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000318}
319
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000320static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000321compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000322{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323 if (c->c_st)
324 PySymtable_Free(c->c_st);
325 if (c->c_future)
Neal Norwitz14bc4e42006-04-10 06:57:06 +0000326 PyObject_Free(c->c_future);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000328}
329
Guido van Rossum79f25d91997-04-29 20:08:16 +0000330static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000331list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000332{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000333 Py_ssize_t i, n;
Georg Brandl5c170fd2006-03-17 19:03:25 +0000334 PyObject *v, *k;
335 PyObject *dict = PyDict_New();
336 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000337
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338 n = PyList_Size(list);
339 for (i = 0; i < n; i++) {
340 v = PyInt_FromLong(i);
341 if (!v) {
342 Py_DECREF(dict);
343 return NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000344 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000345 k = PyList_GET_ITEM(list, i);
Georg Brandl7784f122006-05-26 20:04:44 +0000346 k = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000347 if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
348 Py_XDECREF(k);
349 Py_DECREF(v);
350 Py_DECREF(dict);
351 return NULL;
352 }
Neal Norwitz4737b232005-11-19 23:58:29 +0000353 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354 Py_DECREF(v);
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000355 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356 return dict;
357}
358
359/* Return new dict containing names from src that match scope(s).
360
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000361src is a symbol table dictionary. If the scope of a name matches
362either scope_type or flag is set, insert it into the new dict. The
363values are integers, starting at offset and increasing by one for
364each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365*/
366
367static PyObject *
368dictbytype(PyObject *src, int scope_type, int flag, int offset)
369{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000370 Py_ssize_t pos = 0, i = offset, scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000371 PyObject *k, *v, *dest = PyDict_New();
372
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000373 assert(offset >= 0);
374 if (dest == NULL)
375 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376
377 while (PyDict_Next(src, &pos, &k, &v)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000378 /* XXX this should probably be a macro in symtable.h */
379 assert(PyInt_Check(v));
380 scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000382 if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
383 PyObject *tuple, *item = PyInt_FromLong(i);
384 if (item == NULL) {
385 Py_DECREF(dest);
386 return NULL;
387 }
388 i++;
Georg Brandl7784f122006-05-26 20:04:44 +0000389 tuple = PyTuple_Pack(2, k, k->ob_type);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000390 if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
391 Py_DECREF(item);
392 Py_DECREF(dest);
393 Py_XDECREF(tuple);
394 return NULL;
395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 Py_DECREF(item);
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000397 Py_DECREF(tuple);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399 }
400 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000401}
402
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000403/* Begin: Peephole optimizations ----------------------------------------- */
404
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000405#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000406#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
Raymond Hettinger5b75c382003-03-28 12:05:00 +0000407#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP)
408#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000409#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000410#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000411#define ISBASICBLOCK(blocks, start, bytes) \
412 (blocks[start]==blocks[start+bytes-1])
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000413
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000414/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000415 with LOAD_CONST (c1, c2, ... cn).
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000416 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000417 new constant (c1, c2, ... cn) can be appended.
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000418 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000419 Bails out with no change if one or more of the LOAD_CONSTs is missing.
420 Also works for BUILD_LIST when followed by an "in" or "not in" test.
421*/
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000422static int
423tuple_of_constants(unsigned char *codestr, int n, PyObject *consts)
424{
425 PyObject *newconst, *constant;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000426 Py_ssize_t i, arg, len_consts;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000427
428 /* Pre-conditions */
429 assert(PyList_CheckExact(consts));
Raymond Hettinger7fcb7862005-02-07 19:32:38 +0000430 assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000431 assert(GETARG(codestr, (n*3)) == n);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000432 for (i=0 ; i<n ; i++)
Raymond Hettingereffb3932004-10-30 08:55:08 +0000433 assert(codestr[i*3] == LOAD_CONST);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000434
435 /* Buildup new tuple of constants */
436 newconst = PyTuple_New(n);
437 if (newconst == NULL)
438 return 0;
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000439 len_consts = PyList_GET_SIZE(consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000440 for (i=0 ; i<n ; i++) {
441 arg = GETARG(codestr, (i*3));
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000442 assert(arg < len_consts);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000443 constant = PyList_GET_ITEM(consts, arg);
444 Py_INCREF(constant);
445 PyTuple_SET_ITEM(newconst, i, constant);
446 }
447
448 /* Append folded constant onto consts */
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000449 if (PyList_Append(consts, newconst)) {
450 Py_DECREF(newconst);
451 return 0;
452 }
453 Py_DECREF(newconst);
454
455 /* Write NOPs over old LOAD_CONSTS and
456 add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
457 memset(codestr, NOP, n*3);
458 codestr[n*3] = LOAD_CONST;
459 SETARG(codestr, (n*3), len_consts);
460 return 1;
461}
462
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000463/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464 with LOAD_CONST binop(c1,c2)
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000465 The consts table must still be in list form so that the
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000466 new constant can be appended.
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000467 Called with codestr pointing to the first LOAD_CONST.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000468 Abandons the transformation if the folding fails (i.e. 1+'a').
469 If the new constant is a sequence, only folds when the size
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000470 is below a threshold value. That keeps pyc files from
471 becoming large in the presence of code like: (None,)*1000.
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000472*/
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000473static int
474fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
475{
476 PyObject *newconst, *v, *w;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477 Py_ssize_t len_consts, size;
478 int opcode;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000479
480 /* Pre-conditions */
481 assert(PyList_CheckExact(consts));
482 assert(codestr[0] == LOAD_CONST);
483 assert(codestr[3] == LOAD_CONST);
484
485 /* Create new constant */
486 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
487 w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
488 opcode = codestr[6];
489 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000490 case BINARY_POWER:
491 newconst = PyNumber_Power(v, w, Py_None);
492 break;
493 case BINARY_MULTIPLY:
494 newconst = PyNumber_Multiply(v, w);
495 break;
496 case BINARY_DIVIDE:
497 /* Cannot fold this operation statically since
498 the result can depend on the run-time presence
499 of the -Qnew flag */
500 return 0;
501 case BINARY_TRUE_DIVIDE:
502 newconst = PyNumber_TrueDivide(v, w);
503 break;
504 case BINARY_FLOOR_DIVIDE:
505 newconst = PyNumber_FloorDivide(v, w);
506 break;
507 case BINARY_MODULO:
508 newconst = PyNumber_Remainder(v, w);
509 break;
510 case BINARY_ADD:
511 newconst = PyNumber_Add(v, w);
512 break;
513 case BINARY_SUBTRACT:
514 newconst = PyNumber_Subtract(v, w);
515 break;
516 case BINARY_SUBSCR:
517 newconst = PyObject_GetItem(v, w);
518 break;
519 case BINARY_LSHIFT:
520 newconst = PyNumber_Lshift(v, w);
521 break;
522 case BINARY_RSHIFT:
523 newconst = PyNumber_Rshift(v, w);
524 break;
525 case BINARY_AND:
526 newconst = PyNumber_And(v, w);
527 break;
528 case BINARY_XOR:
529 newconst = PyNumber_Xor(v, w);
530 break;
531 case BINARY_OR:
532 newconst = PyNumber_Or(v, w);
533 break;
534 default:
535 /* Called with an unknown opcode */
536 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000537 "unexpected binary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000538 opcode);
539 return 0;
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000540 }
541 if (newconst == NULL) {
542 PyErr_Clear();
543 return 0;
544 }
Raymond Hettinger9feb2672005-01-26 12:50:05 +0000545 size = PyObject_Size(newconst);
546 if (size == -1)
547 PyErr_Clear();
548 else if (size > 20) {
549 Py_DECREF(newconst);
550 return 0;
551 }
Raymond Hettingerc34f8672005-01-02 06:17:33 +0000552
553 /* Append folded constant into consts table */
554 len_consts = PyList_GET_SIZE(consts);
555 if (PyList_Append(consts, newconst)) {
556 Py_DECREF(newconst);
557 return 0;
558 }
559 Py_DECREF(newconst);
560
561 /* Write NOP NOP NOP NOP LOAD_CONST newconst */
562 memset(codestr, NOP, 4);
563 codestr[4] = LOAD_CONST;
564 SETARG(codestr, 4, len_consts);
565 return 1;
566}
567
Raymond Hettinger80121492005-02-20 12:41:32 +0000568static int
569fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
570{
Raymond Hettingere63a0782005-02-23 13:37:55 +0000571 PyObject *newconst=NULL, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000572 Py_ssize_t len_consts;
573 int opcode;
Raymond Hettinger80121492005-02-20 12:41:32 +0000574
575 /* Pre-conditions */
576 assert(PyList_CheckExact(consts));
577 assert(codestr[0] == LOAD_CONST);
578
579 /* Create new constant */
580 v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
581 opcode = codestr[3];
582 switch (opcode) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000583 case UNARY_NEGATIVE:
584 /* Preserve the sign of -0.0 */
585 if (PyObject_IsTrue(v) == 1)
586 newconst = PyNumber_Negative(v);
587 break;
588 case UNARY_CONVERT:
589 newconst = PyObject_Repr(v);
590 break;
591 case UNARY_INVERT:
592 newconst = PyNumber_Invert(v);
593 break;
594 default:
595 /* Called with an unknown opcode */
596 PyErr_Format(PyExc_SystemError,
Neal Norwitz4737b232005-11-19 23:58:29 +0000597 "unexpected unary operation %d on a constant",
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000598 opcode);
599 return 0;
Raymond Hettinger80121492005-02-20 12:41:32 +0000600 }
601 if (newconst == NULL) {
602 PyErr_Clear();
603 return 0;
604 }
605
606 /* Append folded constant into consts table */
607 len_consts = PyList_GET_SIZE(consts);
608 if (PyList_Append(consts, newconst)) {
609 Py_DECREF(newconst);
610 return 0;
611 }
612 Py_DECREF(newconst);
613
614 /* Write NOP LOAD_CONST newconst */
615 codestr[0] = NOP;
616 codestr[1] = LOAD_CONST;
617 SETARG(codestr, 1, len_consts);
618 return 1;
619}
620
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000621static unsigned int *
622markblocks(unsigned char *code, int len)
623{
Anthony Baxter7b782b62006-04-11 12:01:56 +0000624 unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000625 int i,j, opcode, blockcnt = 0;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000626
Martin v. Löwis73c01d42008-02-14 11:26:18 +0000627 assert(len <= PY_SIZE_MAX / sizeof(int));
628
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000629 if (blocks == NULL) {
630 PyErr_NoMemory();
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000631 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +0000632 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000633 memset(blocks, 0, len*sizeof(int));
Raymond Hettingereffb3932004-10-30 08:55:08 +0000634
635 /* Mark labels in the first pass */
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000636 for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
637 opcode = code[i];
638 switch (opcode) {
639 case FOR_ITER:
640 case JUMP_FORWARD:
641 case JUMP_IF_FALSE:
642 case JUMP_IF_TRUE:
643 case JUMP_ABSOLUTE:
644 case CONTINUE_LOOP:
645 case SETUP_LOOP:
646 case SETUP_EXCEPT:
647 case SETUP_FINALLY:
648 j = GETJUMPTGT(code, i);
Raymond Hettingereffb3932004-10-30 08:55:08 +0000649 blocks[j] = 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000650 break;
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000651 }
652 }
Raymond Hettingereffb3932004-10-30 08:55:08 +0000653 /* Build block numbers in the second pass */
654 for (i=0 ; i<len ; i++) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000655 blockcnt += blocks[i]; /* increment blockcnt over labels */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000656 blocks[i] = blockcnt;
657 }
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000658 return blocks;
659}
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000660
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000661/* Perform basic peephole optimizations to components of a code object.
662 The consts object should still be in list form to allow new constants
663 to be appended.
664
665 To keep the optimizer simple, it bails out (does nothing) for code
666 containing extended arguments or that has a length over 32,700. That
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000667 allows us to avoid overflow and sign issues. Likewise, it bails when
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000668 the lineno table has complex encoding for gaps >= 255.
669
670 Optimizations are restricted to simple transformations occuring within a
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000671 single basic block. All transformations keep the code size the same or
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000672 smaller. For those that reduce size, the gaps are initially filled with
673 NOPs. Later those NOPs are removed and the jump addresses retargeted in
674 a single pass. Line numbering is adjusted accordingly. */
675
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000676static PyObject *
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000677optimize_code(PyObject *code, PyObject* consts, PyObject *names,
678 PyObject *lineno_obj)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000679{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000680 Py_ssize_t i, j, codelen;
681 int nops, h, adj;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000682 int tgt, tgttgt, opcode;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000683 unsigned char *codestr = NULL;
684 unsigned char *lineno;
685 int *addrmap = NULL;
686 int new_line, cum_orig_line, last_line, tabsiz;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000687 int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
Raymond Hettingereffb3932004-10-30 08:55:08 +0000688 unsigned int *blocks = NULL;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000689 char *name;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000690
Raymond Hettingereffb3932004-10-30 08:55:08 +0000691 /* Bail out if an exception is set */
692 if (PyErr_Occurred())
693 goto exitUnchanged;
694
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000695 /* Bypass optimization when the lineno table is too complex */
696 assert(PyString_Check(lineno_obj));
Brett Cannonc9371d42005-06-25 08:23:41 +0000697 lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000698 tabsiz = PyString_GET_SIZE(lineno_obj);
699 if (memchr(lineno, 255, tabsiz) != NULL)
700 goto exitUnchanged;
701
Raymond Hettingera12fa142004-08-24 04:34:16 +0000702 /* Avoid situations where jump retargeting could overflow */
Raymond Hettinger06cc9732004-09-28 17:22:12 +0000703 assert(PyString_Check(code));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000704 codelen = PyString_Size(code);
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000705 if (codelen > 32700)
Raymond Hettingera12fa142004-08-24 04:34:16 +0000706 goto exitUnchanged;
707
708 /* Make a modifiable copy of the code string */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000709 codestr = (unsigned char *)PyMem_Malloc(codelen);
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000710 if (codestr == NULL)
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000711 goto exitUnchanged;
Anthony Baxter7b782b62006-04-11 12:01:56 +0000712 codestr = (unsigned char *)memcpy(codestr,
713 PyString_AS_STRING(code), codelen);
Raymond Hettinger98bd1812004-08-06 19:46:34 +0000714
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000715 /* Verify that RETURN_VALUE terminates the codestring. This allows
Raymond Hettinger07359a72005-02-21 20:03:14 +0000716 the various transformation patterns to look ahead several
717 instructions without additional checks to make sure they are not
718 looking beyond the end of the code string.
719 */
720 if (codestr[codelen-1] != RETURN_VALUE)
721 goto exitUnchanged;
722
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000723 /* Mapping to new jump targets after NOPs are removed */
Anthony Baxter7b782b62006-04-11 12:01:56 +0000724 addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000725 if (addrmap == NULL)
726 goto exitUnchanged;
727
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000728 blocks = markblocks(codestr, codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000729 if (blocks == NULL)
Raymond Hettingerff5bc502004-03-21 15:12:00 +0000730 goto exitUnchanged;
Raymond Hettinger2c31a052004-09-22 18:44:21 +0000731 assert(PyList_Check(consts));
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000732
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000733 for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000734 opcode = codestr[i];
Raymond Hettinger23109ef2004-10-26 08:59:14 +0000735
736 lastlc = cumlc;
737 cumlc = 0;
738
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000739 switch (opcode) {
740
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000741 /* Replace UNARY_NOT JUMP_IF_FALSE POP_TOP with
742 with JUMP_IF_TRUE POP_TOP */
743 case UNARY_NOT:
744 if (codestr[i+1] != JUMP_IF_FALSE ||
745 codestr[i+4] != POP_TOP ||
746 !ISBASICBLOCK(blocks,i,5))
747 continue;
748 tgt = GETJUMPTGT(codestr, (i+1));
749 if (codestr[tgt] != POP_TOP)
750 continue;
751 j = GETARG(codestr, i+1) + 1;
752 codestr[i] = JUMP_IF_TRUE;
753 SETARG(codestr, i, j);
754 codestr[i+3] = POP_TOP;
755 codestr[i+4] = NOP;
756 break;
Raymond Hettinger9c18e812004-06-21 16:31:15 +0000757
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000758 /* not a is b --> a is not b
759 not a in b --> a not in b
760 not a is not b --> a is b
761 not a not in b --> a in b
762 */
763 case COMPARE_OP:
764 j = GETARG(codestr, i);
765 if (j < 6 || j > 9 ||
766 codestr[i+3] != UNARY_NOT ||
767 !ISBASICBLOCK(blocks,i,4))
768 continue;
769 SETARG(codestr, i, (j^1));
770 codestr[i+3] = NOP;
771 break;
Tim Petersdb5860b2004-07-17 05:00:52 +0000772
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000773 /* Replace LOAD_GLOBAL/LOAD_NAME None
774 with LOAD_CONST None */
775 case LOAD_NAME:
776 case LOAD_GLOBAL:
777 j = GETARG(codestr, i);
778 name = PyString_AsString(PyTuple_GET_ITEM(names, j));
779 if (name == NULL || strcmp(name, "None") != 0)
780 continue;
781 for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
Raymond Hettingerd882e362007-03-02 19:19:05 +0000782 if (PyList_GET_ITEM(consts, j) == Py_None)
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000783 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000784 }
Raymond Hettingerd882e362007-03-02 19:19:05 +0000785 if (j == PyList_GET_SIZE(consts)) {
786 if (PyList_Append(consts, Py_None) == -1)
787 goto exitUnchanged;
788 }
789 assert(PyList_GET_ITEM(consts, j) == Py_None);
790 codestr[i] = LOAD_CONST;
791 SETARG(codestr, i, j);
792 cumlc = lastlc + 1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000793 break;
794
795 /* Skip over LOAD_CONST trueconst
796 JUMP_IF_FALSE xx POP_TOP */
797 case LOAD_CONST:
798 cumlc = lastlc + 1;
799 j = GETARG(codestr, i);
800 if (codestr[i+3] != JUMP_IF_FALSE ||
801 codestr[i+6] != POP_TOP ||
802 !ISBASICBLOCK(blocks,i,7) ||
803 !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
804 continue;
805 memset(codestr+i, NOP, 7);
806 cumlc = 0;
807 break;
808
809 /* Try to fold tuples of constants (includes a case for lists
810 which are only used for "in" and "not in" tests).
811 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
812 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
813 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
814 case BUILD_TUPLE:
815 case BUILD_LIST:
816 j = GETARG(codestr, i);
817 h = i - 3 * j;
818 if (h >= 0 &&
819 j <= lastlc &&
820 ((opcode == BUILD_TUPLE &&
821 ISBASICBLOCK(blocks, h, 3*(j+1))) ||
822 (opcode == BUILD_LIST &&
823 codestr[i+3]==COMPARE_OP &&
824 ISBASICBLOCK(blocks, h, 3*(j+2)) &&
825 (GETARG(codestr,i+3)==6 ||
826 GETARG(codestr,i+3)==7))) &&
827 tuple_of_constants(&codestr[h], j, consts)) {
828 assert(codestr[i] == LOAD_CONST);
829 cumlc = 1;
Raymond Hettinger76d962d2004-07-16 12:16:48 +0000830 break;
831 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000832 if (codestr[i+3] != UNPACK_SEQUENCE ||
833 !ISBASICBLOCK(blocks,i,6) ||
834 j != GETARG(codestr, i+3))
835 continue;
836 if (j == 1) {
837 memset(codestr+i, NOP, 6);
838 } else if (j == 2) {
839 codestr[i] = ROT_TWO;
840 memset(codestr+i+1, NOP, 5);
841 } else if (j == 3) {
842 codestr[i] = ROT_THREE;
843 codestr[i+1] = ROT_TWO;
844 memset(codestr+i+2, NOP, 4);
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000845 }
846 break;
Raymond Hettingeref0a82b2004-08-25 03:18:29 +0000847
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000848 /* Fold binary ops on constants.
849 LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
850 case BINARY_POWER:
851 case BINARY_MULTIPLY:
852 case BINARY_TRUE_DIVIDE:
853 case BINARY_FLOOR_DIVIDE:
854 case BINARY_MODULO:
855 case BINARY_ADD:
856 case BINARY_SUBTRACT:
857 case BINARY_SUBSCR:
858 case BINARY_LSHIFT:
859 case BINARY_RSHIFT:
860 case BINARY_AND:
861 case BINARY_XOR:
862 case BINARY_OR:
863 if (lastlc >= 2 &&
864 ISBASICBLOCK(blocks, i-6, 7) &&
865 fold_binops_on_constants(&codestr[i-6], consts)) {
866 i -= 2;
867 assert(codestr[i] == LOAD_CONST);
868 cumlc = 1;
869 }
870 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000871
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000872 /* Fold unary ops on constants.
873 LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
874 case UNARY_NEGATIVE:
875 case UNARY_CONVERT:
876 case UNARY_INVERT:
877 if (lastlc >= 1 &&
878 ISBASICBLOCK(blocks, i-3, 4) &&
879 fold_unaryops_on_constants(&codestr[i-3], consts)) {
880 i -= 2;
881 assert(codestr[i] == LOAD_CONST);
882 cumlc = 1;
883 }
884 break;
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000885
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000886 /* Simplify conditional jump to conditional jump where the
887 result of the first test implies the success of a similar
888 test or the failure of the opposite test.
889 Arises in code like:
890 "if a and b:"
891 "if a or b:"
892 "a and b or c"
893 "(a and b) and c"
894 x:JUMP_IF_FALSE y y:JUMP_IF_FALSE z --> x:JUMP_IF_FALSE z
895 x:JUMP_IF_FALSE y y:JUMP_IF_TRUE z --> x:JUMP_IF_FALSE y+3
896 where y+3 is the instruction following the second test.
897 */
898 case JUMP_IF_FALSE:
899 case JUMP_IF_TRUE:
900 tgt = GETJUMPTGT(codestr, i);
901 j = codestr[tgt];
902 if (j == JUMP_IF_FALSE || j == JUMP_IF_TRUE) {
903 if (j == opcode) {
904 tgttgt = GETJUMPTGT(codestr, tgt) - i - 3;
905 SETARG(codestr, i, tgttgt);
906 } else {
907 tgt -= i;
908 SETARG(codestr, i, tgt);
909 }
910 break;
911 }
912 /* Intentional fallthrough */
913
914 /* Replace jumps to unconditional jumps */
915 case FOR_ITER:
916 case JUMP_FORWARD:
917 case JUMP_ABSOLUTE:
918 case CONTINUE_LOOP:
919 case SETUP_LOOP:
920 case SETUP_EXCEPT:
921 case SETUP_FINALLY:
922 tgt = GETJUMPTGT(codestr, i);
923 if (!UNCONDITIONAL_JUMP(codestr[tgt]))
924 continue;
925 tgttgt = GETJUMPTGT(codestr, tgt);
926 if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
927 opcode = JUMP_ABSOLUTE;
928 if (!ABSOLUTE_JUMP(opcode))
929 tgttgt -= i + 3; /* Calc relative jump addr */
930 if (tgttgt < 0) /* No backward relative jumps */
931 continue;
932 codestr[i] = opcode;
933 SETARG(codestr, i, tgttgt);
934 break;
935
936 case EXTENDED_ARG:
937 goto exitUnchanged;
938
939 /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
940 case RETURN_VALUE:
941 if (i+4 >= codelen ||
942 codestr[i+4] != RETURN_VALUE ||
943 !ISBASICBLOCK(blocks,i,5))
944 continue;
945 memset(codestr+i+1, NOP, 4);
946 break;
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000947 }
948 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000949
950 /* Fixup linenotab */
Raymond Hettinger099ecfb2004-11-01 15:19:11 +0000951 for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
952 addrmap[i] = i - nops;
953 if (codestr[i] == NOP)
954 nops++;
955 }
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000956 cum_orig_line = 0;
957 last_line = 0;
958 for (i=0 ; i < tabsiz ; i+=2) {
959 cum_orig_line += lineno[i];
960 new_line = addrmap[cum_orig_line];
Raymond Hettinger1792bfb2004-08-25 17:19:38 +0000961 assert (new_line - last_line < 255);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000962 lineno[i] =((unsigned char)(new_line - last_line));
963 last_line = new_line;
964 }
965
966 /* Remove NOPs and fixup jump targets */
967 for (i=0, h=0 ; i<codelen ; ) {
968 opcode = codestr[i];
969 switch (opcode) {
970 case NOP:
971 i++;
972 continue;
973
974 case JUMP_ABSOLUTE:
975 case CONTINUE_LOOP:
976 j = addrmap[GETARG(codestr, i)];
977 SETARG(codestr, i, j);
978 break;
979
980 case FOR_ITER:
981 case JUMP_FORWARD:
982 case JUMP_IF_FALSE:
983 case JUMP_IF_TRUE:
984 case SETUP_LOOP:
985 case SETUP_EXCEPT:
986 case SETUP_FINALLY:
987 j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
988 SETARG(codestr, i, j);
989 break;
990 }
991 adj = CODESIZE(opcode);
992 while (adj--)
993 codestr[h++] = codestr[i++];
994 }
Raymond Hettingera12fa142004-08-24 04:34:16 +0000995 assert(h + nops == codelen);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +0000996
997 code = PyString_FromStringAndSize((char *)codestr, h);
998 PyMem_Free(addrmap);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +0000999 PyMem_Free(codestr);
Raymond Hettingerff5bc502004-03-21 15:12:00 +00001000 PyMem_Free(blocks);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +00001001 return code;
1002
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001003 exitUnchanged:
Raymond Hettingereffb3932004-10-30 08:55:08 +00001004 if (blocks != NULL)
1005 PyMem_Free(blocks);
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +00001006 if (addrmap != NULL)
1007 PyMem_Free(addrmap);
1008 if (codestr != NULL)
1009 PyMem_Free(codestr);
Raymond Hettingerf6f575a2003-03-26 01:07:54 +00001010 Py_INCREF(code);
1011 return code;
1012}
1013
Raymond Hettinger2c31a052004-09-22 18:44:21 +00001014/* End: Peephole optimizations ----------------------------------------- */
1015
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001016/*
1017
1018Leave this debugging code for just a little longer.
1019
1020static void
1021compiler_display_symbols(PyObject *name, PyObject *symbols)
1022{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001023PyObject *key, *value;
1024int flags;
1025Py_ssize_t pos = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001026
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001027fprintf(stderr, "block %s\n", PyString_AS_STRING(name));
1028while (PyDict_Next(symbols, &pos, &key, &value)) {
1029flags = PyInt_AsLong(value);
1030fprintf(stderr, "var %s:", PyString_AS_STRING(key));
1031if (flags & DEF_GLOBAL)
1032fprintf(stderr, " declared_global");
1033if (flags & DEF_LOCAL)
1034fprintf(stderr, " local");
1035if (flags & DEF_PARAM)
1036fprintf(stderr, " param");
1037if (flags & DEF_STAR)
1038fprintf(stderr, " stararg");
1039if (flags & DEF_DOUBLESTAR)
1040fprintf(stderr, " starstar");
1041if (flags & DEF_INTUPLE)
1042fprintf(stderr, " tuple");
1043if (flags & DEF_FREE)
1044fprintf(stderr, " free");
1045if (flags & DEF_FREE_GLOBAL)
1046fprintf(stderr, " global");
1047if (flags & DEF_FREE_CLASS)
1048fprintf(stderr, " free/class");
1049if (flags & DEF_IMPORT)
1050fprintf(stderr, " import");
1051fprintf(stderr, "\n");
1052}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053 fprintf(stderr, "\n");
1054}
1055*/
1056
1057static void
1058compiler_unit_check(struct compiler_unit *u)
1059{
1060 basicblock *block;
1061 for (block = u->u_blocks; block != NULL; block = block->b_list) {
1062 assert(block != (void *)0xcbcbcbcb);
1063 assert(block != (void *)0xfbfbfbfb);
1064 assert(block != (void *)0xdbdbdbdb);
1065 if (block->b_instr != NULL) {
1066 assert(block->b_ialloc > 0);
1067 assert(block->b_iused > 0);
1068 assert(block->b_ialloc >= block->b_iused);
1069 }
1070 else {
1071 assert (block->b_iused == 0);
1072 assert (block->b_ialloc == 0);
1073 }
1074 }
1075}
1076
1077static void
1078compiler_unit_free(struct compiler_unit *u)
1079{
1080 basicblock *b, *next;
1081
1082 compiler_unit_check(u);
1083 b = u->u_blocks;
1084 while (b != NULL) {
1085 if (b->b_instr)
1086 PyObject_Free((void *)b->b_instr);
1087 next = b->b_list;
1088 PyObject_Free((void *)b);
1089 b = next;
1090 }
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001091 Py_CLEAR(u->u_ste);
1092 Py_CLEAR(u->u_name);
1093 Py_CLEAR(u->u_consts);
1094 Py_CLEAR(u->u_names);
1095 Py_CLEAR(u->u_varnames);
1096 Py_CLEAR(u->u_freevars);
1097 Py_CLEAR(u->u_cellvars);
1098 Py_CLEAR(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099 PyObject_Free(u);
1100}
1101
1102static int
1103compiler_enter_scope(struct compiler *c, identifier name, void *key,
1104 int lineno)
1105{
1106 struct compiler_unit *u;
1107
Anthony Baxter7b782b62006-04-11 12:01:56 +00001108 u = (struct compiler_unit *)PyObject_Malloc(sizeof(
1109 struct compiler_unit));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001110 if (!u) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001111 PyErr_NoMemory();
1112 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001113 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001114 memset(u, 0, sizeof(struct compiler_unit));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001115 u->u_argcount = 0;
1116 u->u_ste = PySymtable_Lookup(c->c_st, key);
1117 if (!u->u_ste) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001118 compiler_unit_free(u);
1119 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001120 }
1121 Py_INCREF(name);
1122 u->u_name = name;
1123 u->u_varnames = list2dict(u->u_ste->ste_varnames);
1124 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
Neal Norwitzd12bd012006-07-21 07:59:47 +00001125 if (!u->u_varnames || !u->u_cellvars) {
1126 compiler_unit_free(u);
1127 return 0;
1128 }
1129
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001130 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001131 PyDict_Size(u->u_cellvars));
Neal Norwitzd12bd012006-07-21 07:59:47 +00001132 if (!u->u_freevars) {
1133 compiler_unit_free(u);
1134 return 0;
1135 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001136
1137 u->u_blocks = NULL;
1138 u->u_tmpname = 0;
1139 u->u_nfblocks = 0;
1140 u->u_firstlineno = lineno;
1141 u->u_lineno = 0;
1142 u->u_lineno_set = false;
1143 u->u_consts = PyDict_New();
1144 if (!u->u_consts) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001145 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146 return 0;
1147 }
1148 u->u_names = PyDict_New();
1149 if (!u->u_names) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001150 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151 return 0;
1152 }
1153
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001154 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001155
1156 /* Push the old compiler_unit on the stack. */
1157 if (c->u) {
1158 PyObject *wrapper = PyCObject_FromVoidPtr(c->u, NULL);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001159 if (!wrapper || PyList_Append(c->c_stack, wrapper) < 0) {
1160 Py_XDECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001161 compiler_unit_free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001162 return 0;
1163 }
1164 Py_DECREF(wrapper);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001165 u->u_private = c->u->u_private;
1166 Py_XINCREF(u->u_private);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167 }
1168 c->u = u;
1169
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001170 c->c_nestlevel++;
Martin v. Löwis94962612006-01-02 21:15:05 +00001171 if (compiler_use_new_block(c) == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001172 return 0;
1173
1174 return 1;
1175}
1176
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001177static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178compiler_exit_scope(struct compiler *c)
1179{
1180 int n;
1181 PyObject *wrapper;
1182
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001183 c->c_nestlevel--;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184 compiler_unit_free(c->u);
1185 /* Restore c->u to the parent unit. */
1186 n = PyList_GET_SIZE(c->c_stack) - 1;
1187 if (n >= 0) {
1188 wrapper = PyList_GET_ITEM(c->c_stack, n);
1189 c->u = (struct compiler_unit *)PyCObject_AsVoidPtr(wrapper);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001190 /* we are deleting from a list so this really shouldn't fail */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001191 if (PySequence_DelItem(c->c_stack, n) < 0)
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001192 Py_FatalError("compiler_exit_scope()");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193 compiler_unit_check(c->u);
1194 }
1195 else
1196 c->u = NULL;
1197
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
Guido van Rossumc2e20742006-02-27 22:32:47 +00001200/* Allocate a new "anonymous" local variable.
1201 Used by list comprehensions and with statements.
1202*/
1203
1204static PyObject *
1205compiler_new_tmpname(struct compiler *c)
1206{
1207 char tmpname[256];
1208 PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++c->u->u_tmpname);
1209 return PyString_FromString(tmpname);
1210}
1211
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001212/* Allocate a new block and return a pointer to it.
1213 Returns NULL on error.
1214*/
1215
1216static basicblock *
1217compiler_new_block(struct compiler *c)
1218{
1219 basicblock *b;
1220 struct compiler_unit *u;
1221
1222 u = c->u;
1223 b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
Neal Norwitz87b801c2005-12-18 04:42:47 +00001224 if (b == NULL) {
1225 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001226 return NULL;
Neal Norwitz87b801c2005-12-18 04:42:47 +00001227 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001228 memset((void *)b, 0, sizeof(basicblock));
Jeremy Hylton12603c42006-04-01 16:18:02 +00001229 /* Extend the singly linked list of blocks with new block. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001230 b->b_list = u->u_blocks;
1231 u->u_blocks = b;
1232 return b;
1233}
1234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001235static basicblock *
1236compiler_use_new_block(struct compiler *c)
1237{
1238 basicblock *block = compiler_new_block(c);
1239 if (block == NULL)
1240 return NULL;
1241 c->u->u_curblock = block;
1242 return block;
1243}
1244
1245static basicblock *
1246compiler_next_block(struct compiler *c)
1247{
1248 basicblock *block = compiler_new_block(c);
1249 if (block == NULL)
1250 return NULL;
1251 c->u->u_curblock->b_next = block;
1252 c->u->u_curblock = block;
1253 return block;
1254}
1255
1256static basicblock *
1257compiler_use_next_block(struct compiler *c, basicblock *block)
1258{
1259 assert(block != NULL);
1260 c->u->u_curblock->b_next = block;
1261 c->u->u_curblock = block;
1262 return block;
1263}
1264
1265/* Returns the offset of the next instruction in the current block's
1266 b_instr array. Resizes the b_instr as necessary.
1267 Returns -1 on failure.
1268 */
1269
1270static int
1271compiler_next_instr(struct compiler *c, basicblock *b)
1272{
1273 assert(b != NULL);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001274 if (b->b_instr == NULL) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001275 b->b_instr = (struct instr *)PyObject_Malloc(
1276 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001277 if (b->b_instr == NULL) {
1278 PyErr_NoMemory();
1279 return -1;
1280 }
1281 b->b_ialloc = DEFAULT_BLOCK_SIZE;
1282 memset((char *)b->b_instr, 0,
1283 sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 else if (b->b_iused == b->b_ialloc) {
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001286 struct instr *tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001287 size_t oldsize, newsize;
1288 oldsize = b->b_ialloc * sizeof(struct instr);
1289 newsize = oldsize << 1;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00001290
1291 if (oldsize > (PY_SIZE_MAX >> 1)) {
1292 PyErr_NoMemory();
1293 return -1;
1294 }
1295
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001296 if (newsize == 0) {
1297 PyErr_NoMemory();
1298 return -1;
1299 }
1300 b->b_ialloc <<= 1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001301 tmp = (struct instr *)PyObject_Realloc(
Anthony Baxter7b782b62006-04-11 12:01:56 +00001302 (void *)b->b_instr, newsize);
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001303 if (tmp == NULL) {
1304 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001305 return -1;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001306 }
1307 b->b_instr = tmp;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001308 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
1309 }
1310 return b->b_iused++;
1311}
1312
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00001313/* Set the i_lineno member of the instruction at offset off if the
1314 line number for the current expression/statement has not
Jeremy Hylton12603c42006-04-01 16:18:02 +00001315 already been set. If it has been set, the call has no effect.
1316
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00001317 The line number is reset in the following cases:
1318 - when entering a new scope
1319 - on each statement
1320 - on each expression that start a new line
1321 - before the "except" clause
1322 - before the "for" and "while" expressions
Jeremy Hylton12603c42006-04-01 16:18:02 +00001323 */
1324
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001325static void
1326compiler_set_lineno(struct compiler *c, int off)
1327{
1328 basicblock *b;
1329 if (c->u->u_lineno_set)
1330 return;
1331 c->u->u_lineno_set = true;
1332 b = c->u->u_curblock;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001333 b->b_instr[off].i_lineno = c->u->u_lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001334}
1335
1336static int
1337opcode_stack_effect(int opcode, int oparg)
1338{
1339 switch (opcode) {
1340 case POP_TOP:
1341 return -1;
1342 case ROT_TWO:
1343 case ROT_THREE:
1344 return 0;
1345 case DUP_TOP:
1346 return 1;
1347 case ROT_FOUR:
1348 return 0;
1349
1350 case UNARY_POSITIVE:
1351 case UNARY_NEGATIVE:
1352 case UNARY_NOT:
1353 case UNARY_CONVERT:
1354 case UNARY_INVERT:
1355 return 0;
1356
Neal Norwitz10be2ea2006-03-03 20:29:11 +00001357 case LIST_APPEND:
1358 return -2;
1359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 case BINARY_POWER:
1361 case BINARY_MULTIPLY:
1362 case BINARY_DIVIDE:
1363 case BINARY_MODULO:
1364 case BINARY_ADD:
1365 case BINARY_SUBTRACT:
1366 case BINARY_SUBSCR:
1367 case BINARY_FLOOR_DIVIDE:
1368 case BINARY_TRUE_DIVIDE:
1369 return -1;
1370 case INPLACE_FLOOR_DIVIDE:
1371 case INPLACE_TRUE_DIVIDE:
1372 return -1;
1373
1374 case SLICE+0:
1375 return 1;
1376 case SLICE+1:
1377 return 0;
1378 case SLICE+2:
1379 return 0;
1380 case SLICE+3:
1381 return -1;
1382
1383 case STORE_SLICE+0:
1384 return -2;
1385 case STORE_SLICE+1:
1386 return -3;
1387 case STORE_SLICE+2:
1388 return -3;
1389 case STORE_SLICE+3:
1390 return -4;
1391
1392 case DELETE_SLICE+0:
1393 return -1;
1394 case DELETE_SLICE+1:
1395 return -2;
1396 case DELETE_SLICE+2:
1397 return -2;
1398 case DELETE_SLICE+3:
1399 return -3;
1400
1401 case INPLACE_ADD:
1402 case INPLACE_SUBTRACT:
1403 case INPLACE_MULTIPLY:
1404 case INPLACE_DIVIDE:
1405 case INPLACE_MODULO:
1406 return -1;
1407 case STORE_SUBSCR:
1408 return -3;
1409 case DELETE_SUBSCR:
1410 return -2;
1411
1412 case BINARY_LSHIFT:
1413 case BINARY_RSHIFT:
1414 case BINARY_AND:
1415 case BINARY_XOR:
1416 case BINARY_OR:
1417 return -1;
1418 case INPLACE_POWER:
1419 return -1;
1420 case GET_ITER:
1421 return 0;
1422
1423 case PRINT_EXPR:
1424 return -1;
1425 case PRINT_ITEM:
1426 return -1;
1427 case PRINT_NEWLINE:
1428 return 0;
1429 case PRINT_ITEM_TO:
1430 return -2;
1431 case PRINT_NEWLINE_TO:
1432 return -1;
1433 case INPLACE_LSHIFT:
1434 case INPLACE_RSHIFT:
1435 case INPLACE_AND:
1436 case INPLACE_XOR:
1437 case INPLACE_OR:
1438 return -1;
1439 case BREAK_LOOP:
1440 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00001441 case WITH_CLEANUP:
Guido van Rossumf6694362006-03-10 02:28:35 +00001442 return -1; /* XXX Sometimes more */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 case LOAD_LOCALS:
1444 return 1;
1445 case RETURN_VALUE:
1446 return -1;
1447 case IMPORT_STAR:
1448 return -1;
1449 case EXEC_STMT:
1450 return -3;
1451 case YIELD_VALUE:
1452 return 0;
1453
1454 case POP_BLOCK:
1455 return 0;
1456 case END_FINALLY:
1457 return -1; /* or -2 or -3 if exception occurred */
1458 case BUILD_CLASS:
1459 return -2;
1460
1461 case STORE_NAME:
1462 return -1;
1463 case DELETE_NAME:
1464 return 0;
1465 case UNPACK_SEQUENCE:
1466 return oparg-1;
1467 case FOR_ITER:
1468 return 1;
1469
1470 case STORE_ATTR:
1471 return -2;
1472 case DELETE_ATTR:
1473 return -1;
1474 case STORE_GLOBAL:
1475 return -1;
1476 case DELETE_GLOBAL:
1477 return 0;
1478 case DUP_TOPX:
1479 return oparg;
1480 case LOAD_CONST:
1481 return 1;
1482 case LOAD_NAME:
1483 return 1;
1484 case BUILD_TUPLE:
1485 case BUILD_LIST:
1486 return 1-oparg;
1487 case BUILD_MAP:
1488 return 1;
1489 case LOAD_ATTR:
1490 return 0;
1491 case COMPARE_OP:
1492 return -1;
1493 case IMPORT_NAME:
1494 return 0;
1495 case IMPORT_FROM:
1496 return 1;
1497
1498 case JUMP_FORWARD:
1499 case JUMP_IF_FALSE:
1500 case JUMP_IF_TRUE:
1501 case JUMP_ABSOLUTE:
1502 return 0;
1503
1504 case LOAD_GLOBAL:
1505 return 1;
1506
1507 case CONTINUE_LOOP:
1508 return 0;
1509 case SETUP_LOOP:
1510 return 0;
1511 case SETUP_EXCEPT:
1512 case SETUP_FINALLY:
1513 return 3; /* actually pushed by an exception */
1514
1515 case LOAD_FAST:
1516 return 1;
1517 case STORE_FAST:
1518 return -1;
1519 case DELETE_FAST:
1520 return 0;
1521
1522 case RAISE_VARARGS:
1523 return -oparg;
1524#define NARGS(o) (((o) % 256) + 2*((o) / 256))
1525 case CALL_FUNCTION:
1526 return -NARGS(oparg);
1527 case CALL_FUNCTION_VAR:
1528 case CALL_FUNCTION_KW:
1529 return -NARGS(oparg)-1;
1530 case CALL_FUNCTION_VAR_KW:
1531 return -NARGS(oparg)-2;
1532#undef NARGS
1533 case MAKE_FUNCTION:
1534 return -oparg;
1535 case BUILD_SLICE:
1536 if (oparg == 3)
1537 return -2;
1538 else
1539 return -1;
1540
1541 case MAKE_CLOSURE:
1542 return -oparg;
1543 case LOAD_CLOSURE:
1544 return 1;
1545 case LOAD_DEREF:
1546 return 1;
1547 case STORE_DEREF:
1548 return -1;
1549 default:
1550 fprintf(stderr, "opcode = %d\n", opcode);
1551 Py_FatalError("opcode_stack_effect()");
1552
1553 }
1554 return 0; /* not reachable */
1555}
1556
1557/* Add an opcode with no argument.
1558 Returns 0 on failure, 1 on success.
1559*/
1560
1561static int
1562compiler_addop(struct compiler *c, int opcode)
1563{
1564 basicblock *b;
1565 struct instr *i;
1566 int off;
1567 off = compiler_next_instr(c, c->u->u_curblock);
1568 if (off < 0)
1569 return 0;
1570 b = c->u->u_curblock;
1571 i = &b->b_instr[off];
1572 i->i_opcode = opcode;
1573 i->i_hasarg = 0;
1574 if (opcode == RETURN_VALUE)
1575 b->b_return = 1;
1576 compiler_set_lineno(c, off);
1577 return 1;
1578}
1579
1580static int
1581compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
1582{
1583 PyObject *t, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001584 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001585
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001586 /* necessary to make sure types aren't coerced (e.g., int and long) */
Mark Dickinson2bebadf2008-01-21 21:54:47 +00001587 /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
1588 if (PyFloat_Check(o)) {
1589 double d = PyFloat_AS_DOUBLE(o);
1590 unsigned char* p = (unsigned char*) &d;
1591 /* all we need is to make the tuple different in either the 0.0
1592 * or -0.0 case from all others, just to avoid the "coercion".
1593 */
1594 if (*p==0 && p[sizeof(double)-1]==0)
1595 t = PyTuple_Pack(3, o, o->ob_type, Py_None);
1596 else
1597 t = PyTuple_Pack(2, o, o->ob_type);
1598 } else {
1599 t = PyTuple_Pack(2, o, o->ob_type);
1600 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001601 if (t == NULL)
1602 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603
1604 v = PyDict_GetItem(dict, t);
1605 if (!v) {
1606 arg = PyDict_Size(dict);
1607 v = PyInt_FromLong(arg);
1608 if (!v) {
1609 Py_DECREF(t);
1610 return -1;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001611 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612 if (PyDict_SetItem(dict, t, v) < 0) {
1613 Py_DECREF(t);
1614 Py_DECREF(v);
1615 return -1;
1616 }
1617 Py_DECREF(v);
1618 }
1619 else
1620 arg = PyInt_AsLong(v);
1621 Py_DECREF(t);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001622 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001623}
1624
1625static int
1626compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
1627 PyObject *o)
1628{
1629 int arg = compiler_add_o(c, dict, o);
1630 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001631 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632 return compiler_addop_i(c, opcode, arg);
1633}
1634
1635static int
1636compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001637 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638{
1639 int arg;
1640 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1641 if (!mangled)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001642 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643 arg = compiler_add_o(c, dict, mangled);
1644 Py_DECREF(mangled);
1645 if (arg < 0)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001646 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647 return compiler_addop_i(c, opcode, arg);
1648}
1649
1650/* Add an opcode with an integer argument.
1651 Returns 0 on failure, 1 on success.
1652*/
1653
1654static int
1655compiler_addop_i(struct compiler *c, int opcode, int oparg)
1656{
1657 struct instr *i;
1658 int off;
1659 off = compiler_next_instr(c, c->u->u_curblock);
1660 if (off < 0)
1661 return 0;
1662 i = &c->u->u_curblock->b_instr[off];
1663 i->i_opcode = opcode;
1664 i->i_oparg = oparg;
1665 i->i_hasarg = 1;
1666 compiler_set_lineno(c, off);
1667 return 1;
1668}
1669
1670static int
1671compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
1672{
1673 struct instr *i;
1674 int off;
1675
1676 assert(b != NULL);
1677 off = compiler_next_instr(c, c->u->u_curblock);
1678 if (off < 0)
1679 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680 i = &c->u->u_curblock->b_instr[off];
1681 i->i_opcode = opcode;
1682 i->i_target = b;
1683 i->i_hasarg = 1;
1684 if (absolute)
1685 i->i_jabs = 1;
1686 else
1687 i->i_jrel = 1;
Jeremy Hylton12603c42006-04-01 16:18:02 +00001688 compiler_set_lineno(c, off);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689 return 1;
1690}
1691
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001692/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
1693 like to find better names.) NEW_BLOCK() creates a new block and sets
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 it as the current block. NEXT_BLOCK() also creates an implicit jump
1695 from the current block to the new block.
1696*/
1697
1698/* XXX The returns inside these macros make it impossible to decref
1699 objects created in the local function.
1700*/
1701
1702
1703#define NEW_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001704 if (compiler_use_new_block((C)) == NULL) \
1705 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706}
1707
1708#define NEXT_BLOCK(C) { \
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001709 if (compiler_next_block((C)) == NULL) \
1710 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711}
1712
1713#define ADDOP(C, OP) { \
1714 if (!compiler_addop((C), (OP))) \
1715 return 0; \
1716}
1717
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001718#define ADDOP_IN_SCOPE(C, OP) { \
1719 if (!compiler_addop((C), (OP))) { \
1720 compiler_exit_scope(c); \
1721 return 0; \
1722 } \
1723}
1724
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001725#define ADDOP_O(C, OP, O, TYPE) { \
1726 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1727 return 0; \
1728}
1729
1730#define ADDOP_NAME(C, OP, O, TYPE) { \
1731 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1732 return 0; \
1733}
1734
1735#define ADDOP_I(C, OP, O) { \
1736 if (!compiler_addop_i((C), (OP), (O))) \
1737 return 0; \
1738}
1739
1740#define ADDOP_JABS(C, OP, O) { \
1741 if (!compiler_addop_j((C), (OP), (O), 1)) \
1742 return 0; \
1743}
1744
1745#define ADDOP_JREL(C, OP, O) { \
1746 if (!compiler_addop_j((C), (OP), (O), 0)) \
1747 return 0; \
1748}
1749
1750/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1751 the ASDL name to synthesize the name of the C type and the visit function.
1752*/
1753
1754#define VISIT(C, TYPE, V) {\
1755 if (!compiler_visit_ ## TYPE((C), (V))) \
1756 return 0; \
1757}
1758
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001759#define VISIT_IN_SCOPE(C, TYPE, V) {\
1760 if (!compiler_visit_ ## TYPE((C), (V))) { \
1761 compiler_exit_scope(c); \
1762 return 0; \
1763 } \
1764}
1765
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001766#define VISIT_SLICE(C, V, CTX) {\
1767 if (!compiler_visit_slice((C), (V), (CTX))) \
1768 return 0; \
1769}
1770
1771#define VISIT_SEQ(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001772 int _i; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001774 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001775 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001776 if (!compiler_visit_ ## TYPE((C), elt)) \
1777 return 0; \
1778 } \
1779}
1780
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001781#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001782 int _i; \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001783 asdl_seq *seq = (SEQ); /* avoid variable capture */ \
Neal Norwitz08b401f2006-01-07 21:24:09 +00001784 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001785 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
Anthony Baxter7b782b62006-04-11 12:01:56 +00001786 if (!compiler_visit_ ## TYPE((C), elt)) { \
1787 compiler_exit_scope(c); \
1788 return 0; \
1789 } \
1790 } \
1791}
1792
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793static int
1794compiler_isdocstring(stmt_ty s)
1795{
1796 if (s->kind != Expr_kind)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001797 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798 return s->v.Expr.value->kind == Str_kind;
1799}
1800
1801/* Compile a sequence of statements, checking for a docstring. */
1802
1803static int
1804compiler_body(struct compiler *c, asdl_seq *stmts)
1805{
1806 int i = 0;
1807 stmt_ty st;
1808
1809 if (!asdl_seq_LEN(stmts))
1810 return 1;
Anthony Baxter7b782b62006-04-11 12:01:56 +00001811 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Georg Brandlba871a02007-06-01 11:33:45 +00001812 if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
1813 /* don't generate docstrings if -OO */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 i = 1;
1815 VISIT(c, expr, st->v.Expr.value);
1816 if (!compiler_nameop(c, __doc__, Store))
1817 return 0;
1818 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001819 for (; i < asdl_seq_LEN(stmts); i++)
Anthony Baxter7b782b62006-04-11 12:01:56 +00001820 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 return 1;
1822}
1823
1824static PyCodeObject *
1825compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001826{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001827 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001828 int addNone = 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829 static PyObject *module;
1830 if (!module) {
1831 module = PyString_FromString("<module>");
1832 if (!module)
1833 return NULL;
1834 }
Neal Norwitzed657552006-07-10 00:04:44 +00001835 /* Use 0 for firstlineno initially, will fixup in assemble(). */
1836 if (!compiler_enter_scope(c, module, mod, 0))
Guido van Rossumd076c731998-10-07 19:42:25 +00001837 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838 switch (mod->kind) {
1839 case Module_kind:
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001840 if (!compiler_body(c, mod->v.Module.body)) {
1841 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00001843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001844 break;
1845 case Interactive_kind:
1846 c->c_interactive = 1;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00001847 VISIT_SEQ_IN_SCOPE(c, stmt,
1848 mod->v.Interactive.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 break;
1850 case Expression_kind:
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001851 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001852 addNone = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853 break;
1854 case Suite_kind:
Neal Norwitz4737b232005-11-19 23:58:29 +00001855 PyErr_SetString(PyExc_SystemError,
1856 "suite should not be possible");
1857 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001858 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00001859 PyErr_Format(PyExc_SystemError,
1860 "module kind %d should not be possible",
1861 mod->kind);
1862 return 0;
Guido van Rossumd076c731998-10-07 19:42:25 +00001863 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864 co = assemble(c, addNone);
1865 compiler_exit_scope(c);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001866 return co;
1867}
1868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869/* The test for LOCAL must come before the test for FREE in order to
1870 handle classes where name is both local and free. The local var is
1871 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001872*/
1873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874static int
1875get_ref_type(struct compiler *c, PyObject *name)
1876{
1877 int scope = PyST_GetScope(c->u->u_ste, name);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001878 if (scope == 0) {
1879 char buf[350];
1880 PyOS_snprintf(buf, sizeof(buf),
1881 "unknown scope for %.100s in %.100s(%s) in %s\n"
1882 "symbols: %s\nlocals: %s\nglobals: %s\n",
1883 PyString_AS_STRING(name),
1884 PyString_AS_STRING(c->u->u_name),
1885 PyObject_REPR(c->u->u_ste->ste_id),
1886 c->c_filename,
1887 PyObject_REPR(c->u->u_ste->ste_symbols),
1888 PyObject_REPR(c->u->u_varnames),
1889 PyObject_REPR(c->u->u_names)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890 );
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001891 Py_FatalError(buf);
1892 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001893
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001894 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001895}
1896
1897static int
1898compiler_lookup_arg(PyObject *dict, PyObject *name)
1899{
1900 PyObject *k, *v;
Georg Brandl7784f122006-05-26 20:04:44 +00001901 k = PyTuple_Pack(2, name, name->ob_type);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001902 if (k == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001903 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904 v = PyDict_GetItem(dict, k);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00001905 Py_DECREF(k);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906 if (v == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001907 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908 return PyInt_AS_LONG(v);
1909}
1910
1911static int
1912compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
1913{
1914 int i, free = PyCode_GetNumFree(co);
1915 if (free == 0) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001916 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
1917 ADDOP_I(c, MAKE_FUNCTION, args);
1918 return 1;
1919 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 for (i = 0; i < free; ++i) {
1921 /* Bypass com_addop_varname because it will generate
1922 LOAD_DEREF but LOAD_CLOSURE is needed.
1923 */
1924 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1925 int arg, reftype;
1926
1927 /* Special case: If a class contains a method with a
1928 free variable that has the same name as a method,
1929 the name will be considered free *and* local in the
1930 class. It should be handled by the closure, as
1931 well as by the normal name loookup logic.
1932 */
1933 reftype = get_ref_type(c, name);
1934 if (reftype == CELL)
1935 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1936 else /* (reftype == FREE) */
1937 arg = compiler_lookup_arg(c->u->u_freevars, name);
1938 if (arg == -1) {
1939 printf("lookup %s in %s %d %d\n"
1940 "freevars of %s: %s\n",
1941 PyObject_REPR(name),
1942 PyString_AS_STRING(c->u->u_name),
1943 reftype, arg,
1944 PyString_AS_STRING(co->co_name),
1945 PyObject_REPR(co->co_freevars));
1946 Py_FatalError("compiler_make_closure()");
1947 }
1948 ADDOP_I(c, LOAD_CLOSURE, arg);
1949 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001950 ADDOP_I(c, BUILD_TUPLE, free);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951 ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001952 ADDOP_I(c, MAKE_CLOSURE, args);
1953 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954}
1955
1956static int
1957compiler_decorators(struct compiler *c, asdl_seq* decos)
1958{
1959 int i;
1960
1961 if (!decos)
1962 return 1;
1963
1964 for (i = 0; i < asdl_seq_LEN(decos); i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001965 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966 }
1967 return 1;
1968}
1969
1970static int
1971compiler_arguments(struct compiler *c, arguments_ty args)
1972{
1973 int i;
1974 int n = asdl_seq_LEN(args->args);
1975 /* Correctly handle nested argument lists */
1976 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00001977 expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978 if (arg->kind == Tuple_kind) {
1979 PyObject *id = PyString_FromFormat(".%d", i);
1980 if (id == NULL) {
1981 return 0;
1982 }
1983 if (!compiler_nameop(c, id, Load)) {
1984 Py_DECREF(id);
1985 return 0;
1986 }
1987 Py_DECREF(id);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001988 VISIT(c, expr, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 }
1990 }
1991 return 1;
1992}
1993
1994static int
1995compiler_function(struct compiler *c, stmt_ty s)
1996{
1997 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00001998 PyObject *first_const = Py_None;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999 arguments_ty args = s->v.FunctionDef.args;
2000 asdl_seq* decos = s->v.FunctionDef.decorators;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002001 stmt_ty st;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002002 int i, n, docstring;
2003
2004 assert(s->kind == FunctionDef_kind);
2005
2006 if (!compiler_decorators(c, decos))
2007 return 0;
2008 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002009 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010 if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
2011 s->lineno))
2012 return 0;
2013
Anthony Baxter7b782b62006-04-11 12:01:56 +00002014 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002015 docstring = compiler_isdocstring(st);
Georg Brandldfecfdb2007-09-19 06:37:26 +00002016 if (docstring && Py_OptimizeFlag < 2)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002017 first_const = st->v.Expr.value->v.Str.s;
2018 if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002019 compiler_exit_scope(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002020 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002021 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002023 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002024 compiler_arguments(c, args);
2025
2026 c->u->u_argcount = asdl_seq_LEN(args->args);
2027 n = asdl_seq_LEN(s->v.FunctionDef.body);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002028 /* if there was a docstring, we need to skip the first statement */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002029 for (i = docstring; i < n; i++) {
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002030 st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
2031 VISIT_IN_SCOPE(c, stmt, st);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032 }
2033 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002034 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002035 if (co == NULL)
2036 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002037
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002038 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002039 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002040
2041 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2042 ADDOP_I(c, CALL_FUNCTION, 1);
2043 }
2044
2045 return compiler_nameop(c, s->v.FunctionDef.name, Store);
2046}
2047
2048static int
2049compiler_class(struct compiler *c, stmt_ty s)
2050{
2051 int n;
2052 PyCodeObject *co;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002053 PyObject *str;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002054 /* push class name on stack, needed by BUILD_CLASS */
2055 ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
2056 /* push the tuple of base classes on the stack */
2057 n = asdl_seq_LEN(s->v.ClassDef.bases);
2058 if (n > 0)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002059 VISIT_SEQ(c, expr, s->v.ClassDef.bases);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060 ADDOP_I(c, BUILD_TUPLE, n);
2061 if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
2062 s->lineno))
2063 return 0;
Amaury Forgeot d'Arc8432d862008-03-28 20:45:42 +00002064 Py_XDECREF(c->u->u_private);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002065 c->u->u_private = s->v.ClassDef.name;
2066 Py_INCREF(c->u->u_private);
2067 str = PyString_InternFromString("__name__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002068 if (!str || !compiler_nameop(c, str, Load)) {
2069 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002070 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002072 }
2073
2074 Py_DECREF(str);
2075 str = PyString_InternFromString("__module__");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076 if (!str || !compiler_nameop(c, str, Store)) {
2077 Py_XDECREF(str);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002078 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002080 }
2081 Py_DECREF(str);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002082
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002083 if (!compiler_body(c, s->v.ClassDef.body)) {
2084 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002085 return 0;
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002086 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002088 ADDOP_IN_SCOPE(c, LOAD_LOCALS);
2089 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002090 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002091 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092 if (co == NULL)
2093 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002094
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002095 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00002096 Py_DECREF(co);
2097
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002098 ADDOP_I(c, CALL_FUNCTION, 0);
2099 ADDOP(c, BUILD_CLASS);
2100 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2101 return 0;
2102 return 1;
2103}
2104
2105static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002106compiler_ifexp(struct compiler *c, expr_ty e)
2107{
2108 basicblock *end, *next;
2109
2110 assert(e->kind == IfExp_kind);
2111 end = compiler_new_block(c);
2112 if (end == NULL)
2113 return 0;
2114 next = compiler_new_block(c);
2115 if (next == NULL)
2116 return 0;
2117 VISIT(c, expr, e->v.IfExp.test);
2118 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2119 ADDOP(c, POP_TOP);
2120 VISIT(c, expr, e->v.IfExp.body);
2121 ADDOP_JREL(c, JUMP_FORWARD, end);
2122 compiler_use_next_block(c, next);
2123 ADDOP(c, POP_TOP);
2124 VISIT(c, expr, e->v.IfExp.orelse);
2125 compiler_use_next_block(c, end);
2126 return 1;
2127}
2128
2129static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130compiler_lambda(struct compiler *c, expr_ty e)
2131{
2132 PyCodeObject *co;
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002133 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134 arguments_ty args = e->v.Lambda.args;
2135 assert(e->kind == Lambda_kind);
2136
Nick Coghlan944d3eb2005-11-16 12:46:55 +00002137 if (!name) {
2138 name = PyString_InternFromString("<lambda>");
2139 if (!name)
2140 return 0;
2141 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002142
2143 if (args->defaults)
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002144 VISIT_SEQ(c, expr, args->defaults);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002145 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
2146 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002147
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002148 /* unpack nested arguments */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149 compiler_arguments(c, args);
2150
2151 c->u->u_argcount = asdl_seq_LEN(args->args);
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00002152 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2153 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00002155 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002156 if (co == NULL)
2157 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002159 compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
Neal Norwitz4737b232005-11-19 23:58:29 +00002160 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002161
2162 return 1;
2163}
2164
2165static int
2166compiler_print(struct compiler *c, stmt_ty s)
2167{
2168 int i, n;
2169 bool dest;
2170
2171 assert(s->kind == Print_kind);
2172 n = asdl_seq_LEN(s->v.Print.values);
2173 dest = false;
2174 if (s->v.Print.dest) {
2175 VISIT(c, expr, s->v.Print.dest);
2176 dest = true;
2177 }
2178 for (i = 0; i < n; i++) {
2179 expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
2180 if (dest) {
2181 ADDOP(c, DUP_TOP);
2182 VISIT(c, expr, e);
2183 ADDOP(c, ROT_TWO);
2184 ADDOP(c, PRINT_ITEM_TO);
2185 }
2186 else {
2187 VISIT(c, expr, e);
2188 ADDOP(c, PRINT_ITEM);
2189 }
2190 }
2191 if (s->v.Print.nl) {
2192 if (dest)
2193 ADDOP(c, PRINT_NEWLINE_TO)
2194 else
2195 ADDOP(c, PRINT_NEWLINE)
2196 }
2197 else if (dest)
2198 ADDOP(c, POP_TOP);
2199 return 1;
2200}
2201
2202static int
2203compiler_if(struct compiler *c, stmt_ty s)
2204{
2205 basicblock *end, *next;
Georg Brandlddbaa662006-06-04 21:56:52 +00002206 int constant;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002207 assert(s->kind == If_kind);
2208 end = compiler_new_block(c);
2209 if (end == NULL)
2210 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002211 next = compiler_new_block(c);
2212 if (next == NULL)
2213 return 0;
Georg Brandlddbaa662006-06-04 21:56:52 +00002214
2215 constant = expr_constant(s->v.If.test);
2216 /* constant = 0: "if 0"
2217 * constant = 1: "if 1", "if 2", ...
2218 * constant = -1: rest */
2219 if (constant == 0) {
2220 if (s->v.If.orelse)
2221 VISIT_SEQ(c, stmt, s->v.If.orelse);
2222 } else if (constant == 1) {
2223 VISIT_SEQ(c, stmt, s->v.If.body);
2224 } else {
2225 VISIT(c, expr, s->v.If.test);
2226 ADDOP_JREL(c, JUMP_IF_FALSE, next);
2227 ADDOP(c, POP_TOP);
2228 VISIT_SEQ(c, stmt, s->v.If.body);
2229 ADDOP_JREL(c, JUMP_FORWARD, end);
2230 compiler_use_next_block(c, next);
2231 ADDOP(c, POP_TOP);
2232 if (s->v.If.orelse)
2233 VISIT_SEQ(c, stmt, s->v.If.orelse);
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235 compiler_use_next_block(c, end);
2236 return 1;
2237}
2238
2239static int
2240compiler_for(struct compiler *c, stmt_ty s)
2241{
2242 basicblock *start, *cleanup, *end;
2243
2244 start = compiler_new_block(c);
2245 cleanup = compiler_new_block(c);
2246 end = compiler_new_block(c);
2247 if (start == NULL || end == NULL || cleanup == NULL)
2248 return 0;
2249 ADDOP_JREL(c, SETUP_LOOP, end);
2250 if (!compiler_push_fblock(c, LOOP, start))
2251 return 0;
2252 VISIT(c, expr, s->v.For.iter);
2253 ADDOP(c, GET_ITER);
2254 compiler_use_next_block(c, start);
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002255 /* for expressions must be traced on each iteration,
2256 so we need to set an extra line number. */
Neal Norwitz4ffedad2006-08-04 04:58:47 +00002257 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258 ADDOP_JREL(c, FOR_ITER, cleanup);
2259 VISIT(c, expr, s->v.For.target);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002260 VISIT_SEQ(c, stmt, s->v.For.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002261 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
2262 compiler_use_next_block(c, cleanup);
2263 ADDOP(c, POP_BLOCK);
2264 compiler_pop_fblock(c, LOOP, start);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002265 VISIT_SEQ(c, stmt, s->v.For.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266 compiler_use_next_block(c, end);
2267 return 1;
2268}
2269
2270static int
2271compiler_while(struct compiler *c, stmt_ty s)
2272{
2273 basicblock *loop, *orelse, *end, *anchor = NULL;
2274 int constant = expr_constant(s->v.While.test);
2275
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002276 if (constant == 0) {
2277 if (s->v.While.orelse)
2278 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279 return 1;
Amaury Forgeot d'Arcf1a71782008-01-24 23:42:08 +00002280 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281 loop = compiler_new_block(c);
2282 end = compiler_new_block(c);
2283 if (constant == -1) {
2284 anchor = compiler_new_block(c);
2285 if (anchor == NULL)
2286 return 0;
2287 }
2288 if (loop == NULL || end == NULL)
2289 return 0;
2290 if (s->v.While.orelse) {
2291 orelse = compiler_new_block(c);
2292 if (orelse == NULL)
2293 return 0;
2294 }
2295 else
2296 orelse = NULL;
2297
2298 ADDOP_JREL(c, SETUP_LOOP, end);
2299 compiler_use_next_block(c, loop);
2300 if (!compiler_push_fblock(c, LOOP, loop))
2301 return 0;
2302 if (constant == -1) {
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002303 /* while expressions must be traced on each iteration,
2304 so we need to set an extra line number. */
2305 c->u->u_lineno_set = false;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306 VISIT(c, expr, s->v.While.test);
2307 ADDOP_JREL(c, JUMP_IF_FALSE, anchor);
2308 ADDOP(c, POP_TOP);
2309 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002310 VISIT_SEQ(c, stmt, s->v.While.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311 ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
2312
2313 /* XXX should the two POP instructions be in a separate block
2314 if there is no else clause ?
2315 */
2316
2317 if (constant == -1) {
2318 compiler_use_next_block(c, anchor);
2319 ADDOP(c, POP_TOP);
2320 ADDOP(c, POP_BLOCK);
2321 }
2322 compiler_pop_fblock(c, LOOP, loop);
Jeremy Hylton12603c42006-04-01 16:18:02 +00002323 if (orelse != NULL) /* what if orelse is just pass? */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002324 VISIT_SEQ(c, stmt, s->v.While.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325 compiler_use_next_block(c, end);
2326
2327 return 1;
2328}
2329
2330static int
2331compiler_continue(struct compiler *c)
2332{
2333 static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
Georg Brandl74284b92006-10-08 07:06:29 +00002334 static const char IN_FINALLY_ERROR_MSG[] =
2335 "'continue' not supported inside 'finally' clause";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002336 int i;
2337
2338 if (!c->u->u_nfblocks)
2339 return compiler_error(c, LOOP_ERROR_MSG);
2340 i = c->u->u_nfblocks - 1;
2341 switch (c->u->u_fblock[i].fb_type) {
2342 case LOOP:
2343 ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
2344 break;
2345 case EXCEPT:
2346 case FINALLY_TRY:
Georg Brandl74284b92006-10-08 07:06:29 +00002347 while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
2348 /* Prevent try: ... finally:
2349 try: continue ... or
2350 try: ... except: continue */
2351 if (c->u->u_fblock[i].fb_type == FINALLY_END)
2352 return compiler_error(c, IN_FINALLY_ERROR_MSG);
2353 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354 if (i == -1)
2355 return compiler_error(c, LOOP_ERROR_MSG);
2356 ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
2357 break;
2358 case FINALLY_END:
Georg Brandl74284b92006-10-08 07:06:29 +00002359 return compiler_error(c, IN_FINALLY_ERROR_MSG);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360 }
2361
2362 return 1;
2363}
2364
2365/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2366
2367 SETUP_FINALLY L
2368 <code for body>
2369 POP_BLOCK
2370 LOAD_CONST <None>
2371 L: <code for finalbody>
2372 END_FINALLY
2373
2374 The special instructions use the block stack. Each block
2375 stack entry contains the instruction that created it (here
2376 SETUP_FINALLY), the level of the value stack at the time the
2377 block stack entry was created, and a label (here L).
2378
2379 SETUP_FINALLY:
2380 Pushes the current value stack level and the label
2381 onto the block stack.
2382 POP_BLOCK:
2383 Pops en entry from the block stack, and pops the value
2384 stack until its level is the same as indicated on the
2385 block stack. (The label is ignored.)
2386 END_FINALLY:
2387 Pops a variable number of entries from the *value* stack
2388 and re-raises the exception they specify. The number of
2389 entries popped depends on the (pseudo) exception type.
2390
2391 The block stack is unwound when an exception is raised:
2392 when a SETUP_FINALLY entry is found, the exception is pushed
2393 onto the value stack (and the exception condition is cleared),
2394 and the interpreter jumps to the label gotten from the block
2395 stack.
2396*/
2397
2398static int
2399compiler_try_finally(struct compiler *c, stmt_ty s)
2400{
2401 basicblock *body, *end;
2402 body = compiler_new_block(c);
2403 end = compiler_new_block(c);
2404 if (body == NULL || end == NULL)
2405 return 0;
2406
2407 ADDOP_JREL(c, SETUP_FINALLY, end);
2408 compiler_use_next_block(c, body);
2409 if (!compiler_push_fblock(c, FINALLY_TRY, body))
2410 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002411 VISIT_SEQ(c, stmt, s->v.TryFinally.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412 ADDOP(c, POP_BLOCK);
2413 compiler_pop_fblock(c, FINALLY_TRY, body);
2414
2415 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2416 compiler_use_next_block(c, end);
2417 if (!compiler_push_fblock(c, FINALLY_END, end))
2418 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002419 VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420 ADDOP(c, END_FINALLY);
2421 compiler_pop_fblock(c, FINALLY_END, end);
2422
2423 return 1;
2424}
2425
2426/*
2427 Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
2428 (The contents of the value stack is shown in [], with the top
2429 at the right; 'tb' is trace-back info, 'val' the exception's
2430 associated value, and 'exc' the exception.)
2431
2432 Value stack Label Instruction Argument
2433 [] SETUP_EXCEPT L1
2434 [] <code for S>
2435 [] POP_BLOCK
2436 [] JUMP_FORWARD L0
2437
2438 [tb, val, exc] L1: DUP )
2439 [tb, val, exc, exc] <evaluate E1> )
2440 [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
2441 [tb, val, exc, 1-or-0] JUMP_IF_FALSE L2 )
2442 [tb, val, exc, 1] POP )
2443 [tb, val, exc] POP
2444 [tb, val] <assign to V1> (or POP if no V1)
2445 [tb] POP
2446 [] <code for S1>
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002447 JUMP_FORWARD L0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002448
2449 [tb, val, exc, 0] L2: POP
2450 [tb, val, exc] DUP
2451 .............................etc.......................
2452
2453 [tb, val, exc, 0] Ln+1: POP
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002454 [tb, val, exc] END_FINALLY # re-raise exception
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002455
2456 [] L0: <next statement>
2457
2458 Of course, parts are not generated if Vi or Ei is not present.
2459*/
2460static int
2461compiler_try_except(struct compiler *c, stmt_ty s)
2462{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002463 basicblock *body, *orelse, *except, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464 int i, n;
2465
2466 body = compiler_new_block(c);
2467 except = compiler_new_block(c);
2468 orelse = compiler_new_block(c);
2469 end = compiler_new_block(c);
2470 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
2471 return 0;
2472 ADDOP_JREL(c, SETUP_EXCEPT, except);
2473 compiler_use_next_block(c, body);
2474 if (!compiler_push_fblock(c, EXCEPT, body))
2475 return 0;
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002476 VISIT_SEQ(c, stmt, s->v.TryExcept.body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002477 ADDOP(c, POP_BLOCK);
2478 compiler_pop_fblock(c, EXCEPT, body);
2479 ADDOP_JREL(c, JUMP_FORWARD, orelse);
2480 n = asdl_seq_LEN(s->v.TryExcept.handlers);
2481 compiler_use_next_block(c, except);
2482 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002483 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002484 s->v.TryExcept.handlers, i);
2485 if (!handler->type && i < n-1)
2486 return compiler_error(c, "default 'except:' must be last");
Amaury Forgeot d'Arc316f8a82008-02-04 22:34:57 +00002487 c->u->u_lineno_set = false;
2488 c->u->u_lineno = handler->lineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002489 except = compiler_new_block(c);
2490 if (except == NULL)
2491 return 0;
2492 if (handler->type) {
2493 ADDOP(c, DUP_TOP);
2494 VISIT(c, expr, handler->type);
2495 ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
2496 ADDOP_JREL(c, JUMP_IF_FALSE, except);
2497 ADDOP(c, POP_TOP);
2498 }
2499 ADDOP(c, POP_TOP);
2500 if (handler->name) {
2501 VISIT(c, expr, handler->name);
2502 }
2503 else {
2504 ADDOP(c, POP_TOP);
2505 }
2506 ADDOP(c, POP_TOP);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002507 VISIT_SEQ(c, stmt, handler->body);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002508 ADDOP_JREL(c, JUMP_FORWARD, end);
2509 compiler_use_next_block(c, except);
2510 if (handler->type)
2511 ADDOP(c, POP_TOP);
2512 }
2513 ADDOP(c, END_FINALLY);
2514 compiler_use_next_block(c, orelse);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002515 VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002516 compiler_use_next_block(c, end);
2517 return 1;
2518}
2519
2520static int
2521compiler_import_as(struct compiler *c, identifier name, identifier asname)
2522{
2523 /* The IMPORT_NAME opcode was already generated. This function
2524 merely needs to bind the result to a name.
2525
2526 If there is a dot in name, we need to split it and emit a
2527 LOAD_ATTR for each name.
2528 */
2529 const char *src = PyString_AS_STRING(name);
2530 const char *dot = strchr(src, '.');
2531 if (dot) {
2532 /* Consume the base module name to get the first attribute */
2533 src = dot + 1;
2534 while (dot) {
2535 /* NB src is only defined when dot != NULL */
Armin Rigo31441302005-10-21 12:57:31 +00002536 PyObject *attr;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002537 dot = strchr(src, '.');
Armin Rigo31441302005-10-21 12:57:31 +00002538 attr = PyString_FromStringAndSize(src,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539 dot ? dot - src : strlen(src));
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002540 if (!attr)
2541 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542 ADDOP_O(c, LOAD_ATTR, attr, names);
Neal Norwitz7bcabc62005-11-20 23:58:38 +00002543 Py_DECREF(attr);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002544 src = dot + 1;
2545 }
2546 }
2547 return compiler_nameop(c, asname, Store);
2548}
2549
2550static int
2551compiler_import(struct compiler *c, stmt_ty s)
2552{
2553 /* The Import node stores a module name like a.b.c as a single
2554 string. This is convenient for all cases except
2555 import a.b.c as d
2556 where we need to parse that string to extract the individual
2557 module names.
2558 XXX Perhaps change the representation to make this case simpler?
2559 */
2560 int i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002562 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002563 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002564 int r;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002565 PyObject *level;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002566
Neal Norwitzcbce2802006-04-03 06:26:32 +00002567 if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002568 level = PyInt_FromLong(0);
2569 else
2570 level = PyInt_FromLong(-1);
2571
2572 if (level == NULL)
2573 return 0;
2574
2575 ADDOP_O(c, LOAD_CONST, level, consts);
2576 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002577 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2578 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
2579
2580 if (alias->asname) {
Neil Schemenauerac699ef2005-10-23 03:45:42 +00002581 r = compiler_import_as(c, alias->name, alias->asname);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002582 if (!r)
2583 return r;
2584 }
2585 else {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002586 identifier tmp = alias->name;
2587 const char *base = PyString_AS_STRING(alias->name);
2588 char *dot = strchr(base, '.');
2589 if (dot)
2590 tmp = PyString_FromStringAndSize(base,
2591 dot - base);
2592 r = compiler_nameop(c, tmp, Store);
2593 if (dot) {
2594 Py_DECREF(tmp);
2595 }
2596 if (!r)
2597 return r;
2598 }
2599 }
2600 return 1;
2601}
2602
2603static int
2604compiler_from_import(struct compiler *c, stmt_ty s)
2605{
2606 int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002607
2608 PyObject *names = PyTuple_New(n);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002609 PyObject *level;
2610
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611 if (!names)
2612 return 0;
2613
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002614 if (s->v.ImportFrom.level == 0 && c->c_flags &&
Neal Norwitzcbce2802006-04-03 06:26:32 +00002615 !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002616 level = PyInt_FromLong(-1);
2617 else
2618 level = PyInt_FromLong(s->v.ImportFrom.level);
2619
2620 if (!level) {
2621 Py_DECREF(names);
2622 return 0;
2623 }
2624
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625 /* build up the names */
2626 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002627 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628 Py_INCREF(alias->name);
2629 PyTuple_SET_ITEM(names, i, alias->name);
2630 }
2631
2632 if (s->lineno > c->c_future->ff_lineno) {
2633 if (!strcmp(PyString_AS_STRING(s->v.ImportFrom.module),
2634 "__future__")) {
Neal Norwitzd9cf85f2006-03-02 08:08:42 +00002635 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636 Py_DECREF(names);
2637 return compiler_error(c,
2638 "from __future__ imports must occur "
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002639 "at the beginning of the file");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002640
2641 }
2642 }
2643
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002644 ADDOP_O(c, LOAD_CONST, level, consts);
2645 Py_DECREF(level);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002646 ADDOP_O(c, LOAD_CONST, names, consts);
Neal Norwitz3715c3e2005-11-24 22:09:18 +00002647 Py_DECREF(names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
2649 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00002650 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651 identifier store_name;
2652
2653 if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
2654 assert(n == 1);
2655 ADDOP(c, IMPORT_STAR);
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002656 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657 }
2658
2659 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
2660 store_name = alias->name;
2661 if (alias->asname)
2662 store_name = alias->asname;
2663
2664 if (!compiler_nameop(c, store_name, Store)) {
2665 Py_DECREF(names);
2666 return 0;
2667 }
2668 }
Neal Norwitz28b32ac2005-12-06 07:41:30 +00002669 /* remove imported module */
2670 ADDOP(c, POP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002671 return 1;
2672}
2673
2674static int
2675compiler_assert(struct compiler *c, stmt_ty s)
2676{
2677 static PyObject *assertion_error = NULL;
2678 basicblock *end;
2679
2680 if (Py_OptimizeFlag)
2681 return 1;
2682 if (assertion_error == NULL) {
2683 assertion_error = PyString_FromString("AssertionError");
2684 if (assertion_error == NULL)
2685 return 0;
2686 }
2687 VISIT(c, expr, s->v.Assert.test);
2688 end = compiler_new_block(c);
2689 if (end == NULL)
2690 return 0;
2691 ADDOP_JREL(c, JUMP_IF_TRUE, end);
2692 ADDOP(c, POP_TOP);
2693 ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
2694 if (s->v.Assert.msg) {
2695 VISIT(c, expr, s->v.Assert.msg);
2696 ADDOP_I(c, RAISE_VARARGS, 2);
2697 }
2698 else {
2699 ADDOP_I(c, RAISE_VARARGS, 1);
2700 }
Neal Norwitz51abbc72005-12-18 07:06:23 +00002701 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702 ADDOP(c, POP_TOP);
2703 return 1;
2704}
2705
2706static int
2707compiler_visit_stmt(struct compiler *c, stmt_ty s)
2708{
2709 int i, n;
2710
Jeremy Hylton12603c42006-04-01 16:18:02 +00002711 /* Always assign a lineno to the next instruction for a stmt. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002712 c->u->u_lineno = s->lineno;
2713 c->u->u_lineno_set = false;
Jeremy Hylton12603c42006-04-01 16:18:02 +00002714
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002715 switch (s->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002716 case FunctionDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002717 return compiler_function(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002718 case ClassDef_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002719 return compiler_class(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002720 case Return_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721 if (c->u->u_ste->ste_type != FunctionBlock)
2722 return compiler_error(c, "'return' outside function");
2723 if (s->v.Return.value) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724 VISIT(c, expr, s->v.Return.value);
2725 }
2726 else
2727 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2728 ADDOP(c, RETURN_VALUE);
2729 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002730 case Delete_kind:
Anthony Baxter2c33fc72006-04-12 00:43:09 +00002731 VISIT_SEQ(c, expr, s->v.Delete.targets)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002732 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002733 case Assign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734 n = asdl_seq_LEN(s->v.Assign.targets);
2735 VISIT(c, expr, s->v.Assign.value);
2736 for (i = 0; i < n; i++) {
2737 if (i < n - 1)
2738 ADDOP(c, DUP_TOP);
2739 VISIT(c, expr,
2740 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
2741 }
2742 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002743 case AugAssign_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744 return compiler_augassign(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002745 case Print_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746 return compiler_print(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002747 case For_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002748 return compiler_for(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002749 case While_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750 return compiler_while(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002751 case If_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752 return compiler_if(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002753 case Raise_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002754 n = 0;
2755 if (s->v.Raise.type) {
2756 VISIT(c, expr, s->v.Raise.type);
2757 n++;
2758 if (s->v.Raise.inst) {
2759 VISIT(c, expr, s->v.Raise.inst);
2760 n++;
2761 if (s->v.Raise.tback) {
2762 VISIT(c, expr, s->v.Raise.tback);
2763 n++;
2764 }
2765 }
2766 }
2767 ADDOP_I(c, RAISE_VARARGS, n);
2768 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002769 case TryExcept_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770 return compiler_try_except(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002771 case TryFinally_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772 return compiler_try_finally(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002773 case Assert_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774 return compiler_assert(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002775 case Import_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776 return compiler_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002777 case ImportFrom_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778 return compiler_from_import(c, s);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002779 case Exec_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002780 VISIT(c, expr, s->v.Exec.body);
2781 if (s->v.Exec.globals) {
2782 VISIT(c, expr, s->v.Exec.globals);
2783 if (s->v.Exec.locals) {
2784 VISIT(c, expr, s->v.Exec.locals);
2785 } else {
2786 ADDOP(c, DUP_TOP);
2787 }
2788 } else {
2789 ADDOP_O(c, LOAD_CONST, Py_None, consts);
2790 ADDOP(c, DUP_TOP);
2791 }
2792 ADDOP(c, EXEC_STMT);
2793 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002794 case Global_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002795 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002796 case Expr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002797 if (c->c_interactive && c->c_nestlevel <= 1) {
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002798 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799 ADDOP(c, PRINT_EXPR);
2800 }
Neal Norwitz0cbd8052006-08-04 05:09:28 +00002801 else if (s->v.Expr.value->kind != Str_kind &&
2802 s->v.Expr.value->kind != Num_kind) {
2803 VISIT(c, expr, s->v.Expr.value);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002804 ADDOP(c, POP_TOP);
2805 }
2806 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002807 case Pass_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002808 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002809 case Break_kind:
Georg Brandla5fe3ef2006-10-08 07:12:23 +00002810 if (!compiler_in_loop(c))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002811 return compiler_error(c, "'break' outside loop");
2812 ADDOP(c, BREAK_LOOP);
2813 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002814 case Continue_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815 return compiler_continue(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002816 case With_kind:
2817 return compiler_with(c, s);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002818 }
2819 return 1;
2820}
2821
2822static int
2823unaryop(unaryop_ty op)
2824{
2825 switch (op) {
2826 case Invert:
2827 return UNARY_INVERT;
2828 case Not:
2829 return UNARY_NOT;
2830 case UAdd:
2831 return UNARY_POSITIVE;
2832 case USub:
2833 return UNARY_NEGATIVE;
2834 }
2835 return 0;
2836}
2837
2838static int
2839binop(struct compiler *c, operator_ty op)
2840{
2841 switch (op) {
2842 case Add:
2843 return BINARY_ADD;
2844 case Sub:
2845 return BINARY_SUBTRACT;
2846 case Mult:
2847 return BINARY_MULTIPLY;
2848 case Div:
2849 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2850 return BINARY_TRUE_DIVIDE;
2851 else
2852 return BINARY_DIVIDE;
2853 case Mod:
2854 return BINARY_MODULO;
2855 case Pow:
2856 return BINARY_POWER;
2857 case LShift:
2858 return BINARY_LSHIFT;
2859 case RShift:
2860 return BINARY_RSHIFT;
2861 case BitOr:
2862 return BINARY_OR;
2863 case BitXor:
2864 return BINARY_XOR;
2865 case BitAnd:
2866 return BINARY_AND;
2867 case FloorDiv:
2868 return BINARY_FLOOR_DIVIDE;
2869 }
2870 return 0;
2871}
2872
2873static int
2874cmpop(cmpop_ty op)
2875{
2876 switch (op) {
2877 case Eq:
2878 return PyCmp_EQ;
2879 case NotEq:
2880 return PyCmp_NE;
2881 case Lt:
2882 return PyCmp_LT;
2883 case LtE:
2884 return PyCmp_LE;
2885 case Gt:
2886 return PyCmp_GT;
2887 case GtE:
2888 return PyCmp_GE;
2889 case Is:
2890 return PyCmp_IS;
2891 case IsNot:
2892 return PyCmp_IS_NOT;
2893 case In:
2894 return PyCmp_IN;
2895 case NotIn:
2896 return PyCmp_NOT_IN;
2897 }
2898 return PyCmp_BAD;
2899}
2900
2901static int
2902inplace_binop(struct compiler *c, operator_ty op)
2903{
2904 switch (op) {
2905 case Add:
2906 return INPLACE_ADD;
2907 case Sub:
2908 return INPLACE_SUBTRACT;
2909 case Mult:
2910 return INPLACE_MULTIPLY;
2911 case Div:
2912 if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
2913 return INPLACE_TRUE_DIVIDE;
2914 else
2915 return INPLACE_DIVIDE;
2916 case Mod:
2917 return INPLACE_MODULO;
2918 case Pow:
2919 return INPLACE_POWER;
2920 case LShift:
2921 return INPLACE_LSHIFT;
2922 case RShift:
2923 return INPLACE_RSHIFT;
2924 case BitOr:
2925 return INPLACE_OR;
2926 case BitXor:
2927 return INPLACE_XOR;
2928 case BitAnd:
2929 return INPLACE_AND;
2930 case FloorDiv:
2931 return INPLACE_FLOOR_DIVIDE;
2932 }
Neal Norwitz4737b232005-11-19 23:58:29 +00002933 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002934 "inplace binary op %d should not be possible", op);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 return 0;
2936}
2937
2938static int
2939compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
2940{
Neil Schemenauerdad06a12005-10-23 18:52:36 +00002941 int op, scope, arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
2943
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002944 PyObject *dict = c->u->u_names;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002945 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946 /* XXX AugStore isn't used anywhere! */
2947
2948 /* First check for assignment to __debug__. Param? */
2949 if ((ctx == Store || ctx == AugStore || ctx == Del)
2950 && !strcmp(PyString_AS_STRING(name), "__debug__")) {
2951 return compiler_error(c, "can not assign to __debug__");
2952 }
2953
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002954 mangled = _Py_Mangle(c->u->u_private, name);
2955 if (!mangled)
2956 return 0;
2957
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958 op = 0;
2959 optype = OP_NAME;
Neil Schemenauer8b528b22005-10-23 18:37:42 +00002960 scope = PyST_GetScope(c->u->u_ste, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 switch (scope) {
2962 case FREE:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002963 dict = c->u->u_freevars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 optype = OP_DEREF;
2965 break;
2966 case CELL:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00002967 dict = c->u->u_cellvars;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002968 optype = OP_DEREF;
2969 break;
2970 case LOCAL:
2971 if (c->u->u_ste->ste_type == FunctionBlock)
2972 optype = OP_FAST;
2973 break;
2974 case GLOBAL_IMPLICIT:
Neil Schemenauerd403c452005-10-23 04:24:49 +00002975 if (c->u->u_ste->ste_type == FunctionBlock &&
2976 !c->u->u_ste->ste_unoptimized)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977 optype = OP_GLOBAL;
2978 break;
2979 case GLOBAL_EXPLICIT:
2980 optype = OP_GLOBAL;
2981 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00002982 default:
2983 /* scope can be 0 */
2984 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985 }
2986
2987 /* XXX Leave assert here, but handle __doc__ and the like better */
2988 assert(scope || PyString_AS_STRING(name)[0] == '_');
2989
2990 switch (optype) {
2991 case OP_DEREF:
2992 switch (ctx) {
2993 case Load: op = LOAD_DEREF; break;
2994 case Store: op = STORE_DEREF; break;
2995 case AugLoad:
2996 case AugStore:
2997 break;
2998 case Del:
2999 PyErr_Format(PyExc_SyntaxError,
3000 "can not delete variable '%s' referenced "
3001 "in nested scope",
3002 PyString_AS_STRING(name));
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003003 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003004 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003005 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003006 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003007 PyErr_SetString(PyExc_SystemError,
3008 "param invalid for deref variable");
3009 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010 }
3011 break;
3012 case OP_FAST:
3013 switch (ctx) {
3014 case Load: op = LOAD_FAST; break;
3015 case Store: op = STORE_FAST; break;
3016 case Del: op = DELETE_FAST; break;
3017 case AugLoad:
3018 case AugStore:
3019 break;
3020 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003021 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003022 PyErr_SetString(PyExc_SystemError,
3023 "param invalid for local variable");
3024 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025 }
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003026 ADDOP_O(c, op, mangled, varnames);
3027 Py_DECREF(mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028 return 1;
3029 case OP_GLOBAL:
3030 switch (ctx) {
3031 case Load: op = LOAD_GLOBAL; break;
3032 case Store: op = STORE_GLOBAL; break;
3033 case Del: op = DELETE_GLOBAL; break;
3034 case AugLoad:
3035 case AugStore:
3036 break;
3037 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003038 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003039 PyErr_SetString(PyExc_SystemError,
3040 "param invalid for global variable");
3041 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003042 }
3043 break;
3044 case OP_NAME:
3045 switch (ctx) {
3046 case Load: op = LOAD_NAME; break;
3047 case Store: op = STORE_NAME; break;
3048 case Del: op = DELETE_NAME; break;
3049 case AugLoad:
3050 case AugStore:
3051 break;
3052 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003053 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003054 PyErr_SetString(PyExc_SystemError,
3055 "param invalid for name variable");
3056 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 }
3058 break;
3059 }
3060
3061 assert(op);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003062 arg = compiler_add_o(c, dict, mangled);
Neal Norwitz4737b232005-11-19 23:58:29 +00003063 Py_DECREF(mangled);
Neil Schemenauer8b528b22005-10-23 18:37:42 +00003064 if (arg < 0)
3065 return 0;
Neil Schemenauerdad06a12005-10-23 18:52:36 +00003066 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003067}
3068
3069static int
3070compiler_boolop(struct compiler *c, expr_ty e)
3071{
3072 basicblock *end;
3073 int jumpi, i, n;
3074 asdl_seq *s;
3075
3076 assert(e->kind == BoolOp_kind);
3077 if (e->v.BoolOp.op == And)
3078 jumpi = JUMP_IF_FALSE;
3079 else
3080 jumpi = JUMP_IF_TRUE;
3081 end = compiler_new_block(c);
Martin v. Löwis94962612006-01-02 21:15:05 +00003082 if (end == NULL)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003083 return 0;
3084 s = e->v.BoolOp.values;
3085 n = asdl_seq_LEN(s) - 1;
Neal Norwitzc173b482006-07-30 19:18:13 +00003086 assert(n >= 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003087 for (i = 0; i < n; ++i) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003088 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003089 ADDOP_JREL(c, jumpi, end);
3090 ADDOP(c, POP_TOP)
3091 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003092 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003093 compiler_use_next_block(c, end);
3094 return 1;
3095}
3096
3097static int
3098compiler_list(struct compiler *c, expr_ty e)
3099{
3100 int n = asdl_seq_LEN(e->v.List.elts);
3101 if (e->v.List.ctx == Store) {
3102 ADDOP_I(c, UNPACK_SEQUENCE, n);
3103 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003104 VISIT_SEQ(c, expr, e->v.List.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003105 if (e->v.List.ctx == Load) {
3106 ADDOP_I(c, BUILD_LIST, n);
3107 }
3108 return 1;
3109}
3110
3111static int
3112compiler_tuple(struct compiler *c, expr_ty e)
3113{
3114 int n = asdl_seq_LEN(e->v.Tuple.elts);
3115 if (e->v.Tuple.ctx == Store) {
3116 ADDOP_I(c, UNPACK_SEQUENCE, n);
3117 }
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003118 VISIT_SEQ(c, expr, e->v.Tuple.elts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003119 if (e->v.Tuple.ctx == Load) {
3120 ADDOP_I(c, BUILD_TUPLE, n);
3121 }
3122 return 1;
3123}
3124
3125static int
3126compiler_compare(struct compiler *c, expr_ty e)
3127{
3128 int i, n;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003129 basicblock *cleanup = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003130
3131 /* XXX the logic can be cleaned up for 1 or multiple comparisons */
3132 VISIT(c, expr, e->v.Compare.left);
3133 n = asdl_seq_LEN(e->v.Compare.ops);
3134 assert(n > 0);
3135 if (n > 1) {
3136 cleanup = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003137 if (cleanup == NULL)
3138 return 0;
Anthony Baxter7b782b62006-04-11 12:01:56 +00003139 VISIT(c, expr,
3140 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003141 }
3142 for (i = 1; i < n; i++) {
3143 ADDOP(c, DUP_TOP);
3144 ADDOP(c, ROT_THREE);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003146 cmpop((cmpop_ty)(asdl_seq_GET(
Skip Montanaro869bacd2006-04-13 09:48:28 +00003147 e->v.Compare.ops, i - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 ADDOP_JREL(c, JUMP_IF_FALSE, cleanup);
3149 NEXT_BLOCK(c);
3150 ADDOP(c, POP_TOP);
3151 if (i < (n - 1))
Anthony Baxter7b782b62006-04-11 12:01:56 +00003152 VISIT(c, expr,
3153 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003154 }
Anthony Baxter7b782b62006-04-11 12:01:56 +00003155 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003156 ADDOP_I(c, COMPARE_OP,
Martin v. Löwis0cc56e52006-04-13 12:29:43 +00003157 cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003158 if (n > 1) {
3159 basicblock *end = compiler_new_block(c);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003160 if (end == NULL)
3161 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003162 ADDOP_JREL(c, JUMP_FORWARD, end);
3163 compiler_use_next_block(c, cleanup);
3164 ADDOP(c, ROT_TWO);
3165 ADDOP(c, POP_TOP);
3166 compiler_use_next_block(c, end);
3167 }
3168 return 1;
3169}
Anthony Baxterd691f1a2006-04-13 01:23:28 +00003170#undef CMPCAST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003171
3172static int
3173compiler_call(struct compiler *c, expr_ty e)
3174{
3175 int n, code = 0;
3176
3177 VISIT(c, expr, e->v.Call.func);
3178 n = asdl_seq_LEN(e->v.Call.args);
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003179 VISIT_SEQ(c, expr, e->v.Call.args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003180 if (e->v.Call.keywords) {
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003181 VISIT_SEQ(c, keyword, e->v.Call.keywords);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003182 n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
3183 }
3184 if (e->v.Call.starargs) {
3185 VISIT(c, expr, e->v.Call.starargs);
3186 code |= 1;
3187 }
3188 if (e->v.Call.kwargs) {
3189 VISIT(c, expr, e->v.Call.kwargs);
3190 code |= 2;
3191 }
3192 switch (code) {
3193 case 0:
3194 ADDOP_I(c, CALL_FUNCTION, n);
3195 break;
3196 case 1:
3197 ADDOP_I(c, CALL_FUNCTION_VAR, n);
3198 break;
3199 case 2:
3200 ADDOP_I(c, CALL_FUNCTION_KW, n);
3201 break;
3202 case 3:
3203 ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
3204 break;
3205 }
3206 return 1;
3207}
3208
3209static int
3210compiler_listcomp_generator(struct compiler *c, PyObject *tmpname,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003211 asdl_seq *generators, int gen_index,
3212 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003213{
3214 /* generate code for the iterator, then each of the ifs,
3215 and then write to the element */
3216
3217 comprehension_ty l;
3218 basicblock *start, *anchor, *skip, *if_cleanup;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003219 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
3221 start = compiler_new_block(c);
3222 skip = compiler_new_block(c);
3223 if_cleanup = compiler_new_block(c);
3224 anchor = compiler_new_block(c);
3225
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003226 if (start == NULL || skip == NULL || if_cleanup == NULL ||
3227 anchor == NULL)
3228 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003229
Anthony Baxter7b782b62006-04-11 12:01:56 +00003230 l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003231 VISIT(c, expr, l->iter);
3232 ADDOP(c, GET_ITER);
3233 compiler_use_next_block(c, start);
3234 ADDOP_JREL(c, FOR_ITER, anchor);
3235 NEXT_BLOCK(c);
3236 VISIT(c, expr, l->target);
3237
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003238 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003239 n = asdl_seq_LEN(l->ifs);
3240 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003241 expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242 VISIT(c, expr, e);
3243 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3244 NEXT_BLOCK(c);
3245 ADDOP(c, POP_TOP);
3246 }
3247
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003248 if (++gen_index < asdl_seq_LEN(generators))
3249 if (!compiler_listcomp_generator(c, tmpname,
3250 generators, gen_index, elt))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003251 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003253 /* only append after the last for generator */
3254 if (gen_index >= asdl_seq_LEN(generators)) {
3255 if (!compiler_nameop(c, tmpname, Load))
3256 return 0;
3257 VISIT(c, expr, elt);
Neal Norwitz10be2ea2006-03-03 20:29:11 +00003258 ADDOP(c, LIST_APPEND);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003259
3260 compiler_use_next_block(c, skip);
3261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262 for (i = 0; i < n; i++) {
3263 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003264 if (i == 0)
3265 compiler_use_next_block(c, if_cleanup);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003266 ADDOP(c, POP_TOP);
3267 }
3268 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3269 compiler_use_next_block(c, anchor);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003270 /* delete the append method added to locals */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271 if (gen_index == 1)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003272 if (!compiler_nameop(c, tmpname, Del))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273 return 0;
3274
3275 return 1;
3276}
3277
3278static int
3279compiler_listcomp(struct compiler *c, expr_ty e)
3280{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003281 identifier tmp;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003282 int rc = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283 static identifier append;
3284 asdl_seq *generators = e->v.ListComp.generators;
3285
3286 assert(e->kind == ListComp_kind);
3287 if (!append) {
3288 append = PyString_InternFromString("append");
3289 if (!append)
3290 return 0;
3291 }
Guido van Rossumc2e20742006-02-27 22:32:47 +00003292 tmp = compiler_new_tmpname(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003293 if (!tmp)
3294 return 0;
3295 ADDOP_I(c, BUILD_LIST, 0);
3296 ADDOP(c, DUP_TOP);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297 if (compiler_nameop(c, tmp, Store))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003298 rc = compiler_listcomp_generator(c, tmp, generators, 0,
3299 e->v.ListComp.elt);
3300 Py_DECREF(tmp);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301 return rc;
3302}
3303
3304static int
3305compiler_genexp_generator(struct compiler *c,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003306 asdl_seq *generators, int gen_index,
3307 expr_ty elt)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308{
3309 /* generate code for the iterator, then each of the ifs,
3310 and then write to the element */
3311
3312 comprehension_ty ge;
3313 basicblock *start, *anchor, *skip, *if_cleanup, *end;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003314 int i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003315
3316 start = compiler_new_block(c);
3317 skip = compiler_new_block(c);
3318 if_cleanup = compiler_new_block(c);
3319 anchor = compiler_new_block(c);
3320 end = compiler_new_block(c);
3321
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003322 if (start == NULL || skip == NULL || if_cleanup == NULL ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003323 anchor == NULL || end == NULL)
3324 return 0;
3325
Anthony Baxter7b782b62006-04-11 12:01:56 +00003326 ge = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003327 ADDOP_JREL(c, SETUP_LOOP, end);
3328 if (!compiler_push_fblock(c, LOOP, start))
3329 return 0;
3330
3331 if (gen_index == 0) {
3332 /* Receive outermost iter as an implicit argument */
3333 c->u->u_argcount = 1;
3334 ADDOP_I(c, LOAD_FAST, 0);
3335 }
3336 else {
3337 /* Sub-iter - calculate on the fly */
3338 VISIT(c, expr, ge->iter);
3339 ADDOP(c, GET_ITER);
3340 }
3341 compiler_use_next_block(c, start);
3342 ADDOP_JREL(c, FOR_ITER, anchor);
3343 NEXT_BLOCK(c);
3344 VISIT(c, expr, ge->target);
3345
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003346 /* XXX this needs to be cleaned up...a lot! */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003347 n = asdl_seq_LEN(ge->ifs);
3348 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00003349 expr_ty e = (expr_ty)asdl_seq_GET(ge->ifs, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003350 VISIT(c, expr, e);
3351 ADDOP_JREL(c, JUMP_IF_FALSE, if_cleanup);
3352 NEXT_BLOCK(c);
3353 ADDOP(c, POP_TOP);
3354 }
3355
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003356 if (++gen_index < asdl_seq_LEN(generators))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357 if (!compiler_genexp_generator(c, generators, gen_index, elt))
3358 return 0;
3359
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003360 /* only append after the last 'for' generator */
3361 if (gen_index >= asdl_seq_LEN(generators)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362 VISIT(c, expr, elt);
3363 ADDOP(c, YIELD_VALUE);
3364 ADDOP(c, POP_TOP);
3365
3366 compiler_use_next_block(c, skip);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003367 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003368 for (i = 0; i < n; i++) {
3369 ADDOP_I(c, JUMP_FORWARD, 1);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003370 if (i == 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003371 compiler_use_next_block(c, if_cleanup);
3372
3373 ADDOP(c, POP_TOP);
3374 }
3375 ADDOP_JABS(c, JUMP_ABSOLUTE, start);
3376 compiler_use_next_block(c, anchor);
3377 ADDOP(c, POP_BLOCK);
3378 compiler_pop_fblock(c, LOOP, start);
3379 compiler_use_next_block(c, end);
3380
3381 return 1;
3382}
3383
3384static int
3385compiler_genexp(struct compiler *c, expr_ty e)
3386{
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003387 static identifier name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003388 PyCodeObject *co;
3389 expr_ty outermost_iter = ((comprehension_ty)
3390 (asdl_seq_GET(e->v.GeneratorExp.generators,
3391 0)))->iter;
3392
Nick Coghlan944d3eb2005-11-16 12:46:55 +00003393 if (!name) {
3394 name = PyString_FromString("<genexpr>");
3395 if (!name)
3396 return 0;
3397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398
3399 if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
3400 return 0;
3401 compiler_genexp_generator(c, e->v.GeneratorExp.generators, 0,
3402 e->v.GeneratorExp.elt);
3403 co = assemble(c, 1);
Neil Schemenauerc396d9e2005-10-25 06:30:14 +00003404 compiler_exit_scope(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003405 if (co == NULL)
3406 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003407
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003408 compiler_make_closure(c, co, 0);
Neal Norwitz4737b232005-11-19 23:58:29 +00003409 Py_DECREF(co);
3410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003411 VISIT(c, expr, outermost_iter);
3412 ADDOP(c, GET_ITER);
3413 ADDOP_I(c, CALL_FUNCTION, 1);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003414
3415 return 1;
3416}
3417
3418static int
3419compiler_visit_keyword(struct compiler *c, keyword_ty k)
3420{
3421 ADDOP_O(c, LOAD_CONST, k->arg, consts);
3422 VISIT(c, expr, k->value);
3423 return 1;
3424}
3425
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003426/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003427 whether they are true or false.
3428
3429 Return values: 1 for true, 0 for false, -1 for non-constant.
3430 */
3431
3432static int
3433expr_constant(expr_ty e)
3434{
3435 switch (e->kind) {
3436 case Num_kind:
3437 return PyObject_IsTrue(e->v.Num.n);
3438 case Str_kind:
3439 return PyObject_IsTrue(e->v.Str.s);
Georg Brandlddbaa662006-06-04 21:56:52 +00003440 case Name_kind:
3441 /* __debug__ is not assignable, so we can optimize
3442 * it away in if and while statements */
3443 if (strcmp(PyString_AS_STRING(e->v.Name.id),
3444 "__debug__") == 0)
3445 return ! Py_OptimizeFlag;
3446 /* fall through */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003447 default:
3448 return -1;
3449 }
3450}
3451
Guido van Rossumc2e20742006-02-27 22:32:47 +00003452/*
3453 Implements the with statement from PEP 343.
3454
3455 The semantics outlined in that PEP are as follows:
3456
3457 with EXPR as VAR:
3458 BLOCK
3459
3460 It is implemented roughly as:
3461
Guido van Rossumda5b7012006-05-02 19:47:52 +00003462 context = EXPR
Guido van Rossumc2e20742006-02-27 22:32:47 +00003463 exit = context.__exit__ # not calling it
3464 value = context.__enter__()
3465 try:
3466 VAR = value # if VAR present in the syntax
3467 BLOCK
3468 finally:
3469 if an exception was raised:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003470 exc = copy of (exception, instance, traceback)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003471 else:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003472 exc = (None, None, None)
Guido van Rossumc2e20742006-02-27 22:32:47 +00003473 exit(*exc)
3474 */
3475static int
3476compiler_with(struct compiler *c, stmt_ty s)
3477{
Guido van Rossumda5b7012006-05-02 19:47:52 +00003478 static identifier enter_attr, exit_attr;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003479 basicblock *block, *finally;
3480 identifier tmpexit, tmpvalue = NULL;
3481
3482 assert(s->kind == With_kind);
3483
Guido van Rossumc2e20742006-02-27 22:32:47 +00003484 if (!enter_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003485 enter_attr = PyString_InternFromString("__enter__");
3486 if (!enter_attr)
3487 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003488 }
3489 if (!exit_attr) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003490 exit_attr = PyString_InternFromString("__exit__");
3491 if (!exit_attr)
3492 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003493 }
3494
3495 block = compiler_new_block(c);
3496 finally = compiler_new_block(c);
3497 if (!block || !finally)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003498 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003499
3500 /* Create a temporary variable to hold context.__exit__ */
3501 tmpexit = compiler_new_tmpname(c);
3502 if (tmpexit == NULL)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003503 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003504 PyArena_AddPyObject(c->c_arena, tmpexit);
3505
3506 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003507 /* Create a temporary variable to hold context.__enter__().
Guido van Rossumc2e20742006-02-27 22:32:47 +00003508 We need to do this rather than preserving it on the stack
3509 because SETUP_FINALLY remembers the stack level.
3510 We need to do the assignment *inside* the try/finally
3511 so that context.__exit__() is called when the assignment
3512 fails. But we need to call context.__enter__() *before*
3513 the try/finally so that if it fails we won't call
3514 context.__exit__().
3515 */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003516 tmpvalue = compiler_new_tmpname(c);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003517 if (tmpvalue == NULL)
3518 return 0;
3519 PyArena_AddPyObject(c->c_arena, tmpvalue);
3520 }
3521
Guido van Rossumda5b7012006-05-02 19:47:52 +00003522 /* Evaluate EXPR */
Guido van Rossumc2e20742006-02-27 22:32:47 +00003523 VISIT(c, expr, s->v.With.context_expr);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003524
3525 /* Squirrel away context.__exit__ */
3526 ADDOP(c, DUP_TOP);
3527 ADDOP_O(c, LOAD_ATTR, exit_attr, names);
3528 if (!compiler_nameop(c, tmpexit, Store))
3529 return 0;
3530
3531 /* Call context.__enter__() */
3532 ADDOP_O(c, LOAD_ATTR, enter_attr, names);
3533 ADDOP_I(c, CALL_FUNCTION, 0);
3534
3535 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003536 /* Store it in tmpvalue */
3537 if (!compiler_nameop(c, tmpvalue, Store))
Guido van Rossumc2e20742006-02-27 22:32:47 +00003538 return 0;
3539 }
3540 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003541 /* Discard result from context.__enter__() */
3542 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003543 }
3544
3545 /* Start the try block */
3546 ADDOP_JREL(c, SETUP_FINALLY, finally);
3547
3548 compiler_use_next_block(c, block);
3549 if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003550 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003551 }
3552
3553 if (s->v.With.optional_vars) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003554 /* Bind saved result of context.__enter__() to VAR */
3555 if (!compiler_nameop(c, tmpvalue, Load) ||
Guido van Rossumc2e20742006-02-27 22:32:47 +00003556 !compiler_nameop(c, tmpvalue, Del))
3557 return 0;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003558 VISIT(c, expr, s->v.With.optional_vars);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003559 }
3560
3561 /* BLOCK code */
Anthony Baxter2c33fc72006-04-12 00:43:09 +00003562 VISIT_SEQ(c, stmt, s->v.With.body);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003563
3564 /* End of try block; start the finally block */
3565 ADDOP(c, POP_BLOCK);
3566 compiler_pop_fblock(c, FINALLY_TRY, block);
3567
3568 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3569 compiler_use_next_block(c, finally);
3570 if (!compiler_push_fblock(c, FINALLY_END, finally))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003571 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003572
3573 /* Finally block starts; push tmpexit and issue our magic opcode. */
3574 if (!compiler_nameop(c, tmpexit, Load) ||
3575 !compiler_nameop(c, tmpexit, Del))
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003576 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00003577 ADDOP(c, WITH_CLEANUP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00003578
3579 /* Finally block ends. */
3580 ADDOP(c, END_FINALLY);
3581 compiler_pop_fblock(c, FINALLY_END, finally);
3582 return 1;
3583}
3584
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585static int
3586compiler_visit_expr(struct compiler *c, expr_ty e)
3587{
3588 int i, n;
3589
Jeremy Hylton12603c42006-04-01 16:18:02 +00003590 /* If expr e has a different line number than the last expr/stmt,
3591 set a new line number for the next instruction.
3592 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593 if (e->lineno > c->u->u_lineno) {
3594 c->u->u_lineno = e->lineno;
3595 c->u->u_lineno_set = false;
3596 }
3597 switch (e->kind) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003598 case BoolOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003599 return compiler_boolop(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003600 case BinOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601 VISIT(c, expr, e->v.BinOp.left);
3602 VISIT(c, expr, e->v.BinOp.right);
3603 ADDOP(c, binop(c, e->v.BinOp.op));
3604 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003605 case UnaryOp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003606 VISIT(c, expr, e->v.UnaryOp.operand);
3607 ADDOP(c, unaryop(e->v.UnaryOp.op));
3608 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003609 case Lambda_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610 return compiler_lambda(c, e);
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00003611 case IfExp_kind:
3612 return compiler_ifexp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003613 case Dict_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003614 /* XXX get rid of arg? */
3615 ADDOP_I(c, BUILD_MAP, 0);
3616 n = asdl_seq_LEN(e->v.Dict.values);
3617 /* We must arrange things just right for STORE_SUBSCR.
3618 It wants the stack to look like (value) (dict) (key) */
3619 for (i = 0; i < n; i++) {
3620 ADDOP(c, DUP_TOP);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003621 VISIT(c, expr,
3622 (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623 ADDOP(c, ROT_TWO);
Anthony Baxter7b782b62006-04-11 12:01:56 +00003624 VISIT(c, expr,
3625 (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626 ADDOP(c, STORE_SUBSCR);
3627 }
3628 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003629 case ListComp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630 return compiler_listcomp(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003631 case GeneratorExp_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003632 return compiler_genexp(c, e);
3633 case Yield_kind:
3634 if (c->u->u_ste->ste_type != FunctionBlock)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003635 return compiler_error(c, "'yield' outside function");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003636 /*
3637 for (i = 0; i < c->u->u_nfblocks; i++) {
3638 if (c->u->u_fblock[i].fb_type == FINALLY_TRY)
3639 return compiler_error(
3640 c, "'yield' not allowed in a 'try' "
3641 "block with a 'finally' clause");
3642 }
3643 */
3644 if (e->v.Yield.value) {
3645 VISIT(c, expr, e->v.Yield.value);
3646 }
3647 else {
3648 ADDOP_O(c, LOAD_CONST, Py_None, consts);
3649 }
3650 ADDOP(c, YIELD_VALUE);
3651 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003652 case Compare_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653 return compiler_compare(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003654 case Call_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655 return compiler_call(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003656 case Repr_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657 VISIT(c, expr, e->v.Repr.value);
3658 ADDOP(c, UNARY_CONVERT);
3659 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003660 case Num_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661 ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
3662 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003663 case Str_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003664 ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
3665 break;
3666 /* The following exprs can be assignment targets. */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003667 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668 if (e->v.Attribute.ctx != AugStore)
3669 VISIT(c, expr, e->v.Attribute.value);
3670 switch (e->v.Attribute.ctx) {
3671 case AugLoad:
3672 ADDOP(c, DUP_TOP);
3673 /* Fall through to load */
3674 case Load:
3675 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
3676 break;
3677 case AugStore:
3678 ADDOP(c, ROT_TWO);
3679 /* Fall through to save */
3680 case Store:
3681 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
3682 break;
3683 case Del:
3684 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
3685 break;
3686 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003687 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003688 PyErr_SetString(PyExc_SystemError,
3689 "param invalid in attribute expression");
3690 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003691 }
3692 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003693 case Subscript_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003694 switch (e->v.Subscript.ctx) {
3695 case AugLoad:
3696 VISIT(c, expr, e->v.Subscript.value);
3697 VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
3698 break;
3699 case Load:
3700 VISIT(c, expr, e->v.Subscript.value);
3701 VISIT_SLICE(c, e->v.Subscript.slice, Load);
3702 break;
3703 case AugStore:
3704 VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
3705 break;
3706 case Store:
3707 VISIT(c, expr, e->v.Subscript.value);
3708 VISIT_SLICE(c, e->v.Subscript.slice, Store);
3709 break;
3710 case Del:
3711 VISIT(c, expr, e->v.Subscript.value);
3712 VISIT_SLICE(c, e->v.Subscript.slice, Del);
3713 break;
3714 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003715 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003716 PyErr_SetString(PyExc_SystemError,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003717 "param invalid in subscript expression");
Neal Norwitz4737b232005-11-19 23:58:29 +00003718 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003719 }
3720 break;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003721 case Name_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003722 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
3723 /* child nodes of List and Tuple will have expr_context set */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003724 case List_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003725 return compiler_list(c, e);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003726 case Tuple_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003727 return compiler_tuple(c, e);
3728 }
3729 return 1;
3730}
3731
3732static int
3733compiler_augassign(struct compiler *c, stmt_ty s)
3734{
3735 expr_ty e = s->v.AugAssign.target;
3736 expr_ty auge;
3737
3738 assert(s->kind == AugAssign_kind);
3739
3740 switch (e->kind) {
Neal Norwitz2585ad52006-06-12 02:09:34 +00003741 case Attribute_kind:
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003742 auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003743 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003744 if (auge == NULL)
3745 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003746 VISIT(c, expr, auge);
3747 VISIT(c, expr, s->v.AugAssign.value);
3748 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3749 auge->v.Attribute.ctx = AugStore;
3750 VISIT(c, expr, auge);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003751 break;
3752 case Subscript_kind:
3753 auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
Martin v. Löwis49c5da12006-03-01 22:49:05 +00003754 AugLoad, e->lineno, e->col_offset, c->c_arena);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003755 if (auge == NULL)
3756 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003757 VISIT(c, expr, auge);
3758 VISIT(c, expr, s->v.AugAssign.value);
3759 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003760 auge->v.Subscript.ctx = AugStore;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761 VISIT(c, expr, auge);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003762 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003763 case Name_kind:
Neil Schemenauer0e07b602006-07-09 16:16:34 +00003764 if (!compiler_nameop(c, e->v.Name.id, Load))
3765 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766 VISIT(c, expr, s->v.AugAssign.value);
3767 ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
3768 return compiler_nameop(c, e->v.Name.id, Store);
3769 default:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003770 PyErr_Format(PyExc_SystemError,
3771 "invalid node type (%d) for augmented assignment",
3772 e->kind);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003773 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003774 }
3775 return 1;
3776}
3777
3778static int
3779compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3780{
3781 struct fblockinfo *f;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003782 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
3783 PyErr_SetString(PyExc_SystemError,
3784 "too many statically nested blocks");
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003785 return 0;
Neal Norwitz2f0940b2006-10-28 21:38:43 +00003786 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003787 f = &c->u->u_fblock[c->u->u_nfblocks++];
3788 f->fb_type = t;
3789 f->fb_block = b;
3790 return 1;
3791}
3792
3793static void
3794compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
3795{
3796 struct compiler_unit *u = c->u;
3797 assert(u->u_nfblocks > 0);
3798 u->u_nfblocks--;
3799 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
3800 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
3801}
3802
Georg Brandla5fe3ef2006-10-08 07:12:23 +00003803static int
3804compiler_in_loop(struct compiler *c) {
3805 int i;
3806 struct compiler_unit *u = c->u;
3807 for (i = 0; i < u->u_nfblocks; ++i) {
3808 if (u->u_fblock[i].fb_type == LOOP)
3809 return 1;
3810 }
3811 return 0;
3812}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003813/* Raises a SyntaxError and returns 0.
3814 If something goes wrong, a different exception may be raised.
3815*/
3816
3817static int
3818compiler_error(struct compiler *c, const char *errstr)
3819{
3820 PyObject *loc;
3821 PyObject *u = NULL, *v = NULL;
3822
3823 loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
3824 if (!loc) {
3825 Py_INCREF(Py_None);
3826 loc = Py_None;
3827 }
3828 u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
3829 Py_None, loc);
3830 if (!u)
3831 goto exit;
3832 v = Py_BuildValue("(zO)", errstr, u);
3833 if (!v)
3834 goto exit;
3835 PyErr_SetObject(PyExc_SyntaxError, v);
3836 exit:
3837 Py_DECREF(loc);
3838 Py_XDECREF(u);
3839 Py_XDECREF(v);
3840 return 0;
3841}
3842
3843static int
3844compiler_handle_subscr(struct compiler *c, const char *kind,
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003845 expr_context_ty ctx)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003846{
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003847 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003848
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003849 /* XXX this code is duplicated */
3850 switch (ctx) {
3851 case AugLoad: /* fall through to Load */
3852 case Load: op = BINARY_SUBSCR; break;
3853 case AugStore:/* fall through to Store */
3854 case Store: op = STORE_SUBSCR; break;
3855 case Del: op = DELETE_SUBSCR; break;
3856 case Param:
3857 PyErr_Format(PyExc_SystemError,
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003858 "invalid %s kind %d in subscript\n",
3859 kind, ctx);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003860 return 0;
3861 }
3862 if (ctx == AugLoad) {
3863 ADDOP_I(c, DUP_TOPX, 2);
3864 }
3865 else if (ctx == AugStore) {
3866 ADDOP(c, ROT_THREE);
3867 }
3868 ADDOP(c, op);
3869 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003870}
3871
3872static int
3873compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3874{
3875 int n = 2;
3876 assert(s->kind == Slice_kind);
3877
3878 /* only handles the cases where BUILD_SLICE is emitted */
3879 if (s->v.Slice.lower) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003880 VISIT(c, expr, s->v.Slice.lower);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003881 }
3882 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003883 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003884 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003886 if (s->v.Slice.upper) {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003887 VISIT(c, expr, s->v.Slice.upper);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003888 }
3889 else {
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003890 ADDOP_O(c, LOAD_CONST, Py_None, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003891 }
3892
3893 if (s->v.Slice.step) {
3894 n++;
3895 VISIT(c, expr, s->v.Slice.step);
3896 }
3897 ADDOP_I(c, BUILD_SLICE, n);
3898 return 1;
3899}
3900
3901static int
3902compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3903{
3904 int op = 0, slice_offset = 0, stack_count = 0;
3905
3906 assert(s->v.Slice.step == NULL);
3907 if (s->v.Slice.lower) {
3908 slice_offset++;
3909 stack_count++;
3910 if (ctx != AugStore)
3911 VISIT(c, expr, s->v.Slice.lower);
3912 }
3913 if (s->v.Slice.upper) {
3914 slice_offset += 2;
3915 stack_count++;
3916 if (ctx != AugStore)
3917 VISIT(c, expr, s->v.Slice.upper);
3918 }
3919
Jeremy Hyltone9357b22006-03-01 15:47:05 +00003920 if (ctx == AugLoad) {
3921 switch (stack_count) {
3922 case 0: ADDOP(c, DUP_TOP); break;
3923 case 1: ADDOP_I(c, DUP_TOPX, 2); break;
3924 case 2: ADDOP_I(c, DUP_TOPX, 3); break;
3925 }
3926 }
3927 else if (ctx == AugStore) {
3928 switch (stack_count) {
3929 case 0: ADDOP(c, ROT_TWO); break;
3930 case 1: ADDOP(c, ROT_THREE); break;
3931 case 2: ADDOP(c, ROT_FOUR); break;
3932 }
3933 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934
3935 switch (ctx) {
3936 case AugLoad: /* fall through to Load */
3937 case Load: op = SLICE; break;
3938 case AugStore:/* fall through to Store */
3939 case Store: op = STORE_SLICE; break;
3940 case Del: op = DELETE_SLICE; break;
Neal Norwitz4737b232005-11-19 23:58:29 +00003941 case Param:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003942 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003943 PyErr_SetString(PyExc_SystemError,
3944 "param invalid in simple slice");
3945 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946 }
3947
3948 ADDOP(c, op + slice_offset);
3949 return 1;
3950}
3951
3952static int
3953compiler_visit_nested_slice(struct compiler *c, slice_ty s,
3954 expr_context_ty ctx)
3955{
3956 switch (s->kind) {
3957 case Ellipsis_kind:
3958 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3959 break;
3960 case Slice_kind:
3961 return compiler_slice(c, s, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003962 case Index_kind:
3963 VISIT(c, expr, s->v.Index.value);
3964 break;
3965 case ExtSlice_kind:
Neal Norwitz4e6bf492005-12-18 05:32:41 +00003966 default:
Neal Norwitz4737b232005-11-19 23:58:29 +00003967 PyErr_SetString(PyExc_SystemError,
3968 "extended slice invalid in nested slice");
3969 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003970 }
3971 return 1;
3972}
3973
3974
3975static int
3976compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
3977{
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003978 char * kindname = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003979 switch (s->kind) {
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003980 case Index_kind:
3981 kindname = "index";
3982 if (ctx != AugStore) {
3983 VISIT(c, expr, s->v.Index.value);
3984 }
3985 break;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003986 case Ellipsis_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003987 kindname = "ellipsis";
3988 if (ctx != AugStore) {
3989 ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
3990 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003991 break;
3992 case Slice_kind:
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003993 kindname = "slice";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003994 if (!s->v.Slice.step)
3995 return compiler_simple_slice(c, s, ctx);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00003996 if (ctx != AugStore) {
3997 if (!compiler_slice(c, s, ctx))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003998 return 0;
3999 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004000 break;
4001 case ExtSlice_kind:
4002 kindname = "extended slice";
4003 if (ctx != AugStore) {
4004 int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
4005 for (i = 0; i < n; i++) {
Anthony Baxter7b782b62006-04-11 12:01:56 +00004006 slice_ty sub = (slice_ty)asdl_seq_GET(
4007 s->v.ExtSlice.dims, i);
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004008 if (!compiler_visit_nested_slice(c, sub, ctx))
4009 return 0;
4010 }
4011 ADDOP_I(c, BUILD_TUPLE, n);
4012 }
4013 break;
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004014 default:
4015 PyErr_Format(PyExc_SystemError,
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004016 "invalid subscript kind %d", s->kind);
Neal Norwitz4e6bf492005-12-18 05:32:41 +00004017 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004018 }
Nick Coghlaneadee9a2006-03-13 12:31:58 +00004019 return compiler_handle_subscr(c, kindname, ctx);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004020}
4021
4022/* do depth-first search of basic block graph, starting with block.
4023 post records the block indices in post-order.
4024
4025 XXX must handle implicit jumps from one block to next
4026*/
4027
4028static void
4029dfs(struct compiler *c, basicblock *b, struct assembler *a)
4030{
4031 int i;
4032 struct instr *instr = NULL;
4033
4034 if (b->b_seen)
4035 return;
4036 b->b_seen = 1;
4037 if (b->b_next != NULL)
4038 dfs(c, b->b_next, a);
4039 for (i = 0; i < b->b_iused; i++) {
4040 instr = &b->b_instr[i];
4041 if (instr->i_jrel || instr->i_jabs)
4042 dfs(c, instr->i_target, a);
4043 }
4044 a->a_postorder[a->a_nblocks++] = b;
4045}
4046
Neal Norwitz2744c6c2005-11-13 01:08:38 +00004047static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004048stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
4049{
4050 int i;
4051 struct instr *instr;
4052 if (b->b_seen || b->b_startdepth >= depth)
4053 return maxdepth;
4054 b->b_seen = 1;
4055 b->b_startdepth = depth;
4056 for (i = 0; i < b->b_iused; i++) {
4057 instr = &b->b_instr[i];
4058 depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
4059 if (depth > maxdepth)
4060 maxdepth = depth;
4061 assert(depth >= 0); /* invalid code or bug in stackdepth() */
4062 if (instr->i_jrel || instr->i_jabs) {
4063 maxdepth = stackdepth_walk(c, instr->i_target,
4064 depth, maxdepth);
4065 if (instr->i_opcode == JUMP_ABSOLUTE ||
4066 instr->i_opcode == JUMP_FORWARD) {
4067 goto out; /* remaining code is dead */
4068 }
4069 }
4070 }
4071 if (b->b_next)
4072 maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
4073out:
4074 b->b_seen = 0;
4075 return maxdepth;
4076}
4077
4078/* Find the flow path that needs the largest stack. We assume that
4079 * cycles in the flow graph have no net effect on the stack depth.
4080 */
4081static int
4082stackdepth(struct compiler *c)
4083{
4084 basicblock *b, *entryblock;
4085 entryblock = NULL;
4086 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4087 b->b_seen = 0;
4088 b->b_startdepth = INT_MIN;
4089 entryblock = b;
4090 }
Neal Norwitzf71847e2006-07-23 07:51:58 +00004091 if (!entryblock)
4092 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004093 return stackdepth_walk(c, entryblock, 0, 0);
4094}
4095
4096static int
4097assemble_init(struct assembler *a, int nblocks, int firstlineno)
4098{
4099 memset(a, 0, sizeof(struct assembler));
4100 a->a_lineno = firstlineno;
4101 a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
4102 if (!a->a_bytecode)
4103 return 0;
4104 a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
4105 if (!a->a_lnotab)
4106 return 0;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004107 if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
4108 PyErr_NoMemory();
4109 return 0;
4110 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004111 a->a_postorder = (basicblock **)PyObject_Malloc(
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004112 sizeof(basicblock *) * nblocks);
Neal Norwitz87b801c2005-12-18 04:42:47 +00004113 if (!a->a_postorder) {
4114 PyErr_NoMemory();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004115 return 0;
Neal Norwitz87b801c2005-12-18 04:42:47 +00004116 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117 return 1;
4118}
4119
4120static void
4121assemble_free(struct assembler *a)
4122{
4123 Py_XDECREF(a->a_bytecode);
4124 Py_XDECREF(a->a_lnotab);
4125 if (a->a_postorder)
4126 PyObject_Free(a->a_postorder);
4127}
4128
4129/* Return the size of a basic block in bytes. */
4130
4131static int
4132instrsize(struct instr *instr)
4133{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004134 if (!instr->i_hasarg)
4135 return 1;
4136 if (instr->i_oparg > 0xffff)
4137 return 6;
4138 return 3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004139}
4140
4141static int
4142blocksize(basicblock *b)
4143{
4144 int i;
4145 int size = 0;
4146
4147 for (i = 0; i < b->b_iused; i++)
4148 size += instrsize(&b->b_instr[i]);
4149 return size;
4150}
4151
4152/* All about a_lnotab.
4153
4154c_lnotab is an array of unsigned bytes disguised as a Python string.
4155It is used to map bytecode offsets to source code line #s (when needed
4156for tracebacks).
Michael W. Hudsondd32a912002-08-15 14:59:02 +00004157
Tim Peters2a7f3842001-06-09 09:26:21 +00004158The array is conceptually a list of
4159 (bytecode offset increment, line number increment)
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004160pairs. The details are important and delicate, best illustrated by example:
Tim Peters2a7f3842001-06-09 09:26:21 +00004161
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004162 byte code offset source code line number
4163 0 1
4164 6 2
Tim Peters2a7f3842001-06-09 09:26:21 +00004165 50 7
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004166 350 307
4167 361 308
Tim Peters2a7f3842001-06-09 09:26:21 +00004168
4169The first trick is that these numbers aren't stored, only the increments
4170from one row to the next (this doesn't really work, but it's a start):
4171
4172 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
4173
4174The second trick is that an unsigned byte can't hold negative values, or
4175values larger than 255, so (a) there's a deep assumption that byte code
4176offsets and their corresponding line #s both increase monotonically, and (b)
4177if at least one column jumps by more than 255 from one row to the next, more
4178than one pair is written to the table. In case #b, there's no way to know
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004179from looking at the table later how many were written. That's the delicate
Tim Peters2a7f3842001-06-09 09:26:21 +00004180part. A user of c_lnotab desiring to find the source line number
4181corresponding to a bytecode address A should do something like this
4182
4183 lineno = addr = 0
4184 for addr_incr, line_incr in c_lnotab:
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004185 addr += addr_incr
4186 if addr > A:
4187 return lineno
4188 lineno += line_incr
Tim Peters2a7f3842001-06-09 09:26:21 +00004189
4190In order for this to work, when the addr field increments by more than 255,
4191the line # increment in each pair generated must be 0 until the remaining addr
Neal Norwitz84be93b2006-07-16 01:50:38 +00004192increment is < 256. So, in the example above, assemble_lnotab (it used
4193to be called com_set_lineno) should not (as was actually done until 2.2)
4194expand 300, 300 to 255, 255, 45, 45,
4195 but to 255, 0, 45, 255, 0, 45.
Tim Peters2a7f3842001-06-09 09:26:21 +00004196*/
4197
Guido van Rossumf68d8e52001-04-14 17:55:09 +00004198static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004199assemble_lnotab(struct assembler *a, struct instr *i)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004200{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004201 int d_bytecode, d_lineno;
4202 int len;
Neal Norwitzb183a252006-04-10 01:03:32 +00004203 unsigned char *lnotab;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004204
4205 d_bytecode = a->a_offset - a->a_lineno_off;
4206 d_lineno = i->i_lineno - a->a_lineno;
4207
4208 assert(d_bytecode >= 0);
4209 assert(d_lineno >= 0);
4210
Amaury Forgeot d'Arcbc212102008-02-04 23:51:55 +00004211 if(d_bytecode == 0 && d_lineno == 0)
4212 return 1;
4213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004214 if (d_bytecode > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004215 int j, nbytes, ncodes = d_bytecode / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004216 nbytes = a->a_lnotab_off + 2 * ncodes;
4217 len = PyString_GET_SIZE(a->a_lnotab);
4218 if (nbytes >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004219 if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004220 len = nbytes;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004221 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222 len *= 2;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004223 else {
4224 PyErr_NoMemory();
4225 return 0;
4226 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004227 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4228 return 0;
Guido van Rossum8b993a91997-01-17 21:04:03 +00004229 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004230 lnotab = (unsigned char *)
4231 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004232 for (j = 0; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004233 *lnotab++ = 255;
4234 *lnotab++ = 0;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004236 d_bytecode -= ncodes * 255;
4237 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004239 assert(d_bytecode <= 255);
4240 if (d_lineno > 255) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004241 int j, nbytes, ncodes = d_lineno / 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004242 nbytes = a->a_lnotab_off + 2 * ncodes;
4243 len = PyString_GET_SIZE(a->a_lnotab);
4244 if (nbytes >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004245 if ((len <= INT_MAX / 2) && len * 2 < nbytes)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004246 len = nbytes;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004247 else if (len <= INT_MAX / 2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004248 len *= 2;
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004249 else {
4250 PyErr_NoMemory();
4251 return 0;
4252 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004253 if (_PyString_Resize(&a->a_lnotab, len) < 0)
4254 return 0;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004255 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004256 lnotab = (unsigned char *)
4257 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004258 *lnotab++ = d_bytecode;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004259 *lnotab++ = 255;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004260 d_bytecode = 0;
Neal Norwitz08b401f2006-01-07 21:24:09 +00004261 for (j = 1; j < ncodes; j++) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004262 *lnotab++ = 0;
Neal Norwitz84be93b2006-07-16 01:50:38 +00004263 *lnotab++ = 255;
Guido van Rossumf10570b1995-07-07 22:53:21 +00004264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004265 d_lineno -= ncodes * 255;
4266 a->a_lnotab_off += ncodes * 2;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004267 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004269 len = PyString_GET_SIZE(a->a_lnotab);
4270 if (a->a_lnotab_off + 2 >= len) {
4271 if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
Tim Peters51e26512001-09-07 08:45:55 +00004272 return 0;
Tim Peters51e26512001-09-07 08:45:55 +00004273 }
Neal Norwitzb183a252006-04-10 01:03:32 +00004274 lnotab = (unsigned char *)
4275 PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00004276
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004277 a->a_lnotab_off += 2;
4278 if (d_bytecode) {
4279 *lnotab++ = d_bytecode;
4280 *lnotab++ = d_lineno;
Jeremy Hyltond5e5a2a2001-08-12 01:54:38 +00004281 }
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004282 else { /* First line of a block; def stmt, etc. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004283 *lnotab++ = 0;
4284 *lnotab++ = d_lineno;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004285 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004286 a->a_lineno = i->i_lineno;
4287 a->a_lineno_off = a->a_offset;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004288 return 1;
4289}
4290
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004291/* assemble_emit()
4292 Extend the bytecode with a new instruction.
4293 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00004294*/
4295
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004296static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004297assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004298{
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004299 int size, arg = 0, ext = 0;
Neal Norwitz2585ad52006-06-12 02:09:34 +00004300 Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004301 char *code;
4302
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004303 size = instrsize(i);
4304 if (i->i_hasarg) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004305 arg = i->i_oparg;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004306 ext = arg >> 16;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004307 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004308 if (i->i_lineno && !assemble_lnotab(a, i))
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004309 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004310 if (a->a_offset + size >= len) {
Martin v. Löwis73c01d42008-02-14 11:26:18 +00004311 if (len > PY_SSIZE_T_MAX / 2)
4312 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004313 if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
Guido van Rossum681d79a1995-07-18 14:51:37 +00004314 return 0;
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00004315 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004316 code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
4317 a->a_offset += size;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004318 if (size == 6) {
4319 assert(i->i_hasarg);
4320 *code++ = (char)EXTENDED_ARG;
4321 *code++ = ext & 0xff;
4322 *code++ = ext >> 8;
4323 arg &= 0xffff;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004324 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004325 *code++ = i->i_opcode;
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004326 if (i->i_hasarg) {
4327 assert(size == 3 || size == 6);
4328 *code++ = arg & 0xff;
4329 *code++ = arg >> 8;
4330 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004331 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004332}
4333
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004334static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004335assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00004336{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004337 basicblock *b;
Neal Norwitzf1d50682005-10-23 23:00:41 +00004338 int bsize, totsize, extended_arg_count, last_extended_arg_count = 0;
Guido van Rossumf1aeab71992-03-27 17:28:26 +00004339 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00004340
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004341 /* Compute the size of each block and fixup jump args.
4342 Replace block pointer with position in bytecode. */
Neal Norwitzf1d50682005-10-23 23:00:41 +00004343start:
4344 totsize = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345 for (i = a->a_nblocks - 1; i >= 0; i--) {
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004346 b = a->a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004347 bsize = blocksize(b);
4348 b->b_offset = totsize;
4349 totsize += bsize;
Guido van Rossum25831651993-05-19 14:50:45 +00004350 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004351 extended_arg_count = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004352 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4353 bsize = b->b_offset;
4354 for (i = 0; i < b->b_iused; i++) {
4355 struct instr *instr = &b->b_instr[i];
4356 /* Relative jumps are computed relative to
4357 the instruction pointer after fetching
4358 the jump instruction.
4359 */
4360 bsize += instrsize(instr);
4361 if (instr->i_jabs)
4362 instr->i_oparg = instr->i_target->b_offset;
4363 else if (instr->i_jrel) {
4364 int delta = instr->i_target->b_offset - bsize;
4365 instr->i_oparg = delta;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004366 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004367 else
4368 continue;
4369 if (instr->i_oparg > 0xffff)
4370 extended_arg_count++;
Guido van Rossum681d79a1995-07-18 14:51:37 +00004371 }
4372 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00004373
4374 /* XXX: This is an awful hack that could hurt performance, but
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004375 on the bright side it should work until we come up
Neal Norwitzf1d50682005-10-23 23:00:41 +00004376 with a better solution.
4377
4378 In the meantime, should the goto be dropped in favor
4379 of a loop?
4380
4381 The issue is that in the first loop blocksize() is called
4382 which calls instrsize() which requires i_oparg be set
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004383 appropriately. There is a bootstrap problem because
Neal Norwitzf1d50682005-10-23 23:00:41 +00004384 i_oparg is calculated in the second loop above.
4385
4386 So we loop until we stop seeing new EXTENDED_ARGs.
4387 The only EXTENDED_ARGs that could be popping up are
4388 ones in jump instructions. So this should converge
4389 fairly quickly.
4390 */
4391 if (last_extended_arg_count != extended_arg_count) {
4392 last_extended_arg_count = extended_arg_count;
4393 goto start;
4394 }
Guido van Rossum10dc2e81990-11-18 17:27:39 +00004395}
4396
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004397static PyObject *
4398dict_keys_inorder(PyObject *dict, int offset)
4399{
4400 PyObject *tuple, *k, *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004401 Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004402
4403 tuple = PyTuple_New(size);
4404 if (tuple == NULL)
4405 return NULL;
4406 while (PyDict_Next(dict, &pos, &k, &v)) {
4407 i = PyInt_AS_LONG(v);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004408 k = PyTuple_GET_ITEM(k, 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004409 Py_INCREF(k);
Jeremy Hyltonce7ef592001-03-20 00:25:43 +00004410 assert((i - offset) < size);
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004411 assert((i - offset) >= 0);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004412 PyTuple_SET_ITEM(tuple, i - offset, k);
4413 }
4414 return tuple;
4415}
4416
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004417static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004419{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004420 PySTEntryObject *ste = c->u->u_ste;
4421 int flags = 0, n;
4422 if (ste->ste_type != ModuleBlock)
4423 flags |= CO_NEWLOCALS;
4424 if (ste->ste_type == FunctionBlock) {
4425 if (!ste->ste_unoptimized)
4426 flags |= CO_OPTIMIZED;
4427 if (ste->ste_nested)
4428 flags |= CO_NESTED;
4429 if (ste->ste_generator)
4430 flags |= CO_GENERATOR;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004431 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004432 if (ste->ste_varargs)
4433 flags |= CO_VARARGS;
4434 if (ste->ste_varkeywords)
4435 flags |= CO_VARKEYWORDS;
Tim Peters5ca576e2001-06-18 22:08:13 +00004436 if (ste->ste_generator)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004437 flags |= CO_GENERATOR;
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004438
4439 /* (Only) inherit compilerflags in PyCF_MASK */
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004440 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00004441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004442 n = PyDict_Size(c->u->u_freevars);
4443 if (n < 0)
4444 return -1;
4445 if (n == 0) {
4446 n = PyDict_Size(c->u->u_cellvars);
4447 if (n < 0)
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004448 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004449 if (n == 0) {
4450 flags |= CO_NOFREE;
4451 }
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004452 }
Jeremy Hyltond7f393e2001-02-12 16:01:03 +00004453
Jeremy Hylton29906ee2001-02-27 04:23:34 +00004454 return flags;
4455}
4456
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004457static PyCodeObject *
4458makecode(struct compiler *c, struct assembler *a)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004459{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004460 PyObject *tmp;
4461 PyCodeObject *co = NULL;
4462 PyObject *consts = NULL;
4463 PyObject *names = NULL;
4464 PyObject *varnames = NULL;
4465 PyObject *filename = NULL;
4466 PyObject *name = NULL;
4467 PyObject *freevars = NULL;
4468 PyObject *cellvars = NULL;
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004469 PyObject *bytecode = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004470 int nlocals, flags;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004471
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004472 tmp = dict_keys_inorder(c->u->u_consts, 0);
4473 if (!tmp)
4474 goto error;
4475 consts = PySequence_List(tmp); /* optimize_code requires a list */
4476 Py_DECREF(tmp);
4477
4478 names = dict_keys_inorder(c->u->u_names, 0);
4479 varnames = dict_keys_inorder(c->u->u_varnames, 0);
4480 if (!consts || !names || !varnames)
4481 goto error;
4482
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004483 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
4484 if (!cellvars)
4485 goto error;
4486 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
4487 if (!freevars)
4488 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004489 filename = PyString_FromString(c->c_filename);
4490 if (!filename)
4491 goto error;
4492
Jeremy Hyltone9357b22006-03-01 15:47:05 +00004493 nlocals = PyDict_Size(c->u->u_varnames);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004494 flags = compute_code_flags(c);
4495 if (flags < 0)
4496 goto error;
4497
4498 bytecode = optimize_code(a->a_bytecode, consts, names, a->a_lnotab);
4499 if (!bytecode)
4500 goto error;
4501
4502 tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
4503 if (!tmp)
4504 goto error;
4505 Py_DECREF(consts);
4506 consts = tmp;
4507
4508 co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
4509 bytecode, consts, names, varnames,
4510 freevars, cellvars,
4511 filename, c->u->u_name,
4512 c->u->u_firstlineno,
4513 a->a_lnotab);
4514 error:
4515 Py_XDECREF(consts);
4516 Py_XDECREF(names);
4517 Py_XDECREF(varnames);
4518 Py_XDECREF(filename);
4519 Py_XDECREF(name);
4520 Py_XDECREF(freevars);
4521 Py_XDECREF(cellvars);
4522 Py_XDECREF(bytecode);
4523 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004524}
4525
Neal Norwitz4ffedad2006-08-04 04:58:47 +00004526
4527/* For debugging purposes only */
4528#if 0
4529static void
4530dump_instr(const struct instr *i)
4531{
4532 const char *jrel = i->i_jrel ? "jrel " : "";
4533 const char *jabs = i->i_jabs ? "jabs " : "";
4534 char arg[128];
4535
4536 *arg = '\0';
4537 if (i->i_hasarg)
4538 sprintf(arg, "arg: %d ", i->i_oparg);
4539
4540 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
4541 i->i_lineno, i->i_opcode, arg, jabs, jrel);
4542}
4543
4544static void
4545dump_basicblock(const basicblock *b)
4546{
4547 const char *seen = b->b_seen ? "seen " : "";
4548 const char *b_return = b->b_return ? "return " : "";
4549 fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
4550 b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
4551 if (b->b_instr) {
4552 int i;
4553 for (i = 0; i < b->b_iused; i++) {
4554 fprintf(stderr, " [%02d] ", i);
4555 dump_instr(b->b_instr + i);
4556 }
4557 }
4558}
4559#endif
4560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004561static PyCodeObject *
4562assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004563{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004564 basicblock *b, *entryblock;
4565 struct assembler a;
4566 int i, j, nblocks;
4567 PyCodeObject *co = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00004568
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004569 /* Make sure every block that falls off the end returns None.
4570 XXX NEXT_BLOCK() isn't quite right, because if the last
4571 block ends with a jump or return b_next shouldn't set.
4572 */
4573 if (!c->u->u_curblock->b_return) {
4574 NEXT_BLOCK(c);
4575 if (addNone)
4576 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4577 ADDOP(c, RETURN_VALUE);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004578 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004579
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004580 nblocks = 0;
4581 entryblock = NULL;
4582 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
4583 nblocks++;
4584 entryblock = b;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004585 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004586
Neal Norwitzed657552006-07-10 00:04:44 +00004587 /* Set firstlineno if it wasn't explicitly set. */
4588 if (!c->u->u_firstlineno) {
4589 if (entryblock && entryblock->b_instr)
4590 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
4591 else
4592 c->u->u_firstlineno = 1;
4593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004594 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
4595 goto error;
4596 dfs(c, entryblock, &a);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004597
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004598 /* Can't modify the bytecode after computing jump offsets. */
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00004599 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00004600
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004601 /* Emit code in reverse postorder from dfs. */
4602 for (i = a.a_nblocks - 1; i >= 0; i--) {
Neal Norwitz08b401f2006-01-07 21:24:09 +00004603 b = a.a_postorder[i];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004604 for (j = 0; j < b->b_iused; j++)
4605 if (!assemble_emit(&a, &b->b_instr[j]))
4606 goto error;
Tim Petersb6c3cea2001-06-26 03:36:28 +00004607 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00004608
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004609 if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
4610 goto error;
4611 if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
4612 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004613
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004614 co = makecode(c, &a);
4615 error:
4616 assemble_free(&a);
4617 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00004618}